Aspose.Words for .NET API Reference

The Aspose.Words class library provides the following namespaces:

Aspose.Words
Contains classes for generating, converting, modifying, rendering and printing Microsoft Word documents without utilizing Microsoft Word.
Aspose.Words.BuildingBlocks
Contains classes that represent the Glossary Document, Building Blocks and AutoText features in Microsoft Word documents.
Aspose.Words.Drawing
Contains classes that allow to create and modify drawing objects in Microsoft Word documents.
Aspose.Words.Drawing.Charts
Contains classes that allow to access DrawingML charts in Microsoft Word documents.
Aspose.Words.Drawing.Ole
Contains classes to work with OLE / ActiveX controls and forms in Microsoft Word documents.
Aspose.Words.Fields
Provides classes to work with Microsoft Word fields and form fields.
Aspose.Words.Fonts
Provides classes and enumerations to access information about fonts used in a document.
Aspose.Words.Layout
Provides classes to access information about how document elements are laid out onto pages.
Aspose.Words.Lists
Contains classes that represent bulleted and numbered lists.
Aspose.Words.Loading
Provides classes and enumerations that allow to specify additional options when loading documents.
Aspose.Words.MailMerging
Contains classes of the original mail merge based reporting engine.
Aspose.Words.Markup
Contains classes that represent custom XML, smart tags and structured document tags (content controls).
Aspose.Words.Math
Contains classes that represent Office Math elements.
Aspose.Words.Properties
Contains classes that provide access to custom and built-in document properties.
Aspose.Words.Rendering
Contains classes to customize printing and rendering of documents.
Aspose.Words.Replacing
Contains classes to customize find/replace operations over the document tree.
Aspose.Words.Reporting
Contains classes of the new reporting engine that supports report templates marked up with a language based on the LINQ Method Syntax.
Aspose.Words.Saving
Provides classes and enums to specify options for saving or converting documents.
Aspose.Words.Settings
Contains classes to specify document-level settings and options.
Aspose.Words.Shaping
Contains classes to provide support for OpenType features using external text shaping engines.
Aspose.Words.Tables
Contains classes to work with tables, rows, cells and their formatting.
Aspose.Words.Themes
Contains classes to access the document's theme.

We guarantee a prompt response to any inquiry!

© 2003-2019 Aspose Pty Ltd. All rights reserved.


Aspose.Words

Aspose.Words Namespace

The Aspose.Words namespace provides classes for generating, converting, modifying, rendering and printing Microsoft Word documents without utilizing Microsoft Word.

Aspose.Words is written completely in C#, CLS compliant and contains only safe managed code. Microsoft Word is not required in order to use Aspose.Words.

The classes in the Aspose.Words namespace borrow best practices from two well-known frameworks: Microsoft Word Automation and System.Xml. A document in Aspose.Words is represented by a tree of nodes, much like in XML DOM. Where possible, class, method and property names match those found in Microsoft Word Automation.

The main classes in this namespace are:

  • Document is the main class of the object model that represents a Microsoft Word document.
  • DocumentBuilder provides an easy way to insert content and formatting into a document.
  • Node is the base class for all nodes in the document.
  • CompositeNode is the base class for all nodes of the document that can contain other nodes, for example Paragraph, Section and Table.

Namespace hierarchy

Classes

Class | Description
AbsolutePositionTab | An absolute position tab is a character which is used to advance the position on the current line of text when displaying this WordprocessingML content.
Body | Represents a container for the main text of a section.
Bookmark | Represents a single bookmark.
BookmarkCollection | A collection of Bookmark objects that represent the bookmarks in the specified range.
BookmarkEnd | Represents an end of a bookmark in a Word document.
BookmarkStart | Represents a start of a bookmark in a Word document.
Border | Represents a border of an object.
BorderCollection | A collection of Border objects.
BuildVersionInfo | Provides information about the current product name and version.
CertificateHolder | Represents a holder of X509Certificate2 instance.
CleanupOptions | Allows to specify options for document cleaning.
ComHelper | Provides methods for COM clients to load a document into Aspose.Words.
Comment | Represents a container for text of a comment.
CommentCollection | Provides typed access to a collection of Comment nodes.
CommentRangeEnd | Denotes the end of a region of text that has a comment associated with it.
CommentRangeStart | Denotes the start of a region of text that has a comment associated with it.
CompareOptions | Allows to choose advanced options for document comparison operation.
CompositeNode | Base class for nodes that can contain other nodes.
ConditionalStyle | Represents special formatting applied to some area of a table with assigned table style.
ConditionalStyleCollection | Represents a collection of ConditionalStyle objects.
ControlChar | Control characters often encountered in documents.
ConvertUtil | Provides helper functions to convert between various measurement units.
DigitalSignature | Represents a digital signature on a document and the result of its verification.
DigitalSignatureCollection | Provides a read-only collection of digital signatures attached to a document.
DigitalSignatureUtil | Provides methods for signing document.
Document | Represents a Word document.
DocumentBase | Provides the abstract base class for a main document and a glossary document of a Word document.
DocumentBuilder | Provides methods to insert text, images and other content, specify font, paragraph and section formatting.
DocumentVisitor | Base class for custom document visitors.
EditableRange | Represents a single editable range.
EditableRangeEnd | Represents an end of an editable range in a Word document.
EditableRangeStart | Represents a start of an editable range in a Word document.
EndnoteOptions | Represents the endnote numbering options for a document or section.
FileCorruptedException | Thrown during document load, when the document appears to be corrupted and impossible to load.
FileFormatInfo | Contains data returned by FileFormatUtil document format detection methods.
FileFormatUtil | Provides utility methods for working with file formats, such as detecting file format or converting file extensions to/from file format enums.
Font | Contains font attributes (font name, font size, color, and so on) for an object.
Footnote | Represents a container for text of a footnote or endnote.
FootnoteOptions | Represents the footnote numbering options for a document or section.
FrameFormat | Represents frame related formatting for a paragraph.
HeaderFooter | Represents a container for the header or footer text of a section.
HeaderFooterCollection | Provides typed access to HeaderFooter nodes of a Section.
HtmlLoadOptions | Allows to specify additional options when loading HTML document into a Document object.
Hyphenation | Provides methods for working with hyphenation dictionaries. These dictionaries prescribe where words of a specific language can be hyphenated.
ImportFormatOptions | Allows to specify various import options to format output.
IncorrectPasswordException | Thrown if a document is encrypted with a password and the password specified when opening the document is incorrect or missing.
Inline | Base class for inline-level nodes that can have character formatting associated with them, but cannot have child nodes of their own.
InlineStory | Base class for inline-level nodes that can contain paragraphs and tables.
InternableComplexAttr | Base class for internable complex attribute. Internable complex attribute should notify parent collection when going to be changed.
InterruptionToken | This class provides members to manually interrupt Aspose.Words during long running tasks.
LanguagePreferences | Allows to set up language preferences.
License | Provides methods to license the component.
ListFormat | Allows to control what list formatting is applied to a paragraph.
LoadOptions | Allows to specify additional options (such as password or base URI) when loading a document into a Document object.
Metered | Provides methods to set metered key.
Node | Base class for all nodes of a Word document.
NodeChangingArgs | Provides data for methods of the INodeChangingCallback interface.
NodeCollection | Represents a collection of nodes of a specific type.
NodeImporter | Allows to efficiently perform repeated import of nodes from one document to another.
NodeList | Represents a collection of nodes matching an XPath query executed using the SelectNodes method.
PageSetup | Represents the page setup properties of a section.
Paragraph | Represents a paragraph of text.
ParagraphCollection | Provides typed access to a collection of Paragraph nodes.
ParagraphFormat | Represents all the formatting for a paragraph.
PlainTextDocument | Allows to extract plain-text representation of the document's content.
Range | Represents a contiguous area in a document.
Revision | Represents a revision (tracked change) in a document node or style. Use RevisionType to check the type of this revision.
RevisionCollection | A collection of Revision objects that represent revisions in the document.
RevisionGroup | Represents a group of sequential Revision objects.
RevisionGroupCollection | A collection of RevisionGroup objects that represent revision groups in the document.
RtfLoadOptions | Allows to specify additional options when loading Rtf document into a Document object.
Run | Represents a run of characters with the same font formatting.
RunCollection | Provides typed access to a collection of Run nodes.
Section | Represents a single section in a document.
SectionCollection | A collection of Section objects in the document.
Shading | Contains shading attributes for an object.
SignatureLineOptions | Allows to specify options for signature line being inserted. Used in DocumentBuilder.
SignOptions | Allows to specify options for document signing.
SpecialChar | Base class for special characters in the document.
Story | Base class for elements that contain block-level nodes Paragraph and Table.
Style | Represents a single built-in or user-defined style.
StyleCollection | A collection of Style objects that represent both the built-in and user-defined styles in a document.
SubDocument | Represents a SubDocument - which is a reference to an externally stored document.
TableStyle | Represents a table style.
TabStop | Represents a single custom tab stop. The TabStop object is a member of the TabStopCollection collection.
TabStopCollection | A collection of TabStop objects that represent custom tabs for a paragraph or a style.
TextColumn | Represents a single text column. TextColumn is a member of the TextColumnCollection collection. The TextColumns collection includes all the columns in a section of a document.
TextColumnCollection | A collection of TextColumn objects that represent all the columns of text in a section of a document.
TxtLoadOptions | Allows to specify additional options when loading Text document into a Document object.
UnsupportedFileFormatException | Thrown during document load, when the document format is not recognized or not supported by Aspose.Words.
VariableCollection | A collection of document variables.
VbaModule | Provides access to VBA project module.
VbaModuleCollection | Represents a collection of VbaModule objects.
VbaProject | Provides access to VBA project information. A VBA project inside the document is defined as a collection of VBA modules.
WarningInfo | Contains information about a warning that Aspose.Words issued during document loading or saving.
WarningInfoCollection | Represents a typed collection of WarningInfo objects.

Interfaces

Interface | Description
IHyphenationCallback | Implemented by classes which can register hyphenation dictionaries. Use this mehod
INodeChangingCallback | Implement this interface if you want to receive notifications when nodes are inserted or removed in the document.
IWarningCallback | Implement this interface if you want to have your own custom method called to capture loss of fidelity warnings that can occur during document loading or saving.

Enumerations

Enumeration | Description
BorderType | Specifies sides of a border.
BreakType | Specifies type of a break inside a document.
CalendarType | Specifies the type of a calendar.
ComparisonTargetType | Allows to specify base document which will be used during comparison. Default value is Current.
ConditionalStyleType | Represents possible table areas to which conditional formatting may be defined in a table style.
ContentDisposition | Enumerates different ways of presenting the document at the client browser.
DigitalSignatureType | Specifies the type of a digital signature.
DropCapPosition | Specifies the position for a drop cap text.
EditingLanguage | Specifies the editing language.
EditorType | Specifies the set of possible aliases (or editing groups) which can be used as aliases to determine if the current user shall be allowed to edit a single range defined by an editable range within a document.
EndnotePosition | Defines the endnote position.
FindReplaceDirection | Specifies direction for replace operations.
FootnoteNumberingRule | Determines when automatic footnote or endnote numbering restarts.
FootnotePosition | Defines the footnote position.
FootnoteType | Specifies whether this is a footnote or an endnote.
HeaderFooterType | Identifies the type of header or footer found in a Word file.
HeightRule | Specifies the rule for determining the height of an object.
HtmlControlType | Type of document nodes that represent <input> and <select> elements imported from HTML.
ImportFormatMode | Specifies how formatting is merged when importing content from another document.
LineNumberRestartMode | Determines when automatic line numbering restarts.
LineSpacingRule | Specifies line spacing values for a paragraph.
LineStyle | Specifies line style of a Border.
LoadFormat | Indicates the format of the document that is to be loaded.
NodeChangingAction | Specifies the type of node change.
NodeType | Specifies the type of a Word document node.
NumberStyle | Specifies the number style for a list, footnotes and endnotes, page numbers.
Orientation | Specifies page orientation.
OutlineLevel | Specifies the outline level of a paragraph in the document.
PageBorderAppliesTo | Specifies which pages the page border is printed on.
PageBorderDistanceFrom | Specifies the positioning of the page border relative to the page margin.
PageVerticalAlignment | Specifies vertical justification of text on each page.
PaperSize | Specifies paper size.
ParagraphAlignment | Specifies text alignment in a paragraph.
ProtectionType | Protection type for a document.
RevisionType | Specifies the type of change being tracked in Revision.
SaveFormat | Indicates the format in which the document is saved.
SectionLayoutMode | Specifies the layout mode for a section allowing to define the document grid behavior.
SectionStart | The type of break at the beginning of the section.
StoryType | Text of a Word document is stored in stories. StoryType identifies a story.
StyleIdentifier | Locale independent style identifier.
StyleType | Represents type of the style.
TabAlignment | Specifies the alignment/type of a tab stop.
TabLeader | Specifies the type of the leader line displayed under the tab character.
TextDmlEffect | Dml text effect for text runs.
TextEffect | Animation effect for text runs.
TextOrientation | Specifies orientation of text on a page, in a table cell or a text frame.
TextureIndex | Specifies shading texture.
TxtLeadingSpacesOptions | Specifies available options for leading space handling during import from Text file.
TxtTrailingSpacesOptions | Specifies available options for trailing spaces handling during import from Text file.
Underline | Indicates type of the underline applied to a font.
VisitorAction | Allows the visitor to control the enumeration of nodes.
WarningSource | Specifies the module that produces a warning during document loading or saving.
WarningType | Specifies the type of a warning that is issued by Aspose.Words during document loading or saving.

Generated:2019-07-02 12:54:56,version:1.3.49.0


AbsolutePositionTab Class

An absolute position tab is a character which is used to advance the position on the current line of text when displaying this WordprocessingML content.

For a list of all members of this type, see AbsolutePositionTab Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.AbsolutePositionTab

[Visual Basic]
Public Class AbsolutePositionTab
Inherits SpecialChar
[C#]
public class AbsolutePositionTab : SpecialChar

Example

Shows how to use AbsolutePositionTab.

[C#]

public void DocumentToTxt()
{
    // This document contains two sentences separated by an absolute position tab.
    Document doc = new Document(MyDir + "AbsolutePositionTab.docx");

    // An AbsolutePositionTab is a child node of a paragraph.
    // AbsolutePositionTabs get picked up when looking for nodes of the SpecialChar type.
    Paragraph para = doc.FirstSection.Body.FirstParagraph;
    AbsolutePositionTab absPositionTab = (AbsolutePositionTab)para.GetChild(NodeType.SpecialChar, 0, true);

    // This implementation of the DocumentVisitor pattern converts the document to plain text.
    MyDocToTxtWriter myDocToTxtWriter = new MyDocToTxtWriter();

    // We can run the DocumentVisitor over the whole first paragraph.
    para.Accept(myDocToTxtWriter);

    // A tab character is placed where the AbsolutePositionTab was found.
    Assert.AreEqual("Before AbsolutePositionTab\tAfter AbsolutePositionTab", myDocToTxtWriter.GetText());

    // An AbsolutePositionTab can accept a DocumentVisitor by itself too.
    myDocToTxtWriter = new MyDocToTxtWriter();
    absPositionTab.Accept(myDocToTxtWriter);

    Assert.AreEqual("\t", myDocToTxtWriter.GetText());
}

/// <summary>
/// Visitor implementation that simply collects the Runs and AbsolutePositionTabs of a document as plain text.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        // We'll treat the AbsolutePositionTab as a regular tab in this case.
        mBuilder.Append("\t");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honors the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        mBuilder.Append(text);
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

AbsolutePositionTab Members | Aspose.Words Namespace


AbsolutePositionTab Members

AbsolutePositionTab overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from SpecialChar) | Returns NodeType.SpecialChar.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

AbsolutePositionTab Class | Aspose.Words Namespace


AbsolutePositionTab Methods

The methods of the AbsolutePositionTab class are listed below. For a complete list of AbsolutePositionTab class members, see the AbsolutePositionTab Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

AbsolutePositionTab Class | Aspose.Words Namespace


AbsolutePositionTab.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls DocumentVisitor.VisitAbsolutePositionTab.

For more info see the Visitor design pattern.

Example

Shows how to use AbsolutePositionTab.

[C#]

public void DocumentToTxt()
{
    // This document contains two sentences separated by an absolute position tab.
    Document doc = new Document(MyDir + "AbsolutePositionTab.docx");

    // An AbsolutePositionTab is a child node of a paragraph.
    // AbsolutePositionTabs get picked up when looking for nodes of the SpecialChar type.
    Paragraph para = doc.FirstSection.Body.FirstParagraph;
    AbsolutePositionTab absPositionTab = (AbsolutePositionTab)para.GetChild(NodeType.SpecialChar, 0, true);

    // This implementation of the DocumentVisitor pattern converts the document to plain text.
    MyDocToTxtWriter myDocToTxtWriter = new MyDocToTxtWriter();

    // We can run the DocumentVisitor over the whole first paragraph.
    para.Accept(myDocToTxtWriter);

    // A tab character is placed where the AbsolutePositionTab was found.
    Assert.AreEqual("Before AbsolutePositionTab\tAfter AbsolutePositionTab", myDocToTxtWriter.GetText());

    // An AbsolutePositionTab can accept a DocumentVisitor by itself too.
    myDocToTxtWriter = new MyDocToTxtWriter();
    absPositionTab.Accept(myDocToTxtWriter);

    Assert.AreEqual("\t", myDocToTxtWriter.GetText());
}

/// <summary>
/// Visitor implementation that simply collects the Runs and AbsolutePositionTabs of a document as plain text.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        // We'll treat the AbsolutePositionTab as a regular tab in this case.
        mBuilder.Append("\t");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honors the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        mBuilder.Append(text);
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

AbsolutePositionTab Class | Aspose.Words Namespace


Body Class

Represents a container for the main text of a section.

For a list of all members of this type, see Body Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Story
Aspose.Words.Body

[Visual Basic]
Public Class Body
Inherits Story
[C#]
public class Body : Story

Remarks

Body can contain Paragraph and Table child nodes.

Body is a section-level node and can only be a child of Section. There can only be one Body in a Section.

A minimal valid Body needs to contain at least one Paragraph.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Body Members | Aspose.Words Namespace


Body Members

Body overview

Public Instance Constructors

Body Constructor Initializes a new instance of the Body class.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from Story) | Gets the first paragraph in the story.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from Story) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Body.
Paragraphs (inherited from Story) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentSection | Gets the parent section of this story.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType (inherited from Story) | Gets the type of this story.
Tables (inherited from Story) | Gets a collection of tables that are immediate children of the story.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendParagraph (inherited from Story) | A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.
Clone (inherited from Node) |
DeleteShapes (inherited from Story) | Deletes all shapes from the text of this story.
EnsureMinimum | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Body Class | Aspose.Words Namespace


Body Constructor

Initializes a new instance of the Body class.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Body(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Body is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Body to a Section use Section.InsertAfter or Section.InsertBefore.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Body Class | Aspose.Words Namespace


Body Properties

The properties of the Body class are listed below. For a complete list of Body class members, see the Body Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from Story) | Gets the first paragraph in the story.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from Story) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Body.
Paragraphs (inherited from Story) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentSection | Gets the parent section of this story.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType (inherited from Story) | Gets the type of this story.
Tables (inherited from Story) | Gets a collection of tables that are immediate children of the story.

See Also

Body Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Body.NodeType Property

Returns NodeType.Body.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how you can enumerate through children of a composite node and detect types of the children nodes.

[C#]

// Open a document.
Document doc = new Document(MyDir + "Section.BodyNodeType.doc");

// Get the first section in the document.
Section section = doc.FirstSection;

// A Section is a composite node and therefore can contain child nodes.
// Section can contain only Body and HeaderFooter nodes.
foreach (Node node in section)
{
    // Every node has the NodeType property.
    switch (node.NodeType)
    {
        case NodeType.Body:
        {
            // If the node type is Body, we can cast the node to the Body class.
            Body body = (Body) node;

            // Write the content of the main story of the section to the console.
            Console.WriteLine("*** Body ***");
            Console.WriteLine(body.GetText());
            break;
        }
        case NodeType.HeaderFooter:
        {
            // If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
            HeaderFooter headerFooter = (HeaderFooter) node;

            // Write the content of the header footer to the console.
            Console.WriteLine("*** HeaderFooter ***");
            Console.WriteLine(headerFooter.HeaderFooterType);
            Console.WriteLine(headerFooter.GetText());
            break;
        }
        default:
        {
            // Other types of nodes never occur inside a Section node.
            throw new Exception("Unexpected node type in a section.");
        }
    }
}

See Also

Body Class | Aspose.Words Namespace


ParentSection Property

Aspose.Words

Body.ParentSection Property

Gets the parent section of this story.

[Visual Basic]
Public ReadOnly Property ParentSection As Section
[C#]
public Section ParentSection {get;}

Remarks

ParentSection is equivalent to (Section)ParentNode.

Example

Shows how to store endnotes at the end of each section instead of the document and manipulate their positions.

[C#]

public void SuppressEndnotes()
{
    // Create a new document and make it empty
    Document doc = new Document();
    doc.RemoveAllChildren();

    // Normally endnotes are all stored at the end of a document, but this option lets us store them at the end of each section
    doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;

    // Create 3 new sections, each having a paragraph and an endnote at the end
    InsertSection(doc, "Section 1", "Endnote 1, will stay in section 1");
    InsertSection(doc, "Section 2", "Endnote 2, will be pushed down to section 3");
    InsertSection(doc, "Section 3", "Endnote 3, will stay in section 3");

    // Each section contains its own page setup object
    // Setting this value will push this section's endnotes down to the next section
    PageSetup pageSetup = doc.Sections[1].PageSetup;
    pageSetup.SuppressEndnotes = true;

    doc.Save(ArtifactsDir + "PageSetup.SuppressEndnotes.docx");
}

/// <summary>
/// Add a section to the end of a document, give it a body and a paragraph, then add text and an endnote to that paragraph
/// </summary>
private void InsertSection(Document doc, string sectionBodyText, string endnoteText)
{
    Section section = new Section(doc);

    doc.AppendChild(section);

    Body body = new Body(doc);
    section.AppendChild(body);

    Assert.AreEqual(section, body.ParentNode);

    Paragraph para = new Paragraph(doc);
    body.AppendChild(para);

    Assert.AreEqual(body, para.ParentNode);

    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.MoveTo(para);
    builder.Write(sectionBodyText);
    builder.InsertFootnote(FootnoteType.Endnote, endnoteText);
}

See Also

Body Class | Aspose.Words Namespace


Body Methods

The methods of the Body class are listed below. For a complete list of Body class members, see the Body Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendParagraph (inherited from Story) | A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.
Clone (inherited from Node) |
DeleteShapes (inherited from Story) | Deletes all shapes from the text of this story.
EnsureMinimum | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Body Class | Aspose.Words Namespace


Body.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitBodyStart, then calls Accept for all child nodes of the section and calls DocumentVisitor.VisitBodyEnd at the end.

Example

Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.

[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

Body Class | Aspose.Words Namespace


Body.EnsureMinimum Method

If the last child is not a paragraph, creates and appends one empty paragraph.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Clears main text from all sections from the document leaving the sections themselves.

[C#]

// Open a document.
Document doc = new Document(MyDir + "Section.BodyEnsureMinimum.doc");

// This shows what is in the document originally. The document has two sections.
Console.WriteLine(doc.GetText());

// Loop through all sections in the document.
foreach (Section section in doc.Sections.OfType<Section>())
{
    // Each section has a Body node that contains main story (main text) of the section.
    Body body = section.Body;

    // This clears all nodes from the body.
    body.RemoveAllChildren();

    // Technically speaking, for the main story of a section to be valid, it needs to have
    // at least one empty paragraph. That's what the EnsureMinimum method does.
    body.EnsureMinimum();
}

// Check how the content of the document looks now.
Console.WriteLine(doc.GetText());

See Also

Body Class | Aspose.Words Namespace


Bookmark Class

Represents a single bookmark.

For a list of all members of this type, see Bookmark Members.

System.Object
Aspose.Words.Bookmark

[Visual Basic]
Public Class Bookmark
[C#]
public class Bookmark

Remarks

Bookmark is a "facade" object that encapsulates two nodes BookmarkStart and BookmarkEnd in a document tree and allows to work with a bookmark as a single object.

Example

Shows how to get or set bookmark name and text.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];

// Get the name and text of the bookmark.
string name = bookmark.Name;
string text = bookmark.Text;

// Set the name and text of the bookmark.
bookmark.Name = "RenamedBookmark";
bookmark.Text = "This is a new bookmarked text.";

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Bookmark Members | Aspose.Words Namespace


Bookmark Members

Bookmark overview

Public Instance Properties

BookmarkEnd | Gets the node that represents the end of the bookmark.
BookmarkStart | Gets the node that represents the start of the bookmark.
Name | Gets or sets the name of the bookmark.
Text | Gets or sets the text enclosed in the bookmark.

Public Instance Methods

Remove Removes the bookmark from the document. Does not remove text inside the bookmark.

See Also

Bookmark Class | Aspose.Words Namespace


Bookmark Properties

The properties of the Bookmark class are listed below. For a complete list of Bookmark class members, see the Bookmark Members topic.

Public Instance Properties

BookmarkEnd | Gets the node that represents the end of the bookmark.
BookmarkStart | Gets the node that represents the start of the bookmark.
Name | Gets or sets the name of the bookmark.
Text | Gets or sets the text enclosed in the bookmark.

See Also

Bookmark Class | Aspose.Words Namespace


BookmarkEnd Property

Aspose.Words

Bookmark.BookmarkEnd Property

Gets the node that represents the end of the bookmark.

[Visual Basic]
Public ReadOnly Property BookmarkEnd As BookmarkEnd
[C#]
public BookmarkEnd BookmarkEnd {get;}

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

Bookmark Class | Aspose.Words Namespace


BookmarkStart Property

Aspose.Words

Bookmark.BookmarkStart Property

Gets the node that represents the start of the bookmark.

[Visual Basic]
Public ReadOnly Property BookmarkStart As BookmarkStart
[C#]
public BookmarkStart BookmarkStart {get;}

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

Bookmark Class | Aspose.Words Namespace


Name Property

Aspose.Words

Bookmark.Name Property

Gets or sets the name of the bookmark.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

Note that if you change the name of a bookmark to a name that already exists in the document, no error will be given and only the first bookmark will be stored when you save the document.

Example

Shows how to replace elements in bookmark name

[C#]

Document doc = new Document(MyDir + "Bookmarks.Replace.docx");

// MS Word document does not support bookmark names with whitespaces by default.
// If you have document which contains bookmark names with underscores, you can simply replace them to whitespaces.
foreach (Bookmark bookmark in doc.Range.Bookmarks)
{
    bookmark.Name = bookmark.Name.Replace("_", " ");
}
Shows how to get or set bookmark name and text.
[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];

// Get the name and text of the bookmark.
string name = bookmark.Name;
string text = bookmark.Text;

// Set the name and text of the bookmark.
bookmark.Name = "RenamedBookmark";
bookmark.Text = "This is a new bookmarked text.";

See Also

Bookmark Class | Aspose.Words Namespace


Text Property

Aspose.Words

Bookmark.Text Property

Gets or sets the text enclosed in the bookmark.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to get or set bookmark name and text.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];

// Get the name and text of the bookmark.
string name = bookmark.Name;
string text = bookmark.Text;

// Set the name and text of the bookmark.
bookmark.Name = "RenamedBookmark";
bookmark.Text = "This is a new bookmarked text.";

See Also

Bookmark Class | Aspose.Words Namespace


Bookmark Methods

The methods of the Bookmark class are listed below. For a complete list of Bookmark class members, see the Bookmark Members topic.

Public Instance Methods

Remove Removes the bookmark from the document. Does not remove text inside the bookmark.

See Also

Bookmark Class | Aspose.Words Namespace


Bookmark.Remove Method

Removes the bookmark from the document. Does not remove text inside the bookmark.

[Visual Basic]
Public Sub Remove()
[C#]
public void Remove();

Example

Shows how to remove a particular bookmark from a document.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];

// Remove the bookmark. The bookmarked text is not deleted.
bookmark.Remove();

See Also

Bookmark Class | Aspose.Words Namespace


BookmarkCollection Class

A collection of Bookmark objects that represent the bookmarks in the specified range.

For a list of all members of this type, see BookmarkCollection Members.

System.Object
Aspose.Words.BookmarkCollection

[Visual Basic]
Public Class BookmarkCollection
Implements IEnumerable`1([Aspose.Words.Bookmark, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class BookmarkCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to obtain bookmarks from a bookmark collection.

[C#]

Document doc = new Document(MyDir + "Bookmarks.doc");

// By index.
Bookmark bookmark1 = doc.Range.Bookmarks[0];

// By name.
Bookmark bookmark2 = doc.Range.Bookmarks["Bookmark2"];

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BookmarkCollection Members | Aspose.Words Namespace


BookmarkCollection Members

BookmarkCollection overview

Public Instance Properties

Count | Returns the number of bookmarks in the collection.
Item | Overloaded. Returns a bookmark at the specified index.

Public Instance Methods

Clear | Removes all bookmarks from this collection and from the document.
GetEnumerator | Returns an enumerator object.
Remove | Overloaded. Removes the specified bookmark from the document.
RemoveAt | Removes a bookmark at the specified index.

See Also

BookmarkCollection Class | Aspose.Words Namespace


BookmarkCollection Properties

The properties of the BookmarkCollection class are listed below. For a complete list of BookmarkCollection class members, see the BookmarkCollection Members topic.

Public Instance Properties

Count | Returns the number of bookmarks in the collection.
Item | Overloaded. Returns a bookmark at the specified index.

See Also

BookmarkCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

BookmarkCollection.Count Property

Returns the number of bookmarks in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to count the number of bookmarks in a document.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

int count = doc.Range.Bookmarks.Count;

See Also

BookmarkCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

BookmarkCollection.Item Property

Returns a bookmark at the specified index.

Overload List

Returns a bookmark at the specified index.

public Bookmark this[int] {get;}

Returns a bookmark by name.

public Bookmark this[string] {get;}

See Also

BookmarkCollection Class | Aspose.Words Namespace


Item Property (Int32)

Aspose.Words

BookmarkCollection.Item Property (Int32)

Returns a bookmark at the specified index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Bookmark
[C#]
public Bookmark this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to obtain bookmarks from a bookmark collection.

[C#]

Document doc = new Document(MyDir + "Bookmarks.doc");

// By index.
Bookmark bookmark1 = doc.Range.Bookmarks[0];

// By name.
Bookmark bookmark2 = doc.Range.Bookmarks["Bookmark2"];

See Also

BookmarkCollection Class | Aspose.Words Namespace | BookmarkCollection.Item Overload List


Item Property (String)

Aspose.Words

BookmarkCollection.Item Property (String)

Returns a bookmark by name.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal bookmarkName As String _
) As Bookmark
[C#]
public Bookmark this[
string bookmarkName
] {get;}

Parameters

bookmarkName
Case-insensitive name of the bookmark.

Remarks

Returns null if the bookmark with the specified name cannot be found.

Example

Shows how to obtain bookmarks from a bookmark collection.

[C#]

Document doc = new Document(MyDir + "Bookmarks.doc");

// By index.
Bookmark bookmark1 = doc.Range.Bookmarks[0];

// By name.
Bookmark bookmark2 = doc.Range.Bookmarks["Bookmark2"];

See Also

BookmarkCollection Class | Aspose.Words Namespace | BookmarkCollection.Item Overload List


BookmarkCollection Methods

The methods of the BookmarkCollection class are listed below. For a complete list of BookmarkCollection class members, see the BookmarkCollection Members topic.

Public Instance Methods

Clear | Removes all bookmarks from this collection and from the document.
GetEnumerator | Returns an enumerator object.
Remove | Overloaded. Removes the specified bookmark from the document.
RemoveAt | Removes a bookmark at the specified index.

See Also

BookmarkCollection Class | Aspose.Words Namespace


BookmarkCollection.Clear Method

Removes all bookmarks from this collection and from the document.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to remove all bookmarks from a document.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");
doc.Range.Bookmarks.Clear();

See Also

BookmarkCollection Class | Aspose.Words Namespace


BookmarkCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Bookmark) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Bookmark> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkCollection Class | Aspose.Words Namespace


Remove Method

Aspose.Words

BookmarkCollection.Remove Method

Removes the specified bookmark from the document.

Overload List

Removes the specified bookmark from the document.

public void Remove(Bookmark);

Removes a bookmark with the specified name.

public void Remove(string);

See Also

BookmarkCollection Class | Aspose.Words Namespace


BookmarkCollection.Remove Method (Bookmark)

Removes the specified bookmark from the document.

[Visual Basic]
Overloads Public Sub Remove( _
ByVal bookmark As Bookmark _
)
[C#]
public void Remove(
Bookmark bookmark
);

Parameters

bookmark
The bookmark to remove.

Example

Demonstrates different methods of removing bookmarks from a document.

[C#]

Document doc = new Document(MyDir + "Bookmarks.doc");

// Remove a particular bookmark from the document.
Bookmark bookmark = doc.Range.Bookmarks[0];
doc.Range.Bookmarks.Remove(bookmark);

// Remove a bookmark by specified name.
doc.Range.Bookmarks.Remove("Bookmark2");

// Remove a bookmark at the specified index.
doc.Range.Bookmarks.RemoveAt(0);

See Also

BookmarkCollection Class | Aspose.Words Namespace | BookmarkCollection.Remove Overload List


BookmarkCollection.Remove Method (String)

Removes a bookmark with the specified name.

[Visual Basic]
Overloads Public Sub Remove( _
ByVal bookmarkName As String _
)
[C#]
public void Remove(
string bookmarkName
);

Parameters

bookmarkName
The case-insensitive name of the bookmark to remove.

Example

Demonstrates different methods of removing bookmarks from a document.

[C#]

Document doc = new Document(MyDir + "Bookmarks.doc");

// Remove a particular bookmark from the document.
Bookmark bookmark = doc.Range.Bookmarks[0];
doc.Range.Bookmarks.Remove(bookmark);

// Remove a bookmark by specified name.
doc.Range.Bookmarks.Remove("Bookmark2");

// Remove a bookmark at the specified index.
doc.Range.Bookmarks.RemoveAt(0);

See Also

BookmarkCollection Class | Aspose.Words Namespace | BookmarkCollection.Remove Overload List


BookmarkCollection.RemoveAt Method

Removes a bookmark at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the bookmark to remove.

Example

Demonstrates different methods of removing bookmarks from a document.

[C#]

Document doc = new Document(MyDir + "Bookmarks.doc");

// Remove a particular bookmark from the document.
Bookmark bookmark = doc.Range.Bookmarks[0];
doc.Range.Bookmarks.Remove(bookmark);

// Remove a bookmark by specified name.
doc.Range.Bookmarks.Remove("Bookmark2");

// Remove a bookmark at the specified index.
doc.Range.Bookmarks.RemoveAt(0);

See Also

BookmarkCollection Class | Aspose.Words Namespace


BookmarkEnd Class

Represents an end of a bookmark in a Word document.

For a list of all members of this type, see BookmarkEnd Members.

System.Object
Aspose.Words.Node
Aspose.Words.BookmarkEnd

[Visual Basic]
Public Class BookmarkEnd
Inherits Node
[C#]
public class BookmarkEnd : Node

Remarks

A complete bookmark in a Word document consists of a BookmarkStart and a matching BookmarkEnd with the same bookmark name.

BookmarkStart and BookmarkEnd are just markers inside a document that specify where the bookmark starts and ends.

Use the Bookmark class as a "facade" to work with a bookmark as a single object.

Example

Shows how to create a bookmark by inserting bookmark start and end nodes.

[C#]

Document doc = new Document();

// An empty document has just one empty paragraph by default.
Paragraph p = doc.FirstSection.Body.FirstParagraph;

p.AppendChild(new Run(doc, "Text before bookmark."));

p.AppendChild(new BookmarkStart(doc, "My bookmark"));
p.AppendChild(new Run(doc, "Text inside bookmark."));
p.AppendChild(new BookmarkEnd(doc, "My bookmark"));

p.AppendChild(new Run(doc, "Text after bookmark."));

doc.Save(ArtifactsDir + "Bookmarks.CreateBookmarkWithNodes.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BookmarkEnd Members | Aspose.Words Namespace


BookmarkEnd Members

BookmarkEnd overview

Public Instance Constructors

BookmarkEnd Constructor Initializes a new instance of the BookmarkEnd class.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
Name | Gets or sets the bookmark name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns BookmarkEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

BookmarkEnd Class | Aspose.Words Namespace


BookmarkEnd Constructor

Initializes a new instance of the BookmarkEnd class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal name As String _
)
[C#]
public BookmarkEnd(
DocumentBase doc,
string name
);

Parameters

doc
The owner document.
name
The name of the bookmark. Cannot be null.

Example

Shows how to create a bookmark by inserting bookmark start and end nodes.

[C#]

Document doc = new Document();

// An empty document has just one empty paragraph by default.
Paragraph p = doc.FirstSection.Body.FirstParagraph;

p.AppendChild(new Run(doc, "Text before bookmark."));

p.AppendChild(new BookmarkStart(doc, "My bookmark"));
p.AppendChild(new Run(doc, "Text inside bookmark."));
p.AppendChild(new BookmarkEnd(doc, "My bookmark"));

p.AppendChild(new Run(doc, "Text after bookmark."));

doc.Save(ArtifactsDir + "Bookmarks.CreateBookmarkWithNodes.doc");

See Also

BookmarkEnd Class | Aspose.Words Namespace


BookmarkEnd Properties

The properties of the BookmarkEnd class are listed below. For a complete list of BookmarkEnd class members, see the BookmarkEnd Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
Name | Gets or sets the bookmark name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns BookmarkEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

BookmarkEnd Class | Aspose.Words Namespace


Name Property

Aspose.Words

BookmarkEnd.Name Property

Gets or sets the bookmark name.

[Visual Basic]
NotOverridable Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

Cannot be null.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkEnd Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

BookmarkEnd.NodeType Property

Returns BookmarkEnd.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

BookmarkEnd Class | Aspose.Words Namespace


BookmarkEnd Methods

The methods of the BookmarkEnd class are listed below. For a complete list of BookmarkEnd class members, see the BookmarkEnd Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

BookmarkEnd Class | Aspose.Words Namespace


BookmarkEnd.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitBookmarkEnd.

For more info see the Visitor design pattern.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkEnd Class | Aspose.Words Namespace


BookmarkStart Class

Represents a start of a bookmark in a Word document.

For a list of all members of this type, see BookmarkStart Members.

System.Object
Aspose.Words.Node
Aspose.Words.BookmarkStart

[Visual Basic]
Public Class BookmarkStart
Inherits Node
[C#]
public class BookmarkStart : Node

Remarks

A complete bookmark in a Word document consists of a BookmarkStart and a matching BookmarkEnd with the same bookmark name.

BookmarkStart and BookmarkEnd are just markers inside a document that specify where the bookmark starts and ends.

Use the Bookmark class as a "facade" to work with a bookmark as a single object.

Example

Shows how to create a bookmark by inserting bookmark start and end nodes.

[C#]

Document doc = new Document();

// An empty document has just one empty paragraph by default.
Paragraph p = doc.FirstSection.Body.FirstParagraph;

p.AppendChild(new Run(doc, "Text before bookmark."));

p.AppendChild(new BookmarkStart(doc, "My bookmark"));
p.AppendChild(new Run(doc, "Text inside bookmark."));
p.AppendChild(new BookmarkEnd(doc, "My bookmark"));

p.AppendChild(new Run(doc, "Text after bookmark."));

doc.Save(ArtifactsDir + "Bookmarks.CreateBookmarkWithNodes.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BookmarkStart Members | Aspose.Words Namespace


BookmarkStart Members

BookmarkStart overview

Public Instance Constructors

BookmarkStart Constructor Initializes a new instance of the BookmarkStart class.

Public Instance Properties

Bookmark | Gets the facade object that encapsulates this bookmark start and end.
Document (inherited from Node) | Gets the document to which this node belongs.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
Name | Gets or sets the bookmark name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns BookmarkStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText | Returns an empty string.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

BookmarkStart Class | Aspose.Words Namespace


BookmarkStart Constructor

Initializes a new instance of the BookmarkStart class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal name As String _
)
[C#]
public BookmarkStart(
DocumentBase doc,
string name
);

Parameters

doc
The owner document.
name
The name of the bookmark. Cannot be null.

Example

Shows how to create a bookmark by inserting bookmark start and end nodes.

[C#]

Document doc = new Document();

// An empty document has just one empty paragraph by default.
Paragraph p = doc.FirstSection.Body.FirstParagraph;

p.AppendChild(new Run(doc, "Text before bookmark."));

p.AppendChild(new BookmarkStart(doc, "My bookmark"));
p.AppendChild(new Run(doc, "Text inside bookmark."));
p.AppendChild(new BookmarkEnd(doc, "My bookmark"));

p.AppendChild(new Run(doc, "Text after bookmark."));

doc.Save(ArtifactsDir + "Bookmarks.CreateBookmarkWithNodes.doc");

See Also

BookmarkStart Class | Aspose.Words Namespace


BookmarkStart Properties

The properties of the BookmarkStart class are listed below. For a complete list of BookmarkStart class members, see the BookmarkStart Members topic.

Public Instance Properties

Bookmark | Gets the facade object that encapsulates this bookmark start and end.
Document (inherited from Node) | Gets the document to which this node belongs.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
Name | Gets or sets the bookmark name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns BookmarkStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

BookmarkStart Class | Aspose.Words Namespace


Bookmark Property

Aspose.Words

BookmarkStart.Bookmark Property

Gets the facade object that encapsulates this bookmark start and end.

[Visual Basic]
Public ReadOnly Property Bookmark As Bookmark
[C#]
public Bookmark Bookmark {get;}

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkStart Class | Aspose.Words Namespace


Name Property

Aspose.Words

BookmarkStart.Name Property

Gets or sets the bookmark name.

[Visual Basic]
NotOverridable Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

Cannot be null.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkStart Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

BookmarkStart.NodeType Property

Returns BookmarkStart.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

BookmarkStart Class | Aspose.Words Namespace


BookmarkStart Methods

The methods of the BookmarkStart class are listed below. For a complete list of BookmarkStart class members, see the BookmarkStart Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText | Returns an empty string.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

BookmarkStart Class | Aspose.Words Namespace


BookmarkStart.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitBookmarkStart.

For more info see the Visitor design pattern.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkStart Class | Aspose.Words Namespace


BookmarkStart.GetText Method

Returns an empty string.

[Visual Basic]
Overrides Public Function GetText() As String
[C#]
public override string GetText();

Return Value

An empty string.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}

See Also

BookmarkStart Class | Aspose.Words Namespace


Border Class

Represents a border of an object.

For a list of all members of this type, see Border Members.

System.Object
Aspose.Words.InternableComplexAttr
Aspose.Words.Border

[Visual Basic]
Public Class Border
Inherits InternableComplexAttr
[C#]
public class Border : InternableComplexAttr

Remarks

Borders can be applied to various document elements including paragraph, run of text inside a paragraph or a table cell.

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
Inserts a paragraph with a top border.
[C#]

DocumentBuilder builder = new DocumentBuilder();

Border topBorder = builder.ParagraphFormat.Borders[BorderType.Top];
topBorder.Color = Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Border Members | Aspose.Words Namespace


Border Members

Border overview

Public Instance Properties

Color | Gets or sets the border color.
DistanceFromText | Gets or sets distance of the border from text or from the page edge in points.
IsVisible | Returns true if the LineStyle is not LineStyle.None.
LineStyle | Gets or sets the border style.
LineWidth | Gets or sets the border width in points.
Shadow | Gets or sets a value indicating whether the border has a shadow.

Public Instance Methods

ClearFormatting | Resets border properties to default values.
Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.

See Also

Border Class | Aspose.Words Namespace


Border Properties

The properties of the Border class are listed below. For a complete list of Border class members, see the Border Members topic.

Public Instance Properties

Color | Gets or sets the border color.
DistanceFromText | Gets or sets distance of the border from text or from the page edge in points.
IsVisible | Returns true if the LineStyle is not LineStyle.None.
LineStyle | Gets or sets the border style.
LineWidth | Gets or sets the border width in points.
Shadow | Gets or sets a value indicating whether the border has a shadow.

See Also

Border Class | Aspose.Words Namespace


Color Property

Aspose.Words

Border.Color Property

Gets or sets the border color.

[Visual Basic]
Public Property Color As Color
[C#]
public Color Color {get; set;}

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");

See Also

Border Class | Aspose.Words Namespace


DistanceFromText Property

Aspose.Words

Border.DistanceFromText Property

Gets or sets distance of the border from text or from the page edge in points.

[Visual Basic]
Public Property DistanceFromText As Double
[C#]
public double DistanceFromText {get; set;}

Remarks

Has no effect and will be automatically reset to zero for borders of table cells.

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");

See Also

Border Class | Aspose.Words Namespace | BorderDistanceFrom


IsVisible Property

Aspose.Words

Border.IsVisible Property

Returns true if the LineStyle is not LineStyle.None.

[Visual Basic]
Public ReadOnly Property IsVisible As Boolean
[C#]
public bool IsVisible {get;}

Example

Shows the equality of BorderCollections as well counting, visibility of their elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 1."));

Paragraph firstParagraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection firstParaBorders = firstParagraph.ParagraphFormat.Borders;

builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 2."));

Paragraph secondParagraph = builder.CurrentParagraph;
BorderCollection secondParaBorders = secondParagraph.ParagraphFormat.Borders;

// Two paragraphs have two different BorderCollections, but share the elements that are in from the first paragraph
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsTrue(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Borders are invisible by default
    Assert.IsFalse(firstParaBorders[i].IsVisible);
}

// We see that the elements in both collections are equal, while the collections themselves are not.
Assert.IsFalse(firstParaBorders.Equals(secondParaBorders));

// Each border in the second paragraph collection becomes no longer the same as its counterpart from the first paragraph collection
// There are always 6 elements in a border collection, and changing all of them will make the second collection completely different from the first
secondParaBorders[BorderType.Left].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Right].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Top].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Bottom].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Vertical].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Horizontal].LineStyle = LineStyle.DotDash;

// Now the BorderCollections both have their own elements
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsFalse(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreNotEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Changing the line style made the borders visible
    Assert.IsTrue(secondParaBorders[i].IsVisible);
}

See Also

Border Class | Aspose.Words Namespace


LineStyle Property

Aspose.Words

Border.LineStyle Property

Gets or sets the border style.

[Visual Basic]
Public Property LineStyle As LineStyle
[C#]
public LineStyle LineStyle {get; set;}

Remarks

If you set line style to none, then line width is automatically changed to zero.

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");

See Also

Border Class | Aspose.Words Namespace


LineWidth Property

Aspose.Words

Border.LineWidth Property

Gets or sets the border width in points.

[Visual Basic]
Public Property LineWidth As Double
[C#]
public double LineWidth {get; set;}

Remarks

If you set line width greater than zero when line style is none, the line style is automatically changed to single line.

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");

See Also

Border Class | Aspose.Words Namespace


Shadow Property

Aspose.Words

Border.Shadow Property

Gets or sets a value indicating whether the border has a shadow.

[Visual Basic]
Public Property Shadow As Boolean
[C#]
public bool Shadow {get; set;}

Remarks

In Microsoft Word, for a border to have a shadow, the borders on all four sides (left, top, right and bottom) should be of the same type, width, color and all should have the Shadow property set to true.

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

Border Class | Aspose.Words Namespace


Border Methods

The methods of the Border class are listed below. For a complete list of Border class members, see the Border Members topic.

Public Instance Methods

ClearFormatting | Resets border properties to default values.
Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.

See Also

Border Class | Aspose.Words Namespace


Border.ClearFormatting Method

Resets border properties to default values.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Remarks

When border properties are reset to default values, the border is invisible.

Example

Shows how to remove borders from a paragraph one by one.

[C#]

Document doc = new Document(MyDir + "Border.Borders.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

BorderCollection borders = builder.ParagraphFormat.Borders;

foreach (Border border in borders)
{
    border.ClearFormatting();
}

builder.CurrentParagraph.Runs[0].Text = "Paragraph with no border";

doc.Save(ArtifactsDir + "Border.NoBorder.doc");

See Also

Border Class | Aspose.Words Namespace


Border.Equals Method

Determines whether the specified object is equal in value to the current object.

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

Example

Shows the equality of BorderCollections as well counting, visibility of their elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 1."));

Paragraph firstParagraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection firstParaBorders = firstParagraph.ParagraphFormat.Borders;

builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 2."));

Paragraph secondParagraph = builder.CurrentParagraph;
BorderCollection secondParaBorders = secondParagraph.ParagraphFormat.Borders;

// Two paragraphs have two different BorderCollections, but share the elements that are in from the first paragraph
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsTrue(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Borders are invisible by default
    Assert.IsFalse(firstParaBorders[i].IsVisible);
}

// We see that the elements in both collections are equal, while the collections themselves are not.
Assert.IsFalse(firstParaBorders.Equals(secondParaBorders));

// Each border in the second paragraph collection becomes no longer the same as its counterpart from the first paragraph collection
// There are always 6 elements in a border collection, and changing all of them will make the second collection completely different from the first
secondParaBorders[BorderType.Left].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Right].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Top].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Bottom].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Vertical].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Horizontal].LineStyle = LineStyle.DotDash;

// Now the BorderCollections both have their own elements
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsFalse(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreNotEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Changing the line style made the borders visible
    Assert.IsTrue(secondParaBorders[i].IsVisible);
}

See Also

Border Class | Aspose.Words Namespace


Border.GetHashCode Method

Serves as a hash function for this type.

[Visual Basic]
Overrides Public Function GetHashCode() As Integer
[C#]
public override int GetHashCode();

Example

Shows the equality of BorderCollections as well counting, visibility of their elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 1."));

Paragraph firstParagraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection firstParaBorders = firstParagraph.ParagraphFormat.Borders;

builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 2."));

Paragraph secondParagraph = builder.CurrentParagraph;
BorderCollection secondParaBorders = secondParagraph.ParagraphFormat.Borders;

// Two paragraphs have two different BorderCollections, but share the elements that are in from the first paragraph
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsTrue(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Borders are invisible by default
    Assert.IsFalse(firstParaBorders[i].IsVisible);
}

// We see that the elements in both collections are equal, while the collections themselves are not.
Assert.IsFalse(firstParaBorders.Equals(secondParaBorders));

// Each border in the second paragraph collection becomes no longer the same as its counterpart from the first paragraph collection
// There are always 6 elements in a border collection, and changing all of them will make the second collection completely different from the first
secondParaBorders[BorderType.Left].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Right].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Top].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Bottom].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Vertical].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Horizontal].LineStyle = LineStyle.DotDash;

// Now the BorderCollections both have their own elements
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsFalse(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreNotEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Changing the line style made the borders visible
    Assert.IsTrue(secondParaBorders[i].IsVisible);
}

See Also

Border Class | Aspose.Words Namespace


BorderCollection Class

A collection of Border objects.

For a list of all members of this type, see BorderCollection Members.

System.Object
Aspose.Words.BorderCollection

[Visual Basic]
NotInheritable Public Class BorderCollection
Implements IEnumerable`1([Aspose.Words.Border, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public sealed class BorderCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

Different document elements have different borders. For example, ParagraphFormat has Bottom, Left, Right and Top borders. You can specify different formatting for each border independently or enumerate through all borders and apply same formatting.

Example

Inserts a paragraph with a top border.

[C#]

DocumentBuilder builder = new DocumentBuilder();

Border topBorder = builder.ParagraphFormat.Borders[BorderType.Top];
topBorder.Color = Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BorderCollection Members | Aspose.Words Namespace


BorderCollection Members

BorderCollection overview

Public Instance Properties

Bottom | Gets the bottom border.
Color | Gets or sets the border color.
Count | Gets the number of borders in the collection.
DistanceFromText | Gets or sets distance of the border from text in points.
Horizontal | Gets the horizontal border that is used between cells or conforming paragraphs.
Item | Overloaded. Retrieves a Border object.
Left | Gets the left border.
LineStyle | Gets or sets the border style.
LineWidth | Gets or sets the border width in points.
Right | Gets the right border.
Shadow | Gets or sets a value indicating whether the border has a shadow.
Top | Gets the top border.
Vertical | Gets the vertical border that is used between cells.

Public Instance Methods

ClearFormatting | Removes all borders of an object.
GetEnumerator | Returns an enumerator object that can be used to iterate over all borders in the collection.

See Also

BorderCollection Class | Aspose.Words Namespace


BorderCollection Properties

The properties of the BorderCollection class are listed below. For a complete list of BorderCollection class members, see the BorderCollection Members topic.

Public Instance Properties

Bottom | Gets the bottom border.
Color | Gets or sets the border color.
Count | Gets the number of borders in the collection.
DistanceFromText | Gets or sets distance of the border from text in points.
Horizontal | Gets the horizontal border that is used between cells or conforming paragraphs.
Item | Overloaded. Retrieves a Border object.
Left | Gets the left border.
LineStyle | Gets or sets the border style.
LineWidth | Gets or sets the border width in points.
Right | Gets the right border.
Shadow | Gets or sets a value indicating whether the border has a shadow.
Top | Gets the top border.
Vertical | Gets the vertical border that is used between cells.

See Also

BorderCollection Class | Aspose.Words Namespace


Bottom Property

Aspose.Words

BorderCollection.Bottom Property

Gets the bottom border.

[Visual Basic]
Public ReadOnly Property Bottom As Border
[C#]
public Border Bottom {get;}

Example

Shows how to format table and cell with different borders and shadings

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Color Property

Aspose.Words

BorderCollection.Color Property

Gets or sets the border color.

[Visual Basic]
Public Property Color As Color
[C#]
public Color Color {get; set;}

Remarks

Returns the color of the first border in the collection.

Sets the color of all borders in the collection excluding diagonal borders.

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

BorderCollection.Count Property

Gets the number of borders in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows the equality of BorderCollections as well counting, visibility of their elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 1."));

Paragraph firstParagraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection firstParaBorders = firstParagraph.ParagraphFormat.Borders;

builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 2."));

Paragraph secondParagraph = builder.CurrentParagraph;
BorderCollection secondParaBorders = secondParagraph.ParagraphFormat.Borders;

// Two paragraphs have two different BorderCollections, but share the elements that are in from the first paragraph
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsTrue(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Borders are invisible by default
    Assert.IsFalse(firstParaBorders[i].IsVisible);
}

// We see that the elements in both collections are equal, while the collections themselves are not.
Assert.IsFalse(firstParaBorders.Equals(secondParaBorders));

// Each border in the second paragraph collection becomes no longer the same as its counterpart from the first paragraph collection
// There are always 6 elements in a border collection, and changing all of them will make the second collection completely different from the first
secondParaBorders[BorderType.Left].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Right].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Top].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Bottom].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Vertical].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Horizontal].LineStyle = LineStyle.DotDash;

// Now the BorderCollections both have their own elements
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsFalse(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreNotEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Changing the line style made the borders visible
    Assert.IsTrue(secondParaBorders[i].IsVisible);
}

See Also

BorderCollection Class | Aspose.Words Namespace


DistanceFromText Property

Aspose.Words

BorderCollection.DistanceFromText Property

Gets or sets distance of the border from text in points.

[Visual Basic]
Public Property DistanceFromText As Double
[C#]
public double DistanceFromText {get; set;}

Remarks

Gets the distance from text for the first border.

Sets the distance from text for all borders in the collection excluding diagonal borders.

Has no effect and will be automatically reset to zero for borders of table cells.

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Horizontal Property

Aspose.Words

BorderCollection.Horizontal Property

Gets the horizontal border that is used between cells or conforming paragraphs.

[Visual Basic]
Public ReadOnly Property Horizontal As Border
[C#]
public Border Horizontal {get;}

Example

Shows the difference between the Horizontal and Vertical properties of BorderCollection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A BorderCollection is one of a Paragraph's formatting properties
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection paragraphBorders = paragraph.ParagraphFormat.Borders;

// paragraphBorders belongs to the first paragraph, but these changes will apply to subsequently created paragraphs
paragraphBorders.Horizontal.Color = Color.Red;
paragraphBorders.Horizontal.LineStyle = LineStyle.DashSmallGap;
paragraphBorders.Horizontal.LineWidth = 3;

// Horizontal borders only appear under a paragraph if there's another paragraph under it
// Right now the first paragraph has no borders
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph above horizontal border."));

// Now the first paragraph will have a red dashed line border under it
// This new second paragraph can have a border too, but only if we add another paragraph underneath it
builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph below horizontal border."));

// A table makes use of both vertical and horizontal properties of BorderCollection
// Both these properties can only affect the inner borders of a table
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);

for (int i = 0; i < 3; i++)
{
    Row row = new Row(doc);
    BorderCollection rowBorders = row.RowFormat.Borders;

    // Vertical borders are ones between rows in a table
    rowBorders.Horizontal.Color = Color.Red;
    rowBorders.Horizontal.LineStyle = LineStyle.Dot;
    rowBorders.Horizontal.LineWidth = 2;

    // Vertical borders are ones between cells in a table
    rowBorders.Vertical.Color = Color.Blue;
    rowBorders.Vertical.LineStyle = LineStyle.Dot;
    rowBorders.Vertical.LineWidth = 2;

    // A blue dotted vertical border will appear between cells
    // A red dotted border will appear between rows
    row.AppendChild(new Cell(doc));
    row.LastCell.AppendChild(new Paragraph(doc));
    row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Vertical border to the right."));

    row.AppendChild(new Cell(doc));
    row.LastCell.AppendChild(new Paragraph(doc));
    row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Vertical border to the left."));
    table.AppendChild(row);
}

doc.Save(ArtifactsDir + "Border.HorizontalAndVerticalBorders.docx");

See Also

BorderCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

BorderCollection.Item Property

Retrieves a Border object.

Overload List

Retrieves a Border object by border type.

public Border this[Aspose.Words.BorderType] {get;}

Retrieves a Border object by index.

public Border this[int] {get;}

See Also

BorderCollection Class | Aspose.Words Namespace


Item Property (BorderType)

Aspose.Words

BorderCollection.Item Property (BorderType)

Retrieves a Border object by border type.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal borderType As BorderType _
) As Border
[C#]
public Border this[
Aspose.Words.BorderType borderType
] {get;}

Parameters

borderType
A BorderType value that specifies the type of the border to retrieve.

Remarks

Note that not all borders are present for different document elements. This method throws an exception if you request a border not applicable to the current object.

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");

See Also

BorderCollection Class | Aspose.Words Namespace | BorderCollection.Item Overload List


Item Property (Int32)

Aspose.Words

BorderCollection.Item Property (Int32)

Retrieves a Border object by index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Border
[C#]
public Border this[
int index
] {get;}

Parameters

index
Zero-based index of the border to retrieve.

Example

Shows the equality of BorderCollections as well counting, visibility of their elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 1."));

Paragraph firstParagraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection firstParaBorders = firstParagraph.ParagraphFormat.Borders;

builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph 2."));

Paragraph secondParagraph = builder.CurrentParagraph;
BorderCollection secondParaBorders = secondParagraph.ParagraphFormat.Borders;

// Two paragraphs have two different BorderCollections, but share the elements that are in from the first paragraph
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsTrue(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Borders are invisible by default
    Assert.IsFalse(firstParaBorders[i].IsVisible);
}

// We see that the elements in both collections are equal, while the collections themselves are not.
Assert.IsFalse(firstParaBorders.Equals(secondParaBorders));

// Each border in the second paragraph collection becomes no longer the same as its counterpart from the first paragraph collection
// There are always 6 elements in a border collection, and changing all of them will make the second collection completely different from the first
secondParaBorders[BorderType.Left].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Right].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Top].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Bottom].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Vertical].LineStyle = LineStyle.DotDash;
secondParaBorders[BorderType.Horizontal].LineStyle = LineStyle.DotDash;

// Now the BorderCollections both have their own elements
for (int i = 0; i < firstParaBorders.Count; i++)
{
    Assert.IsFalse(firstParaBorders[i].Equals(secondParaBorders[i]));
    Assert.AreNotEqual(firstParaBorders[i].GetHashCode(), secondParaBorders[i].GetHashCode());

    // Changing the line style made the borders visible
    Assert.IsTrue(secondParaBorders[i].IsVisible);
}

See Also

BorderCollection Class | Aspose.Words Namespace | BorderCollection.Item Overload List


Left Property

Aspose.Words

BorderCollection.Left Property

Gets the left border.

[Visual Basic]
Public ReadOnly Property Left As Border
[C#]
public Border Left {get;}

Example

Shows how to format table and cell with different borders and shadings

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


LineStyle Property

Aspose.Words

BorderCollection.LineStyle Property

Gets or sets the border style.

[Visual Basic]
Public Property LineStyle As LineStyle
[C#]
public LineStyle LineStyle {get; set;}

Remarks

Returns the style of the first border in the collection.

Sets the style of all borders in the collection excluding diagonal borders.

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


LineWidth Property

Aspose.Words

BorderCollection.LineWidth Property

Gets or sets the border width in points.

[Visual Basic]
Public Property LineWidth As Double
[C#]
public double LineWidth {get; set;}

Remarks

Returns the width of the first border in the collection.

Sets the width of all borders in the collection excluding diagonal borders.

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Right Property

Aspose.Words

BorderCollection.Right Property

Gets the right border.

[Visual Basic]
Public ReadOnly Property Right As Border
[C#]
public Border Right {get;}

Example

Shows how to format table and cell with different borders and shadings

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Shadow Property

Aspose.Words

BorderCollection.Shadow Property

Gets or sets a value indicating whether the border has a shadow.

[Visual Basic]
Public Property Shadow As Boolean
[C#]
public bool Shadow {get; set;}

Remarks

Gets the value from the first border in the collection.

Sets the value for all borders in the collection excluding diagonal borders.

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Top Property

Aspose.Words

BorderCollection.Top Property

Gets the top border.

[Visual Basic]
Public ReadOnly Property Top As Border
[C#]
public Border Top {get;}

Example

Shows how to format table and cell with different borders and shadings

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


Vertical Property

Aspose.Words

BorderCollection.Vertical Property

Gets the vertical border that is used between cells.

[Visual Basic]
Public ReadOnly Property Vertical As Border
[C#]
public Border Vertical {get;}

Example

Shows the difference between the Horizontal and Vertical properties of BorderCollection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A BorderCollection is one of a Paragraph's formatting properties
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
BorderCollection paragraphBorders = paragraph.ParagraphFormat.Borders;

// paragraphBorders belongs to the first paragraph, but these changes will apply to subsequently created paragraphs
paragraphBorders.Horizontal.Color = Color.Red;
paragraphBorders.Horizontal.LineStyle = LineStyle.DashSmallGap;
paragraphBorders.Horizontal.LineWidth = 3;

// Horizontal borders only appear under a paragraph if there's another paragraph under it
// Right now the first paragraph has no borders
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph above horizontal border."));

// Now the first paragraph will have a red dashed line border under it
// This new second paragraph can have a border too, but only if we add another paragraph underneath it
builder.InsertParagraph();
builder.CurrentParagraph.AppendChild(new Run(doc, "Paragraph below horizontal border."));

// A table makes use of both vertical and horizontal properties of BorderCollection
// Both these properties can only affect the inner borders of a table
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);

for (int i = 0; i < 3; i++)
{
    Row row = new Row(doc);
    BorderCollection rowBorders = row.RowFormat.Borders;

    // Vertical borders are ones between rows in a table
    rowBorders.Horizontal.Color = Color.Red;
    rowBorders.Horizontal.LineStyle = LineStyle.Dot;
    rowBorders.Horizontal.LineWidth = 2;

    // Vertical borders are ones between cells in a table
    rowBorders.Vertical.Color = Color.Blue;
    rowBorders.Vertical.LineStyle = LineStyle.Dot;
    rowBorders.Vertical.LineWidth = 2;

    // A blue dotted vertical border will appear between cells
    // A red dotted border will appear between rows
    row.AppendChild(new Cell(doc));
    row.LastCell.AppendChild(new Paragraph(doc));
    row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Vertical border to the right."));

    row.AppendChild(new Cell(doc));
    row.LastCell.AppendChild(new Paragraph(doc));
    row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Vertical border to the left."));
    table.AppendChild(row);
}

doc.Save(ArtifactsDir + "Border.HorizontalAndVerticalBorders.docx");

See Also

BorderCollection Class | Aspose.Words Namespace


BorderCollection Methods

The methods of the BorderCollection class are listed below. For a complete list of BorderCollection class members, see the BorderCollection Members topic.

Public Instance Methods

ClearFormatting | Removes all borders of an object.
GetEnumerator | Returns an enumerator object that can be used to iterate over all borders in the collection.

See Also

BorderCollection Class | Aspose.Words Namespace


BorderCollection.ClearFormatting Method

Removes all borders of an object.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Example

Shows how to remove all borders from a paragraph at once.

[C#]

Document doc = new Document(MyDir + "Border.Borders.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
BorderCollection borders = builder.ParagraphFormat.Borders;

borders.ClearFormatting();

See Also

BorderCollection Class | Aspose.Words Namespace


BorderCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all borders in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Border) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Border> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to enumerate all borders in a collection.

[C#]

Document doc = new Document(MyDir + "Border.Borders.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

BorderCollection borders = builder.ParagraphFormat.Borders;

using (IEnumerator<Border> enumerator = borders.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        // Do something useful.
        Border b = enumerator.Current;
        b.Color = Color.RoyalBlue;
        b.LineStyle = LineStyle.Double;
    }
}

doc.Save(ArtifactsDir + "Border.ChangedColorBorder.doc");

See Also

BorderCollection Class | Aspose.Words Namespace


BorderType Enumeration

Specifies sides of a border.

[Visual Basic]
Public Enum BorderType
[C#]
public enum BorderType

Example

Inserts a paragraph with a top border.

[C#]

DocumentBuilder builder = new DocumentBuilder();

Border topBorder = builder.ParagraphFormat.Borders[BorderType.Top];
topBorder.Color = Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");

Members

Member Name | Description | Value
None | Default value. | -1
Bottom | Specifies the bottom border of a paragraph or a table cell. | 0
Left | Specifies the left border of a paragraph or a table cell. | 1
Right | Specifies the right border of a paragraph or a table cell. | 2
Top | Specifies the top border of a paragraph or a table cell. | 3
Horizontal | Specifies the horizontal border between cells in a table or between conforming paragraphs. | 4
Vertical | Specifies the vertical border between cells in a table. | 5
DiagonalDown | Specifies the diagonal border in a table cell. | 6
DiagonalUp | Specifies the diagonal border in a table cell. | 7

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


BreakType Enumeration

Specifies type of a break inside a document.

[Visual Basic]
Public Enum BreakType
[C#]
public enum BreakType

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");
Creates headers and footers in a document using DocumentBuilder.
[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");
Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.
[C#]

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 2");
builder.Writeln("Heading 3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");

// Call the method below to update the TOC.
doc.UpdateFields();

Members

Member Name | Description | Value
ParagraphBreak | Break between paragraphs. | 0
PageBreak | Explicit page break. | 1
ColumnBreak | Explicit column break. | 2
SectionBreakContinuous | Specifies start of new section on the same page as the previous section. | 3
SectionBreakNewColumn | Specifies start of new section in the new column. | 4
SectionBreakNewPage | Specifies start of new section on a new page. | 5
SectionBreakEvenPage | Specifies start of new section on a new even page. | 6
SectionBreakOddPage | Specifies start of new section on a odd page. | 7
LineBreak | Explicit line break. | 8

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


BuildVersionInfo Class

Provides information about the current product name and version.

For a list of all members of this type, see BuildVersionInfo Members.

System.Object
Aspose.Words.BuildVersionInfo

[Visual Basic]
MustInherit NotInheritable Public Class BuildVersionInfo
[C#]
public abstract sealed class BuildVersionInfo

Example

Shows how to use BuildVersionInfo to obtain information about this product.

[C#]

Console.WriteLine("I am currently using {0}, version number {1}.", BuildVersionInfo.Product,
    BuildVersionInfo.Version);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BuildVersionInfo Members | Aspose.Words Namespace


BuildVersionInfo Members

BuildVersionInfo overview

Public Static (Shared) Properties

Product | Gets the full name of the product.
Version | Gets the product version.

See Also

BuildVersionInfo Class | Aspose.Words Namespace


BuildVersionInfo Properties

The properties of the BuildVersionInfo class are listed below. For a complete list of BuildVersionInfo class members, see the BuildVersionInfo Members topic.

Public Static (Shared) Properties

Product | Gets the full name of the product.
Version | Gets the product version.

See Also

BuildVersionInfo Class | Aspose.Words Namespace


Product Property

Aspose.Words

BuildVersionInfo.Product Property

Gets the full name of the product.

[Visual Basic]
Public Shared ReadOnly Property Product As String
[C#]
public static string Product {get;}

Example

Shows how to use BuildVersionInfo to obtain information about this product.

[C#]

Console.WriteLine("I am currently using {0}, version number {1}.", BuildVersionInfo.Product,
    BuildVersionInfo.Version);

See Also

BuildVersionInfo Class | Aspose.Words Namespace


Version Property

Aspose.Words

BuildVersionInfo.Version Property

Gets the product version.

[Visual Basic]
Public Shared ReadOnly Property Version As String
[C#]
public static string Version {get;}

Remarks

The product version is in the "Major.Minor.Hotfix.0" format.

Example

Shows how to use BuildVersionInfo to obtain information about this product.

[C#]

Console.WriteLine("I am currently using {0}, version number {1}.", BuildVersionInfo.Product,
    BuildVersionInfo.Version);

See Also

BuildVersionInfo Class | Aspose.Words Namespace


CalendarType Enumeration

Specifies the type of a calendar.

[Visual Basic]
Public Enum CalendarType
[C#]
public enum CalendarType

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

Members

Member Name | Description | Value
Gregorian | The Gregorian calendar. | 0
Hijri | The Hijri Lunar calendar. | 1
Hebrew | The Hebrew Lunar calendar. | 2
SakaEra | The Saka Era calendar. | 3
UmAlQura | The Um-al-Qura calendar. | 4

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


CertificateHolder Class

Represents a holder of X509Certificate2 instance.

For a list of all members of this type, see CertificateHolder Members.

System.Object
Aspose.Words.CertificateHolder

[Visual Basic]
Public Class CertificateHolder
[C#]
public class CertificateHolder

Remarks

CertificateHolder can be created by static factory methods only. It contains an instance of X509Certificate2 which is used to introduce private, public keys and certificate chains into the system. This class is applied in DigitalSignatureUtil and PdfDigitalSignatureDetails instead of obsolete methods with X509Certificate2 as parameters.

Example

Shows how to sign documents using certificate holder and sign options.

[C#]

CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions { Comments = "My comment", SignTime = DateTime.Now };

using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.DigitalSignature.docx", FileMode.OpenOrCreate))
    {
        DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
    }
}
Shows how to sign encrypted document file.
[C#]

string outputFileName = ArtifactsDir + "Document.Encrypted.docx";

Document doc = new Document(MyDir + "Document.Encrypted.docx", new LoadOptions("docPassword"));

// Create certificate holder from a file.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions
{
    Comments = "Comment",
    SignTime = DateTime.Now,
    DecryptionPassword = "docPassword"
};

// Digitally sign encrypted with "docPassword" document in the specified path.
DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, certificateHolder, signOptions);
Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.
[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CertificateHolder Members | Aspose.Words Namespace


CertificateHolder Members

CertificateHolder overview

Public Static (Shared) Methods

Create Overloaded. Creates CertificateHolder object using byte array of PKCS12 store and its password.

Public Instance Properties

Certificate Returns the instance of X509Certificate2 which holds private, public keys and certificate chain.

See Also

CertificateHolder Class | Aspose.Words Namespace


CertificateHolder Properties

The properties of the CertificateHolder class are listed below. For a complete list of CertificateHolder class members, see the CertificateHolder Members topic.

Public Instance Properties

Certificate Returns the instance of X509Certificate2 which holds private, public keys and certificate chain.

See Also

CertificateHolder Class | Aspose.Words Namespace


Certificate Property

Aspose.Words

CertificateHolder.Certificate Property

Returns the instance of X509Certificate2 which holds private, public keys and certificate chain.

[Visual Basic]
Public ReadOnly Property Certificate As X509Certificate2
[C#]
public X509Certificate2 Certificate {get;}

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

CertificateHolder Class | Aspose.Words Namespace


CertificateHolder Methods

The methods of the CertificateHolder class are listed below. For a complete list of CertificateHolder class members, see the CertificateHolder Members topic.

Public Static (Shared) Methods

Create Overloaded. Creates CertificateHolder object using byte array of PKCS12 store and its password.

See Also

CertificateHolder Class | Aspose.Words Namespace


Create Method

Aspose.Words

CertificateHolder.Create Method

Creates CertificateHolder object using byte array of PKCS12 store and its password.

Overload List

Creates CertificateHolder object using byte array of PKCS12 store and its password.

public static CertificateHolder Create(byte[],SecureString);

Creates CertificateHolder object using byte array of PKCS12 store and its password.

public static CertificateHolder Create(byte[],string);

Obsolete. Creates CertificateHolder object using already created X509Certificate2. The given X509Certificate2 must have private key. This method is obsolete and will be removed in the future releases.

public static CertificateHolder Create(X509Certificate2);

Creates CertificateHolder object using path to PKCS12 store and its password.

public static CertificateHolder Create(string,string);

Creates CertificateHolder object using path to PKCS12 store, its password and the alias by using which private key and certificate will be found.

public static CertificateHolder Create(string,string,string);

See Also

CertificateHolder Class | Aspose.Words Namespace


CertificateHolder.Create Method (Byte[], SecureString)

Creates CertificateHolder object using byte array of PKCS12 store and its password.

[Visual Basic]
Overloads Public Shared Function Create( _
ByVal certBytes As Byte(), _
ByVal password As SecureString _
) As CertificateHolder
[C#]
public static CertificateHolder Create(
byte[] certBytes,
SecureString password
);

Parameters

certBytes
A byte array that contains data from an X.509 certificate.
password
The password required to access the X.509 certificate data.

Return Value

An instance of CertificateHolder

Exceptions

Exception Type | Condition
InvalidParameterException | Thrown if certBytes is null
InvalidParameterException | Thrown if password is null
SecurityException | Thrown if PKCS12 store contains no aliases
IOException | Thrown if there is wrong password or corrupted file.

Example

Shows how to create CertificateHolder objects.

[C#]

// 1: Load a PKCS #12 file into a byte array and apply its password to create the CertificateHolder
byte[] certBytes = File.ReadAllBytes(MyDir + "morzal.pfx");
CertificateHolder.Create(certBytes, "aw");

// 2: Pass a SecureString which contains the password instead of a normal string
SecureString password = new NetworkCredential("", "aw").SecurePassword;
CertificateHolder.Create(certBytes, password);

// 3: If the certificate has private keys corresponding to aliases, we can use the aliases to fetch their respective keys
// First, we'll check for valid aliases like this
using (FileStream certStream = new FileStream(MyDir + "morzal.pfx", FileMode.Open))
{
    Pkcs12Store pkcs12Store = new Pkcs12Store(certStream, "aw".ToCharArray());
    IEnumerator enumerator = pkcs12Store.Aliases.GetEnumerator();

    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
        {
            string currentAlias = enumerator.Current.ToString();
            if (pkcs12Store.IsKeyEntry(currentAlias) && pkcs12Store.GetKey(currentAlias).Key.IsPrivate)
            {
                Console.WriteLine($"Valid alias found: {enumerator.Current}");
            }
        }
    }
}

// For this file, we'll use an alias found above
CertificateHolder.Create(MyDir + "morzal.pfx", "aw", "c20be521-11ea-4976-81ed-865fbbfc9f24");

// If we leave the alias null, then the first possible alias that retrieves a private key will be used
CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

See Also

CertificateHolder Class | Aspose.Words Namespace | CertificateHolder.Create Overload List


CertificateHolder.Create Method (Byte[], String)

Creates CertificateHolder object using byte array of PKCS12 store and its password.

[Visual Basic]
Overloads Public Shared Function Create( _
ByVal certBytes As Byte(), _
ByVal password As String _
) As CertificateHolder
[C#]
public static CertificateHolder Create(
byte[] certBytes,
string password
);

Parameters

certBytes
A byte array that contains data from an X.509 certificate.
password
The password required to access the X.509 certificate data.

Return Value

An instance of CertificateHolder

Exceptions

Exception Type | Condition
InvalidParameterException | Thrown if certBytes is null
InvalidParameterException | Thrown if password is null
SecurityException | Thrown if PKCS12 store contains no aliases
IOException | Thrown if there is wrong password or corrupted file.

Example

Shows how to create CertificateHolder objects.

[C#]

// 1: Load a PKCS #12 file into a byte array and apply its password to create the CertificateHolder
byte[] certBytes = File.ReadAllBytes(MyDir + "morzal.pfx");
CertificateHolder.Create(certBytes, "aw");

// 2: Pass a SecureString which contains the password instead of a normal string
SecureString password = new NetworkCredential("", "aw").SecurePassword;
CertificateHolder.Create(certBytes, password);

// 3: If the certificate has private keys corresponding to aliases, we can use the aliases to fetch their respective keys
// First, we'll check for valid aliases like this
using (FileStream certStream = new FileStream(MyDir + "morzal.pfx", FileMode.Open))
{
    Pkcs12Store pkcs12Store = new Pkcs12Store(certStream, "aw".ToCharArray());
    IEnumerator enumerator = pkcs12Store.Aliases.GetEnumerator();

    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
        {
            string currentAlias = enumerator.Current.ToString();
            if (pkcs12Store.IsKeyEntry(currentAlias) && pkcs12Store.GetKey(currentAlias).Key.IsPrivate)
            {
                Console.WriteLine($"Valid alias found: {enumerator.Current}");
            }
        }
    }
}

// For this file, we'll use an alias found above
CertificateHolder.Create(MyDir + "morzal.pfx", "aw", "c20be521-11ea-4976-81ed-865fbbfc9f24");

// If we leave the alias null, then the first possible alias that retrieves a private key will be used
CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

See Also

CertificateHolder Class | Aspose.Words Namespace | CertificateHolder.Create Overload List


CertificateHolder.Create Method (X509Certificate2)

NOTE: This method is now obsolete.

Used for the compatibility with the public API which contains X509Certificate2. X509Certificate2 must have Private key and have the X509KeyStorageFlags.Exportable flag set.

Creates CertificateHolder object using already created X509Certificate2. The given X509Certificate2 must have private key. This method is obsolete and will be removed in the future releases.

[Visual Basic]
Overloads Public Shared Function Create( _
ByVal certificate As X509Certificate2 _
) As CertificateHolder
[C#]
public static CertificateHolder Create(
X509Certificate2 certificate
);

Parameters

certificate
X509Certificate2 which contains private key.

Return Value

An instance of CertificateHolder

See Also

CertificateHolder Class | Aspose.Words Namespace | CertificateHolder.Create Overload List


CertificateHolder.Create Method (String, String)

Creates CertificateHolder object using path to PKCS12 store and its password.

[Visual Basic]
Overloads Public Shared Function Create( _
ByVal fileName As String, _
ByVal password As String _
) As CertificateHolder
[C#]
public static CertificateHolder Create(
string fileName,
string password
);

Parameters

fileName
The name of a certificate file.
password
The password required to access the X.509 certificate data.

Return Value

An instance of CertificateHolder

Exceptions

Exception Type | Condition
InvalidParameterException | Thrown if fileName is null
InvalidParameterException | Thrown if password is null
SecurityException | Thrown if PKCS12 store contains no aliases
IOException | Thrown if there is wrong password or corrupted file.

Example

Shows how to sign documents using certificate holder and sign options.

[C#]

CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions { Comments = "My comment", SignTime = DateTime.Now };

using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.DigitalSignature.docx", FileMode.OpenOrCreate))
    {
        DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
    }
}

See Also

CertificateHolder Class | Aspose.Words Namespace | CertificateHolder.Create Overload List


CertificateHolder.Create Method (String, String, String)

Creates CertificateHolder object using path to PKCS12 store, its password and the alias by using which private key and certificate will be found.

[Visual Basic]
Overloads Public Shared Function Create( _
ByVal fileName As String, _
ByVal password As String, _
ByVal alias As String _
) As CertificateHolder
[C#]
public static CertificateHolder Create(
string fileName,
string password,
string alias
);

Parameters

fileName
The name of a certificate file.
password
The password required to access the X.509 certificate data.
alias
The associated alias for a certificate and its private key

Return Value

An instance of CertificateHolder

Exceptions

Exception Type | Condition
InvalidParameterException | Thrown if fileName is null
InvalidParameterException | Thrown if password is null
SecurityException | Thrown if PKCS12 store contains no aliases
IOException | Thrown if there is wrong password or corrupted file.
SecurityException | Thrown if there is no private key with the given alias

Example

Shows how to create CertificateHolder objects.

[C#]

// 1: Load a PKCS #12 file into a byte array and apply its password to create the CertificateHolder
byte[] certBytes = File.ReadAllBytes(MyDir + "morzal.pfx");
CertificateHolder.Create(certBytes, "aw");

// 2: Pass a SecureString which contains the password instead of a normal string
SecureString password = new NetworkCredential("", "aw").SecurePassword;
CertificateHolder.Create(certBytes, password);

// 3: If the certificate has private keys corresponding to aliases, we can use the aliases to fetch their respective keys
// First, we'll check for valid aliases like this
using (FileStream certStream = new FileStream(MyDir + "morzal.pfx", FileMode.Open))
{
    Pkcs12Store pkcs12Store = new Pkcs12Store(certStream, "aw".ToCharArray());
    IEnumerator enumerator = pkcs12Store.Aliases.GetEnumerator();

    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
        {
            string currentAlias = enumerator.Current.ToString();
            if (pkcs12Store.IsKeyEntry(currentAlias) && pkcs12Store.GetKey(currentAlias).Key.IsPrivate)
            {
                Console.WriteLine($"Valid alias found: {enumerator.Current}");
            }
        }
    }
}

// For this file, we'll use an alias found above
CertificateHolder.Create(MyDir + "morzal.pfx", "aw", "c20be521-11ea-4976-81ed-865fbbfc9f24");

// If we leave the alias null, then the first possible alias that retrieves a private key will be used
CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

See Also

CertificateHolder Class | Aspose.Words Namespace | CertificateHolder.Create Overload List


CleanupOptions Class

Allows to specify options for document cleaning.

For a list of all members of this type, see CleanupOptions Members.

System.Object
Aspose.Words.CleanupOptions

[Visual Basic]
Public Class CleanupOptions
[C#]
public class CleanupOptions

Example

Shows how to remove all unused styles and lists from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

CleanupOptions cleanupOptions = new CleanupOptions
{
    UnusedLists = true,
    UnusedStyles = true
};

doc.Cleanup(cleanupOptions);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CleanupOptions Members | Aspose.Words Namespace


CleanupOptions Members

CleanupOptions overview

Public Instance Constructors

CleanupOptions Constructor Initializes a new instance of the CleanupOptions class.

Public Instance Properties

UnusedLists | Specifies whether unused list and list definitions should be removed from document. Default value is true.
UnusedStyles | Specifies whether unused styles should be removed from document. Default value is true.

See Also

CleanupOptions Class | Aspose.Words Namespace


CleanupOptions Constructor

Initializes a new instance of the CleanupOptions class.

[Visual Basic]
Public Sub New()
[C#]
public CleanupOptions();

See Also

CleanupOptions Class | Aspose.Words Namespace


CleanupOptions Properties

The properties of the CleanupOptions class are listed below. For a complete list of CleanupOptions class members, see the CleanupOptions Members topic.

Public Instance Properties

UnusedLists | Specifies whether unused list and list definitions should be removed from document. Default value is true.
UnusedStyles | Specifies whether unused styles should be removed from document. Default value is true.

See Also

CleanupOptions Class | Aspose.Words Namespace


UnusedLists Property

Aspose.Words

CleanupOptions.UnusedLists Property

Specifies whether unused list and list definitions should be removed from document. Default value is true.

[Visual Basic]
Public Property UnusedLists As Boolean
[C#]
public bool UnusedLists {get; set;}

Example

Shows how to remove all unused styles and lists from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

CleanupOptions cleanupOptions = new CleanupOptions
{
    UnusedLists = true,
    UnusedStyles = true
};

doc.Cleanup(cleanupOptions);

See Also

CleanupOptions Class | Aspose.Words Namespace


UnusedStyles Property

Aspose.Words

CleanupOptions.UnusedStyles Property

Specifies whether unused styles should be removed from document. Default value is true.

[Visual Basic]
Public Property UnusedStyles As Boolean
[C#]
public bool UnusedStyles {get; set;}

Example

Shows how to remove all unused styles and lists from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

CleanupOptions cleanupOptions = new CleanupOptions
{
    UnusedLists = true,
    UnusedStyles = true
};

doc.Cleanup(cleanupOptions);

See Also

CleanupOptions Class | Aspose.Words Namespace


ComHelper Class

Provides methods for COM clients to load a document into Aspose.Words.

For a list of all members of this type, see ComHelper Members.

System.Object
Aspose.Words.ComHelper

[Visual Basic]
Public Class ComHelper
[C#]
public class ComHelper

Remarks

Use the ComHelper class to load a document from a file or stream into a Document object in a COM application.

The Document class provides a default constructor to create a new document and also provides overloaded constructors to load a document from a file or stream. If you are using Aspose.Words from a .NET application, you can use all of the Document constructors directly, but if you are using Aspose.Words from a COM application, only the default Document constructor is available.

Example

[VBScript]

Dim helper
Set helper = CreateObject("Aspose.Words.ComHelper")

Dim doc
Set doc = helper.Open(fileName)
Shows how to open documents using the ComHelper class.
[C#]

// If you need to open a document within a COM application,
// you will need to do so using the ComHelper class as instead of the Document constructor
ComHelper comHelper = new ComHelper();

// There are two ways of using a ComHelper to open a document
// 1: Using a filename
Document doc = comHelper.Open(MyDir + "Document.docx");
Assert.AreEqual("Hello World!\f", doc.GetText());

// 2: Using a Stream
using (FileStream stream = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    doc = comHelper.Open(stream);
    Assert.AreEqual("Hello World!\f", doc.GetText());
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ComHelper Members | Aspose.Words Namespace


ComHelper Members

ComHelper overview

Public Instance Constructors

ComHelper Constructor Initializes a new instance of this class.

Public Instance Methods

Open Overloaded. Allows a COM application to load a document.

See Also

ComHelper Class | Aspose.Words Namespace


ComHelper Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New()
[C#]
public ComHelper();

Example

Shows how to open documents using the ComHelper class.

[C#]

// If you need to open a document within a COM application,
// you will need to do so using the ComHelper class as instead of the Document constructor
ComHelper comHelper = new ComHelper();

// There are two ways of using a ComHelper to open a document
// 1: Using a filename
Document doc = comHelper.Open(MyDir + "Document.docx");
Assert.AreEqual("Hello World!\f", doc.GetText());

// 2: Using a Stream
using (FileStream stream = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    doc = comHelper.Open(stream);
    Assert.AreEqual("Hello World!\f", doc.GetText());
}

See Also

ComHelper Class | Aspose.Words Namespace


ComHelper Methods

The methods of the ComHelper class are listed below. For a complete list of ComHelper class members, see the ComHelper Members topic.

Public Instance Methods

Open Overloaded. Allows a COM application to load a document.

See Also

ComHelper Class | Aspose.Words Namespace


Open Method

Aspose.Words

ComHelper.Open Method

Allows a COM application to load a document.

Overload List

Allows a COM application to load Document from a stream.

public Document Open(Stream);

Allows a COM application to load a Document from a file.

public Document Open(string);

See Also

ComHelper Class | Aspose.Words Namespace


ComHelper.Open Method (Stream)

Allows a COM application to load Document from a stream.

[Visual Basic]
Overloads Public Function Open( _
ByVal stream As Stream _
) As Document
[C#]
public Document Open(
Stream stream
);

Parameters

stream
A .NET stream object that contains the document to load.

Return Value

A Document object that represents a Word document.

Remarks

This method is same as calling the Document constructor with a stream parameter.

Example

Shows how to open documents using the ComHelper class.

[C#]

// If you need to open a document within a COM application,
// you will need to do so using the ComHelper class as instead of the Document constructor
ComHelper comHelper = new ComHelper();

// There are two ways of using a ComHelper to open a document
// 1: Using a filename
Document doc = comHelper.Open(MyDir + "Document.docx");
Assert.AreEqual("Hello World!\f", doc.GetText());

// 2: Using a Stream
using (FileStream stream = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    doc = comHelper.Open(stream);
    Assert.AreEqual("Hello World!\f", doc.GetText());
}

See Also

ComHelper Class | Aspose.Words Namespace | ComHelper.Open Overload List


ComHelper.Open Method (String)

Allows a COM application to load a Document from a file.

[Visual Basic]
Overloads Public Function Open( _
ByVal fileName As String _
) As Document
[C#]
public Document Open(
string fileName
);

Parameters

fileName
Filename of the document to load.

Return Value

A Document object that represents a Word document.

Remarks

This method is same as calling the Document constructor with a file name parameter.

Example

[VBScript]

Dim helper
Set helper = CreateObject("Aspose.Words.ComHelper")

Dim doc
Set doc = helper.Open(fileName)
Shows how to open documents using the ComHelper class.
[C#]

// If you need to open a document within a COM application,
// you will need to do so using the ComHelper class as instead of the Document constructor
ComHelper comHelper = new ComHelper();

// There are two ways of using a ComHelper to open a document
// 1: Using a filename
Document doc = comHelper.Open(MyDir + "Document.docx");
Assert.AreEqual("Hello World!\f", doc.GetText());

// 2: Using a Stream
using (FileStream stream = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    doc = comHelper.Open(stream);
    Assert.AreEqual("Hello World!\f", doc.GetText());
}

See Also

ComHelper Class | Aspose.Words Namespace | ComHelper.Open Overload List


Comment Class

Represents a container for text of a comment.

For a list of all members of this type, see Comment Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.InlineStory
Aspose.Words.Comment

[Visual Basic]
NotInheritable Public Class Comment
Inherits InlineStory
[C#]
public sealed class Comment : InlineStory

Remarks

A comment is an annotation which is anchored to a region of text or to a position in text. A comment can contain an arbitrary amount of block-level content.

If a Comment object occurs on its own, the comment is anchored to the position of the Comment object.

To anchor a comment to a region of text three objects are required: Comment, CommentRangeStart and CommentRangeEnd. All three objects need to share the same Id value.

Comment is an inline-level node and can only be a child of Paragraph.

Comment can contain Paragraph and Table child nodes.

Example

Shows how to add a comment to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Comment comment = new Comment(doc, "Amy Lee", "AL", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
Shows how to add a comment with a reply to a document.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create new comment
Comment newComment = new Comment(doc, "John Doe", "J.D.", DateTime.Now);
newComment.SetText("My comment.");

// Add this comment to a document node
builder.CurrentParagraph.AppendChild(newComment);

// Add comment reply
newComment.AddReply("John Doe", "JD", new DateTime(2017, 9, 25, 12, 15, 0), "New reply");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Comment Members | Aspose.Words Namespace | CommentRangeStart | CommentRangeEnd


Comment Members

Comment overview

Public Instance Constructors

Comment Overloaded. Initializes a new instance of the Comment class.

Public Instance Properties

Ancestor | Returns the parent Comment object. Returns null for top-level comments.
Author | Returns or sets the author name for a comment.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DateTime | Gets the date and time that the comment was made.
Document (inherited from Node) | Gets the document to which this node belongs.
Done | Gets or sets flag indicating that the comment has been marked done.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from InlineStory) | Gets the first paragraph in the story.
Font (inherited from InlineStory) | Provides access to the font formatting of the anchor character of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Id | Gets the comment identifier.
Initial | Returns or sets the initials of the user associated with a specific comment.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from InlineStory) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from InlineStory) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from InlineStory) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from InlineStory) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from InlineStory) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Comment.
Paragraphs (inherited from InlineStory) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from InlineStory) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Replies | Returns a collection of Comment objects that are immediate children of the specified comment.
StoryType | Returns StoryType.Comments.
Tables (inherited from InlineStory) | Gets a collection of tables that are immediate children of the story.

Public Instance Methods

Accept | Accepts a visitor.
AddReply | Adds a reply to this comment.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum (inherited from InlineStory) | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveAllReplies | Removes all replies to this comment.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveReply | Removes the specified reply to this comment.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
SetText | This is a convenience method that allows to easily set text of the comment.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Comment Class | Aspose.Words Namespace | CommentRangeStart | CommentRangeEnd


Comment Constructor

Initializes a new instance of the Comment class.

Overload List

Initializes a new instance of the Comment class.

public Comment(DocumentBase);

Initializes a new instance of the Comment class.

public Comment(DocumentBase,string,string,DateTime);

See Also

Comment Class | Aspose.Words Namespace


Comment Constructor (DocumentBase)

Initializes a new instance of the Comment class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Comment(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Comment is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Comment to the document use InsertAfter or InsertBefore on the paragraph where you want the comment inserted.

After creating a comment, don't forget to set its Author, Initial and DateTime properties.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Comment Class | Aspose.Words Namespace | Comment Constructor Overload List


Comment Constructor (DocumentBase, String, String, DateTime)

Initializes a new instance of the Comment class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal author As String, _
ByVal initial As String, _
ByVal dateTime As Date _
)
[C#]
public Comment(
DocumentBase doc,
string author,
string initial,
DateTime dateTime
);

Parameters

doc
The owner document.
author
The author name for the comment. Cannot be null.
initial
The author initials for the comment. Cannot be null.
dateTime
The date and time for the comment.

Example

Shows how to add a comment to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Comment comment = new Comment(doc, "Amy Lee", "AL", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));

See Also

Comment Class | Aspose.Words Namespace | Comment Constructor Overload List


Comment Properties

The properties of the Comment class are listed below. For a complete list of Comment class members, see the Comment Members topic.

Public Instance Properties

Ancestor | Returns the parent Comment object. Returns null for top-level comments.
Author | Returns or sets the author name for a comment.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DateTime | Gets the date and time that the comment was made.
Document (inherited from Node) | Gets the document to which this node belongs.
Done | Gets or sets flag indicating that the comment has been marked done.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from InlineStory) | Gets the first paragraph in the story.
Font (inherited from InlineStory) | Provides access to the font formatting of the anchor character of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Id | Gets the comment identifier.
Initial | Returns or sets the initials of the user associated with a specific comment.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from InlineStory) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from InlineStory) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from InlineStory) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from InlineStory) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from InlineStory) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Comment.
Paragraphs (inherited from InlineStory) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from InlineStory) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Replies | Returns a collection of Comment objects that are immediate children of the specified comment.
StoryType | Returns StoryType.Comments.
Tables (inherited from InlineStory) | Gets a collection of tables that are immediate children of the story.

See Also

Comment Class | Aspose.Words Namespace | CommentRangeStart | CommentRangeEnd


Ancestor Property

Aspose.Words

Comment.Ancestor Property

Returns the parent Comment object. Returns null for top-level comments.

[Visual Basic]
Public ReadOnly Property Ancestor As Comment
[C#]
public Comment Ancestor {get;}

Example

Shows how to get all comments with all replies.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

// Get all comment from the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

// For all comments and replies we identify comment level and info about it
foreach (Comment comment in comments.OfType<Comment>())
{
    if (comment.Ancestor == null)
    {
        Console.WriteLine("This is a top-level comment\n");

        Console.WriteLine("Comment author: " + comment.Author);
        Console.WriteLine("Comment text: " + comment.GetText());

        foreach (Comment commentReply in comment.Replies.OfType<Comment>())
        {
            Console.WriteLine("This is a comment reply\n");

            Console.WriteLine("Comment author: " + commentReply.Author);
            Console.WriteLine("Comment text: " + commentReply.GetText());
        }
    }
}

See Also

Comment Class | Aspose.Words Namespace


Author Property

Aspose.Words

Comment.Author Property

Returns or sets the author name for a comment.

[Visual Basic]
Public Property Author As String
[C#]
public string Author {get; set;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to get all comments with all replies.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

// Get all comment from the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

// For all comments and replies we identify comment level and info about it
foreach (Comment comment in comments.OfType<Comment>())
{
    if (comment.Ancestor == null)
    {
        Console.WriteLine("This is a top-level comment\n");

        Console.WriteLine("Comment author: " + comment.Author);
        Console.WriteLine("Comment text: " + comment.GetText());

        foreach (Comment commentReply in comment.Replies.OfType<Comment>())
        {
            Console.WriteLine("This is a comment reply\n");

            Console.WriteLine("Comment author: " + commentReply.Author);
            Console.WriteLine("Comment text: " + commentReply.GetText());
        }
    }
}

See Also

Comment Class | Aspose.Words Namespace


DateTime Property

Aspose.Words

Comment.DateTime Property

Gets the date and time that the comment was made.

[Visual Basic]
Public Property DateTime As Date
[C#]
public DateTime DateTime {get; set;}

Remarks

Default is MinValue.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Comment Class | Aspose.Words Namespace


Done Property

Aspose.Words

Comment.Done Property

Gets or sets flag indicating that the comment has been marked done.

[Visual Basic]
Public Property Done As Boolean
[C#]
public bool Done {get; set;}

Example

Shows how to mark comment as Done.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

Comment comment = (Comment) comments[0];
CommentCollection repliesCollection = comment.Replies;

foreach (Comment childComment in repliesCollection)
{
    if (!childComment.Done)
    {
        // Update comment reply Done mark.
        childComment.Done = true;
    }
}
Shows how to create comments with replies and get all interested info.
[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Comment Class | Aspose.Words Namespace


Id Property

Aspose.Words

Comment.Id Property

Gets the comment identifier.

[Visual Basic]
Public ReadOnly Property Id As Integer
[C#]
public int Id {get;}

Remarks

The comment identifier allows to anchor a comment to a region of text in the document. The region must be demarcated using the CommentRangeStart and CommentRangeEnd object sharing the same identifier value as the Comment object.

You would use this value when looking for the CommentRangeStart and CommentRangeEnd nodes that are linked to this comment.

Comment identifiers are supposed to be unique across a document and Aspose.Words automatically maintains comment identifiers when loading, saving and combining documents.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Comment Class | Aspose.Words Namespace


Initial Property

Aspose.Words

Comment.Initial Property

Returns or sets the initials of the user associated with a specific comment.

[Visual Basic]
Public Property Initial As String
[C#]
public string Initial {get; set;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Comment Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Comment.NodeType Property

Returns NodeType.Comment.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Comment Class | Aspose.Words Namespace


Replies Property

Aspose.Words

Comment.Replies Property

Returns a collection of Comment objects that are immediate children of the specified comment.

[Visual Basic]
Public ReadOnly Property Replies As CommentCollection
[C#]
public CommentCollection Replies {get;}

Example

Shows how to get all comments with all replies.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

// Get all comment from the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

// For all comments and replies we identify comment level and info about it
foreach (Comment comment in comments.OfType<Comment>())
{
    if (comment.Ancestor == null)
    {
        Console.WriteLine("This is a top-level comment\n");

        Console.WriteLine("Comment author: " + comment.Author);
        Console.WriteLine("Comment text: " + comment.GetText());

        foreach (Comment commentReply in comment.Replies.OfType<Comment>())
        {
            Console.WriteLine("This is a comment reply\n");

            Console.WriteLine("Comment author: " + commentReply.Author);
            Console.WriteLine("Comment text: " + commentReply.GetText());
        }
    }
}

See Also

Comment Class | Aspose.Words Namespace


StoryType Property

Aspose.Words

Comment.StoryType Property

Returns StoryType.Comments.

[Visual Basic]
Overrides Public ReadOnly Property StoryType As StoryType
[C#]
public override StoryType StoryType {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

Comment Class | Aspose.Words Namespace


Comment Methods

The methods of the Comment class are listed below. For a complete list of Comment class members, see the Comment Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AddReply | Adds a reply to this comment.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum (inherited from InlineStory) | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveAllReplies | Removes all replies to this comment.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveReply | Removes the specified reply to this comment.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
SetText | This is a convenience method that allows to easily set text of the comment.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Comment Class | Aspose.Words Namespace | CommentRangeStart | CommentRangeEnd


Comment.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitCommentStart, then calls Accept for all child nodes of the comment and calls VisitCommentEnd at the end.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Comment Class | Aspose.Words Namespace


Comment.AddReply Method

Adds a reply to this comment.

[Visual Basic]
Public Function AddReply( _
ByVal author As String, _
ByVal initial As String, _
ByVal dateTime As Date, _
ByVal text As String _
) As Comment
[C#]
public Comment AddReply(
string author,
string initial,
DateTime dateTime,
string text
);

Parameters

author
The author name for the reply.
initial
The author initials for the reply.
dateTime
The date and time for the reply.
text
The reply text.

Return Value

The created Comment node for the reply.

Remarks

Due to the existing MS Office limitations only 1 level of replies is allowed in the document. An exception of type InvalidOperationException will be raised if this method is called on the existing Reply comment.

Example

Shows how to add a comment with a reply to a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create new comment
Comment newComment = new Comment(doc, "John Doe", "J.D.", DateTime.Now);
newComment.SetText("My comment.");

// Add this comment to a document node
builder.CurrentParagraph.AppendChild(newComment);

// Add comment reply
newComment.AddReply("John Doe", "JD", new DateTime(2017, 9, 25, 12, 15, 0), "New reply");

See Also

Comment Class | Aspose.Words Namespace


Comment.RemoveAllReplies Method

Removes all replies to this comment.

[Visual Basic]
Public Sub RemoveAllReplies()
[C#]
public void RemoveAllReplies();

Remarks

All constituent nodes of the replies will be deleted from the document.

Example

Shows how to remove comment replies.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
Comment comment = (Comment) comments[0];

comment.RemoveAllReplies();

See Also

Comment Class | Aspose.Words Namespace


Comment.RemoveReply Method

Removes the specified reply to this comment.

[Visual Basic]
Public Sub RemoveReply( _
ByVal reply As Comment _
)
[C#]
public void RemoveReply(
Comment reply
);

Parameters

reply
The comment node of the deleting reply.

Remarks

All constituent nodes of the reply will be deleted from the document.

Example

Shows how to remove specific comment reply.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

Comment parentComment = (Comment) comments[0];
CommentCollection repliesCollection = parentComment.Replies;

// Remove the first reply to comment
parentComment.RemoveReply(repliesCollection[0]);

See Also

Comment Class | Aspose.Words Namespace


Comment.SetText Method

This is a convenience method that allows to easily set text of the comment.

[Visual Basic]
Public Sub SetText( _
ByVal text As String _
)
[C#]
public void SetText(
string text
);

Parameters

text
The new text of the comment.

Remarks

This method allows to quickly set text of a comment from a string. The string can contain paragraph breaks, this will create paragraphs of text in the comment accordingly. If you want to insert more complex elements into the comment, for example bookmarks or tables or apply rich formatting, then you need to use the appropriate node classes to build up the comment text.

Example

Shows how to add a comment with a reply to a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create new comment
Comment newComment = new Comment(doc, "John Doe", "J.D.", DateTime.Now);
newComment.SetText("My comment.");

// Add this comment to a document node
builder.CurrentParagraph.AppendChild(newComment);

// Add comment reply
newComment.AddReply("John Doe", "JD", new DateTime(2017, 9, 25, 12, 15, 0), "New reply");

See Also

Comment Class | Aspose.Words Namespace


CommentCollection Class

Provides typed access to a collection of Comment nodes.

For a list of all members of this type, see CommentCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.CommentCollection

[Visual Basic]
Public Class CommentCollection
Inherits NodeCollection
[C#]
public class CommentCollection : NodeCollection

Example

Shows how to mark comment as Done.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

Comment comment = (Comment) comments[0];
CommentCollection repliesCollection = comment.Replies;

foreach (Comment childComment in repliesCollection)
{
    if (!childComment.Done)
    {
        // Update comment reply Done mark.
        childComment.Done = true;
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CommentCollection Members | Aspose.Words Namespace


CommentCollection Members

CommentCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Comment at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray (inherited from NodeCollection) | Copies all nodes from the collection to a new array of nodes.

See Also

CommentCollection Class | Aspose.Words Namespace


CommentCollection Properties

The properties of the CommentCollection class are listed below. For a complete list of CommentCollection class members, see the CommentCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Comment at the given index.

See Also

CommentCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

CommentCollection.Item Property

Retrieves a Comment at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Comment
[C#]
new public Comment this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to remove specific comment reply.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

Comment parentComment = (Comment) comments[0];
CommentCollection repliesCollection = parentComment.Replies;

// Remove the first reply to comment
parentComment.RemoveReply(repliesCollection[0]);

See Also

CommentCollection Class | Aspose.Words Namespace


CommentRangeEnd Class

Denotes the end of a region of text that has a comment associated with it.

For a list of all members of this type, see CommentRangeEnd Members.

System.Object
Aspose.Words.Node
Aspose.Words.CommentRangeEnd

[Visual Basic]
NotInheritable Public Class CommentRangeEnd
Inherits Node
[C#]
public sealed class CommentRangeEnd : Node

Remarks

To create a comment anchored to a region of text, you need to create a Comment and then create CommentRangeStart and CommentRangeEnd and set their identifiers to the same Id value.

CommentRangeEnd is an inline-level node and can only be a child of Paragraph.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CommentRangeEnd Members | Aspose.Words Namespace | Comment | CommentRangeStart


CommentRangeEnd Members

CommentRangeEnd overview

Public Instance Constructors

CommentRangeEnd Constructor Initializes a new instance of this class.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Id | Specifies the identifier of the comment to which this region is linked to.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns CommentRangeEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

CommentRangeEnd Class | Aspose.Words Namespace | Comment | CommentRangeStart


CommentRangeEnd Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase, _
ByVal id As Integer _
)
[C#]
public CommentRangeEnd(
DocumentBase doc,
int id
);

Parameters

doc
The owner document.
id
The comment identifier to which this object is linked.

Remarks

When CommentRangeEnd is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append a CommentRangeEnd to the document use InsertAfter or InsertBefore on the paragraph where you want the comment inserted.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

CommentRangeEnd Class | Aspose.Words Namespace


CommentRangeEnd Properties

The properties of the CommentRangeEnd class are listed below. For a complete list of CommentRangeEnd class members, see the CommentRangeEnd Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Id | Specifies the identifier of the comment to which this region is linked to.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns CommentRangeEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

CommentRangeEnd Class | Aspose.Words Namespace | Comment | CommentRangeStart


Id Property

Aspose.Words

CommentRangeEnd.Id Property

Specifies the identifier of the comment to which this region is linked to.

[Visual Basic]
Public Property Id As Integer
[C#]
public int Id {get; set;}

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

CommentRangeEnd Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

CommentRangeEnd.NodeType Property

Returns CommentRangeEnd.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

CommentRangeEnd Class | Aspose.Words Namespace


CommentRangeEnd Methods

The methods of the CommentRangeEnd class are listed below. For a complete list of CommentRangeEnd class members, see the CommentRangeEnd Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

CommentRangeEnd Class | Aspose.Words Namespace | Comment | CommentRangeStart


CommentRangeEnd.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitCommentRangeEnd.

For more info see the Visitor design pattern.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

CommentRangeEnd Class | Aspose.Words Namespace


CommentRangeStart Class

Denotes the start of a region of text that has a comment associated with it.

For a list of all members of this type, see CommentRangeStart Members.

System.Object
Aspose.Words.Node
Aspose.Words.CommentRangeStart

[Visual Basic]
NotInheritable Public Class CommentRangeStart
Inherits Node
[C#]
public sealed class CommentRangeStart : Node

Remarks

To create a comment anchored to a region of text, you need to create a Comment and then create CommentRangeStart and CommentRangeEnd and set their identifiers to the same Id value.

CommentRangeStart is an inline-level node and can only be a child of Paragraph.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CommentRangeStart Members | Aspose.Words Namespace | Comment | CommentRangeEnd


CommentRangeStart Members

CommentRangeStart overview

Public Instance Constructors

CommentRangeStart Constructor Initializes a new instance of this class.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Id | Specifies the identifier of the comment to which this region is linked.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns CommentRangeStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

CommentRangeStart Class | Aspose.Words Namespace | Comment | CommentRangeEnd


CommentRangeStart Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase, _
ByVal id As Integer _
)
[C#]
public CommentRangeStart(
DocumentBase doc,
int id
);

Parameters

doc
The owner document.
id
The comment identifier to which this object is linked.

Remarks

When CommentRangeStart is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append a CommentRangeStart to the document use InsertAfter or InsertBefore on the paragraph where you want the comment inserted.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

CommentRangeStart Class | Aspose.Words Namespace


CommentRangeStart Properties

The properties of the CommentRangeStart class are listed below. For a complete list of CommentRangeStart class members, see the CommentRangeStart Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Id | Specifies the identifier of the comment to which this region is linked.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns CommentRangeStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

CommentRangeStart Class | Aspose.Words Namespace | Comment | CommentRangeEnd


Id Property

Aspose.Words

CommentRangeStart.Id Property

Specifies the identifier of the comment to which this region is linked.

[Visual Basic]
Public Property Id As Integer
[C#]
public int Id {get; set;}

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

CommentRangeStart Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

CommentRangeStart.NodeType Property

Returns CommentRangeStart.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

CommentRangeStart Class | Aspose.Words Namespace


CommentRangeStart Methods

The methods of the CommentRangeStart class are listed below. For a complete list of CommentRangeStart class members, see the CommentRangeStart Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

CommentRangeStart Class | Aspose.Words Namespace | Comment | CommentRangeEnd


CommentRangeStart.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitCommentRangeStart.

For more info see the Visitor design pattern.

Example

Shows how to create comments with replies and get all interested info.

[C#]

public void CreateCommentsAndPrintAllInfo()
{
    Document doc = new Document();
    doc.RemoveAllChildren();

    Section sect = (Section)doc.AppendChild(new Section(doc));
    Body body = (Body)sect.AppendChild(new Body(doc));

    // Create a commented text with several comment replies
    for (int i = 0; i <= 10; i++)
    {
        Comment newComment = CreateComment(doc, "VDeryushev", "VD", DateTime.Now, "My test comment " + i);

        Paragraph para = (Paragraph)body.AppendChild(new Paragraph(doc));
        para.AppendChild(new CommentRangeStart(doc, newComment.Id));
        para.AppendChild(new Run(doc, "Commented text " + i));
        para.AppendChild(new CommentRangeEnd(doc, newComment.Id));
        para.AppendChild(newComment);

        for (int y = 0; y <= 2; y++)
        {
            newComment.AddReply("John Doe", "JD", DateTime.Now, "New reply " + y);
        }
    }

    // Look at information of our comments
    PrintAllCommentInfo(ExtractComments(doc));
}

/// <summary>
/// Create a new comment
/// </summary>
public static Comment CreateComment(Document doc, string author, string initials, DateTime dateTime, string text)
{
    Comment newComment = new Comment(doc)
    {
        Author = author, Initial = initials, DateTime = dateTime
    };
    newComment.SetText(text);

    return newComment;
}

/// <summary>
/// Extract comments from the document without replies
/// </summary>
public static List<Comment> ExtractComments(Document doc)
{
    List<Comment> collectedComments = new List<Comment>();

    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);

    foreach (Comment comment in comments)
    {
        // All replies have ancestor, so we will add this check
        if (comment.Ancestor == null)
        {
            collectedComments.Add(comment);
        }
    }

    return collectedComments;
}

/// <summary>
/// Use an iterator and a visitor to print info of every comment from within a document.
/// </summary>
private static void PrintAllCommentInfo(List<Comment> comments)
{
    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter commentVisitor = new CommentInfoPrinter();

    // Get the enumerator from the document's comment collection and iterate over the comments
    using (IEnumerator<Comment> enumerator = comments.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Comment currentComment = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our comments
            if (currentComment != null)
            {
                // Get CommentRangeStart from our current comment and construct its information
                CommentRangeStart commentRangeStart = (CommentRangeStart)currentComment.PreviousSibling.PreviousSibling.PreviousSibling;
                commentRangeStart.Accept(commentVisitor);

                // Construct current comment information
                currentComment.Accept(commentVisitor);

                // Get CommentRangeEnd from our current comment and construct its information
                CommentRangeEnd commentRangeEnd = (CommentRangeEnd)currentComment.PreviousSibling;
                commentRangeEnd.Accept(commentVisitor);
            }
        }

        // Output of all information received
        Console.WriteLine(commentVisitor.GetText());
    }
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end] ID: " + commentRangeEnd.Id + "\n");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(string.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(string text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

CommentRangeStart Class | Aspose.Words Namespace


CompareOptions Class

Allows to choose advanced options for document comparison operation.

For a list of all members of this type, see CompareOptions Members.

System.Object
Aspose.Words.CompareOptions

[Visual Basic]
Public Class CompareOptions
[C#]
public class CompareOptions

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CompareOptions Members | Aspose.Words Namespace


CompareOptions Members

CompareOptions overview

Public Instance Constructors

CompareOptions Constructor Initializes a new instance of the CompareOptions class.

Public Instance Properties

IgnoreCaseChanges | True indicates that documents comparison is case insensitive. By default comparison is case sensitive.
IgnoreComments | Specifies whether to compare differences in comments. By default comments are not ignored.
IgnoreFields | Specifies whether to compare differences in fields. By default fields are not ignored.
IgnoreFootnotes | Specifies whether to compare differences in footnotes and endnotes. By default footnotes are not ignored.
IgnoreFormatting | True indicates that formatting is ignored. By default document formatting is not ignored.
IgnoreHeadersAndFooters | True indicates that headers and footers content is ignored. By default headers and footers are not ignored.
IgnoreTables | Specifies whether to compare the differences in data contained in tables. By default tables are not ignored.
IgnoreTextboxes | Specifies whether to compare differences in the data contained within text boxes. By default textboxes are not ignored.
Target | Specifies which document shall be used as a target during comparison.

See Also

CompareOptions Class | Aspose.Words Namespace


CompareOptions Constructor

Initializes a new instance of the CompareOptions class.

[Visual Basic]
Public Sub New()
[C#]
public CompareOptions();

See Also

CompareOptions Class | Aspose.Words Namespace


CompareOptions Properties

The properties of the CompareOptions class are listed below. For a complete list of CompareOptions class members, see the CompareOptions Members topic.

Public Instance Properties

IgnoreCaseChanges | True indicates that documents comparison is case insensitive. By default comparison is case sensitive.
IgnoreComments | Specifies whether to compare differences in comments. By default comments are not ignored.
IgnoreFields | Specifies whether to compare differences in fields. By default fields are not ignored.
IgnoreFootnotes | Specifies whether to compare differences in footnotes and endnotes. By default footnotes are not ignored.
IgnoreFormatting | True indicates that formatting is ignored. By default document formatting is not ignored.
IgnoreHeadersAndFooters | True indicates that headers and footers content is ignored. By default headers and footers are not ignored.
IgnoreTables | Specifies whether to compare the differences in data contained in tables. By default tables are not ignored.
IgnoreTextboxes | Specifies whether to compare differences in the data contained within text boxes. By default textboxes are not ignored.
Target | Specifies which document shall be used as a target during comparison.

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreCaseChanges Property

Aspose.Words

CompareOptions.IgnoreCaseChanges Property

True indicates that documents comparison is case insensitive. By default comparison is case sensitive.

[Visual Basic]
Public Property IgnoreCaseChanges As Boolean
[C#]
public bool IgnoreCaseChanges {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreComments Property

Aspose.Words

CompareOptions.IgnoreComments Property

Specifies whether to compare differences in comments. By default comments are not ignored.

[Visual Basic]
Public Property IgnoreComments As Boolean
[C#]
public bool IgnoreComments {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreFields Property

Aspose.Words

CompareOptions.IgnoreFields Property

Specifies whether to compare differences in fields. By default fields are not ignored.

[Visual Basic]
Public Property IgnoreFields As Boolean
[C#]
public bool IgnoreFields {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreFootnotes Property

Aspose.Words

CompareOptions.IgnoreFootnotes Property

Specifies whether to compare differences in footnotes and endnotes. By default footnotes are not ignored.

[Visual Basic]
Public Property IgnoreFootnotes As Boolean
[C#]
public bool IgnoreFootnotes {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreFormatting Property

Aspose.Words

CompareOptions.IgnoreFormatting Property

True indicates that formatting is ignored. By default document formatting is not ignored.

[Visual Basic]
Public Property IgnoreFormatting As Boolean
[C#]
public bool IgnoreFormatting {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreHeadersAndFooters Property

Aspose.Words

CompareOptions.IgnoreHeadersAndFooters Property

True indicates that headers and footers content is ignored. By default headers and footers are not ignored.

[Visual Basic]
Public Property IgnoreHeadersAndFooters As Boolean
[C#]
public bool IgnoreHeadersAndFooters {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreTables Property

Aspose.Words

CompareOptions.IgnoreTables Property

Specifies whether to compare the differences in data contained in tables. By default tables are not ignored.

[Visual Basic]
Public Property IgnoreTables As Boolean
[C#]
public bool IgnoreTables {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


IgnoreTextboxes Property

Aspose.Words

CompareOptions.IgnoreTextboxes Property

Specifies whether to compare differences in the data contained within text boxes. By default textboxes are not ignored.

[Visual Basic]
Public Property IgnoreTextboxes As Boolean
[C#]
public bool IgnoreTextboxes {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


Target Property

Aspose.Words

CompareOptions.Target Property

Specifies which document shall be used as a target during comparison.

[Visual Basic]
Public Property Target As ComparisonTargetType
[C#]
public ComparisonTargetType Target {get; set;}

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

CompareOptions Class | Aspose.Words Namespace


ComparisonTargetType Enumeration

Allows to specify base document which will be used during comparison. Default value is Current.

[Visual Basic]
Public Enum ComparisonTargetType
[C#]
public enum ComparisonTargetType

Remarks

Relates to Microsoft Word "Show changes in" option in "Compare Documents" dialog box.

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

Members

Member Name | Description | Value
Current | This document is used as a base during comparison. | 0
New | Other document is used as a base during comparison. | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


CompositeNode Class

Base class for nodes that can contain other nodes.

For a list of all members of this type, see CompositeNode Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Derived types

[Visual Basic]
MustInherit Public Class CompositeNode
Inherits Node
Implements IEnumerable`1([Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable, IXPathNavigable
[C#]
public abstract class CompositeNode : Node, 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable, IXPathNavigable

Remarks

A document is represented as a tree of nodes, similar to DOM or XmlDocument.

For more info see the Composite design pattern.

The CompositeNode class:

  • Provides access to the child nodes.
  • Implements Composite operations such as insert and remove children.
  • Provides methods for XPath navigation.

Example

Shows how to extract a specific child node from a CompositeNode by using the GetChild method and passing the NodeType and index.

[C#]

Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CompositeNode Members | Aspose.Words Namespace


CompositeNode Members

CompositeNode overview

Public Instance Properties

ChildNodes | Gets all immediate child nodes of this node.
Count | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild | Gets the first child of the node.
HasChildNodes | Returns true if this node has any child nodes.
IsComposite | Returns true as this node can have child nodes.
LastChild | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild | Returns an Nth child node that matches the specified type.
GetChildNodes | Returns a live collection of child nodes that match the specified type.
GetEnumerator | Provides support for the for each style iteration over the child nodes of this node.
GetText | Gets the text of this node and of all its children.
IndexOf | Returns the index of the specified child node in the child node array.
InsertAfter | Inserts the specified node immediately after the specified reference node.
InsertBefore | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren | Removes all the child nodes of the current node.
RemoveChild | Removes the specified child node.
RemoveSmartTags | Removes all SmartTag descendant nodes of the current node.
SelectNodes | Selects a list of nodes matching the XPath expression.
SelectSingleNode | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode Properties

The properties of the CompositeNode class are listed below. For a complete list of CompositeNode class members, see the CompositeNode Members topic.

Public Instance Properties

ChildNodes | Gets all immediate child nodes of this node.
Count | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild | Gets the first child of the node.
HasChildNodes | Returns true if this node has any child nodes.
IsComposite | Returns true as this node can have child nodes.
LastChild | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

CompositeNode Class | Aspose.Words Namespace


ChildNodes Property

Aspose.Words

CompositeNode.ChildNodes Property

Gets all immediate child nodes of this node.

[Visual Basic]
Public ReadOnly Property ChildNodes As NodeCollection
[C#]
public NodeCollection ChildNodes {get;}

Remarks

Note, ChildNodes is equivalent to calling GetChildNodes(NodeType.Any, false) and creates and returns a new collection every time it is accessed.

If there are no child nodes, this property returns an empty collection.

Example

Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.

[C#]

NodeCollection children = paragraph.ChildNodes;
foreach (Node child in children)
{
    // Paragraph may contain children of various types such as runs, shapes and so on.
    if (child.NodeType.Equals(NodeType.Run))
    {
        // Say we found the node that we want, do something useful.
        Run run = (Run) child;
        Console.WriteLine(run.Text);
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


Count Property

Aspose.Words

CompositeNode.Count Property

Gets the number of immediate children of this node.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to add, update and delete child nodes from within a CompositeNode.

[C#]

Document doc = new Document();

// An empty document has one paragraph by default
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);

// A paragraph is a composite node because it can contain runs, which are another type of node
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
Run paragraphText = new Run(doc, "Initial text. ");
paragraph.AppendChild(paragraphText);

// We will place these 3 children into the main text of our paragraph
Run run1 = new Run(doc, "Run 1. ");
Run run2 = new Run(doc, "Run 2. ");
Run run3 = new Run(doc, "Run 3. ");

// We initialized them but not in our paragraph yet
Assert.AreEqual("Initial text. " + (char) 12, paragraph.GetText());

// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph.InsertBefore(run2, paragraphText);

// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph.InsertAfter(run3, paragraphText);

// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph.PrependChild(run1);

Assert.AreEqual("Run 1. Run 2. Initial text. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(4, paragraph.GetChildNodes(NodeType.Any, true).Count);

// Access the child node collection and update/delete children
((Run) paragraph.GetChildNodes(NodeType.Run, true)[1]).Text = "Updated run 2. ";
paragraph.GetChildNodes(NodeType.Run, true).Remove(paragraphText);

Assert.AreEqual("Run 1. Updated run 2. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(3, paragraph.GetChildNodes(NodeType.Any, true).Count);

See Also

CompositeNode Class | Aspose.Words Namespace


FirstChild Property

Aspose.Words

CompositeNode.FirstChild Property

Gets the first child of the node.

[Visual Basic]
Public ReadOnly Property FirstChild As Node
[C#]
public Node FirstChild {get;}

Remarks

If there is no first child node, a null is returned.

Example

Shows how to enumerate immediate child nodes of a composite node using NextSibling. In this example we enumerate all paragraphs of a section body.

[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Loop starting from the first child until we reach null.
for (Node node = body.FirstChild; node != null; node = node.NextSibling)
{
    // Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType));
}
Shows how to efficiently visit all direct and indirect children of a composite node.
[C#]

public void RecurseAllNodes()
{
    // Open a document.
    Document doc = new Document(MyDir + "Node.RecurseAllNodes.doc");

    // Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc);
}

/// <summary>
/// A simple function that will walk through all children of a specified node recursively
/// and print the type of each node to the screen.
/// </summary>
public void TraverseAllNodes(CompositeNode parentNode)
{
    // This is the most efficient way to loop through immediate children of a node.
    for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
    {
        // Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType));

        // Recurse into the node if it is a composite node.
        if (childNode.IsComposite)
            TraverseAllNodes((CompositeNode) childNode);
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


HasChildNodes Property

Aspose.Words

CompositeNode.HasChildNodes Property

Returns true if this node has any child nodes.

[Visual Basic]
Public ReadOnly Property HasChildNodes As Boolean
[C#]
public bool HasChildNodes {get;}

Example

Demonstrates how to use the InsertDocument method to insert a document into a merge field during mail merge.

[C#]

// Open the main document.
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    // Add a handler to MergeField event
    mainDoc.MailMerge.FieldMergingCallback = new InsertDocumentAtMailMergeHandler();

    // The main document has a merge field in it called "Document_1".
    // The corresponding data for this field contains fully qualified path to the document
    // that should be inserted to this field.
    mainDoc.MailMerge.Execute(new String[] { "Document_1" }, new object[] { MyDir + "InsertDocument2.doc" });

    mainDoc.Save(ArtifactsDir + "InsertDocumentAtMailMerge.doc");
}

private class InsertDocumentAtMailMergeHandler : IFieldMergingCallback
{
    /// <summary>
    /// This handler makes special processing for the "Document_1" field.
    /// The field value contains the path to load the document.
    /// We load the document and insert it into the current merge field.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        if (args.DocumentFieldName == "Document_1")
        {
            // Use document builder to navigate to the merge field with the specified name.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);

            // The name of the document to load and insert is stored in the field value.
            Document subDoc = new Document((String) args.FieldValue);

            // Insert the document.
            InsertDocument(builder.CurrentParagraph, subDoc);

            // The paragraph that contained the merge field might be empty now and you probably want to delete it.
            if (!builder.CurrentParagraph.HasChildNodes)
                builder.CurrentParagraph.Remove();

            // Indicate to the mail merge engine that we have inserted what we wanted.
            args.Text = null;
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


IsComposite Property

Aspose.Words

CompositeNode.IsComposite Property

Returns true as this node can have child nodes.

[Visual Basic]
Overrides Public ReadOnly Property IsComposite As Boolean
[C#]
public override bool IsComposite {get;}

Example

Shows how to efficiently visit all direct and indirect children of a composite node.

[C#]

public void RecurseAllNodes()
{
    // Open a document.
    Document doc = new Document(MyDir + "Node.RecurseAllNodes.doc");

    // Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc);
}

/// <summary>
/// A simple function that will walk through all children of a specified node recursively
/// and print the type of each node to the screen.
/// </summary>
public void TraverseAllNodes(CompositeNode parentNode)
{
    // This is the most efficient way to loop through immediate children of a node.
    for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
    {
        // Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType));

        // Recurse into the node if it is a composite node.
        if (childNode.IsComposite)
            TraverseAllNodes((CompositeNode) childNode);
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


LastChild Property

Aspose.Words

CompositeNode.LastChild Property

Gets the last child of the node.

[Visual Basic]
Public ReadOnly Property LastChild As Node
[C#]
public Node LastChild {get;}

Remarks

If there is no last child node, a null is returned.

Example

Demonstrates use of methods of Node and CompositeNode to remove a section before the last section in the document.

[C#]

// Document is a CompositeNode and LastChild returns the last child node in the Document node.
// Since the Document can contain only Section nodes, the last child is the last section.
Node lastSection = doc.LastChild;

// Each node knows its next and previous sibling nodes.
// Previous sibling of a section is a section before the specified section.
// If the node is the first child, PreviousSibling will return null.
Node sectionBeforeLast = lastSection.PreviousSibling;

if (sectionBeforeLast != null)
    doc.RemoveChild(sectionBeforeLast);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode Methods

The methods of the CompositeNode class are listed below. For a complete list of CompositeNode class members, see the CompositeNode Members topic.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild | Returns an Nth child node that matches the specified type.
GetChildNodes | Returns a live collection of child nodes that match the specified type.
GetEnumerator | Provides support for the for each style iteration over the child nodes of this node.
GetText | Gets the text of this node and of all its children.
IndexOf | Returns the index of the specified child node in the child node array.
InsertAfter | Inserts the specified node immediately after the specified reference node.
InsertBefore | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren | Removes all the child nodes of the current node.
RemoveChild | Removes the specified child node.
RemoveSmartTags | Removes all SmartTag descendant nodes of the current node.
SelectNodes | Selects a list of nodes matching the XPath expression.
SelectSingleNode | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.AppendChild Method

Adds the specified node to the end of the list of child nodes for this node.

[Visual Basic]
Public Function AppendChild( _
ByVal newChild As Node _
) As Node
[C#]
public Node AppendChild(
Node newChild
);

Parameters

newChild
The node to add.

Return Value

The node added.

Remarks

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use ImportNode to import the node to the current document. The imported node can then be inserted into the current document.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.GetChild Method

Returns an Nth child node that matches the specified type.

[Visual Basic]
Public Function GetChild( _
ByVal nodeType As NodeType, _
ByVal index As Integer, _
ByVal isDeep As Boolean _
) As Node
[C#]
public Node GetChild(
NodeType nodeType,
int index,
bool isDeep
);

Parameters

nodeType
Specifies the type of the child node.
index
Zero based index of the child node to select. Negative indexes are also allowed and indicate access from the end, that is -1 means the last node.
isDeep
True to select from all child nodes recursively. False to select only among immediate children. See remarks for more info.

Return Value

The child node that matches the criteria or null if no matching node is found.

Remarks

If index is out of range, a null is returned.

Note that markup nodes (StructuredDocumentTag and SmartTag) are traversed even when isDeep = false and GetChild is invoked for non-markup node type. For example if the first run in a para is wrapped in a StructuredDocumentTag, it will still be returned by GetChild(NodeType.Run, 0, false).

Example

Shows how to extract a specific child node from a CompositeNode by using the GetChild method and passing the NodeType and index.

[C#]

Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);
Shows how to test if a node is inside a field by using an XPath expression.
[C#]

// Let's pick a document we know has some fields in.
Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

// Let's say we want to check if the Run below is inside a field.
Run run = (Run) doc.GetChild(NodeType.Run, 5, true);

// Evaluate the XPath expression. The resulting NodeList will contain all nodes found inside a field a field (between FieldStart
// and FieldEnd exclusive). There can however be FieldStart and FieldEnd nodes in the list if there are nested fields
// in the path. Currently does not find rare fields in which the FieldCode or FieldResult spans across multiple paragraphs.
NodeList resultList =
    doc.SelectNodes("//FieldStart/following-sibling::node()[following-sibling::FieldEnd]");

// Check if the specified run is one of the nodes that are inside the field.
foreach (Node node in resultList)
{
    if (node == run)
    {
        Console.WriteLine("The node is found inside a field");
        break;
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.GetChildNodes Method

Returns a live collection of child nodes that match the specified type.

[Visual Basic]
Public Function GetChildNodes( _
ByVal nodeType As NodeType, _
ByVal isDeep As Boolean _
) As NodeCollection
[C#]
public NodeCollection GetChildNodes(
NodeType nodeType,
bool isDeep
);

Parameters

nodeType
Specifies the type of nodes to select.
isDeep
True to select from all child nodes recursively. False to select only among immediate children.

Return Value

A live collection of child nodes of the specified type.

Remarks

The collection of nodes returned by this method is always live.

A live collection is always in sync with the document. For example, if you selected all sections in a document and enumerate through the collection deleting the sections, the section is removed from the collection immediately when it is removed from the document.

Example

Demonstrates how to remove a specified TOC from a document.

[C#]

// Open a document which contains a TOC.
Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Remove the first TOC from the document.
Field tocField = doc.Range.Fields[0];
tocField.Remove();

// Save the output.
doc.Save(ArtifactsDir + "Document.TableOfContentsRemoveTOC.doc");
Shows how to extract images from a document and save them as files.
[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.GetEnumerator Method

Provides support for the for each style iteration over the child nodes of this node.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Node) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Node> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.

[C#]

NodeCollection children = paragraph.ChildNodes;
foreach (Node child in children)
{
    // Paragraph may contain children of various types such as runs, shapes and so on.
    if (child.NodeType.Equals(NodeType.Run))
    {
        // Say we found the node that we want, do something useful.
        Run run = (Run) child;
        Console.WriteLine(run.Text);
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.GetText Method

Gets the text of this node and of all its children.

[Visual Basic]
Overrides Public Function GetText() As String
[C#]
public override string GetText();

Remarks

The returned string includes all control and special characters as described in ControlChar.

Example

Finds and outputs all paragraphs in a document that are bulleted or numbered.

[C#]

NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph para in paras.OfType<Paragraph>())
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}",
            para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}
Shows the difference between calling the GetText and ToString methods on a node.
[C#]

Document doc = new Document();

// Enter a dummy field into the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField("MERGEFIELD Field");

// GetText will retrieve all field codes and special characters
Console.WriteLine("GetText() Result: " + doc.GetText());

// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
Console.WriteLine("ToString() Result: " + doc.ToString(SaveFormat.Text));

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.IndexOf Method

Returns the index of the specified child node in the child node array.

[Visual Basic]
Public Function IndexOf( _
ByVal child As Node _
) As Integer
[C#]
public int IndexOf(
Node child
);

Remarks

Returns -1 if the node is not found in the child nodes.

Example

Retrieves the index of a cell in a row.

[C#]

int cellIndex = row.IndexOf(cell);
Retrieves the index of a row in a table.
[C#]

int rowIndex = table.IndexOf(row);
Shows how to get the index of a given child node from its parent.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Get the body of the first section in the document.
Body body = doc.FirstSection.Body;
// Retrieve the index of the last paragraph in the body.
int index = body.ChildNodes.IndexOf(body.LastParagraph);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.InsertAfter Method

Inserts the specified node immediately after the specified reference node.

[Visual Basic]
Public Function InsertAfter( _
ByVal newChild As Node, _
ByVal refChild As Node _
) As Node
[C#]
public Node InsertAfter(
Node newChild,
Node refChild
);

Parameters

newChild
The Node to insert.
refChild
The Node that is the reference node. The newNode is placed after the refNode.

Return Value

The inserted node.

Remarks

If refChild is null, inserts newChild at the beginning of the list of child nodes.

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use ImportNode to import the node to the current document. The imported node can then be inserted into the current document.

Example

Shows how to replace all textboxes with images.

[C#]

Document doc = new Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

// This gets a live collection of all shape nodes in the document.
NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

// Since we will be adding/removing nodes, it is better to copy all collection
// into a fixed size array, otherwise iterator will be invalidated.
Node[] shapes = shapeCollection.ToArray();

foreach (Shape shape in shapes.OfType<Shape>())
{
    // Filter out all shapes that we don't need.
    if (shape.ShapeType.Equals(ShapeType.TextBox))
    {
        // Create a new shape that will replace the existing shape.
        Shape image = new Shape(doc, ShapeType.Image);

        // Load the image into the new shape.
        image.ImageData.SetImage(ImageDir + "Hammer.wmf");

        // Make new shape's position to match the old shape.
        image.Left = shape.Left;
        image.Top = shape.Top;
        image.Width = shape.Width;
        image.Height = shape.Height;
        image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
        image.RelativeVerticalPosition = shape.RelativeVerticalPosition;
        image.HorizontalAlignment = shape.HorizontalAlignment;
        image.VerticalAlignment = shape.VerticalAlignment;
        image.WrapType = shape.WrapType;
        image.WrapSide = shape.WrapSide;

        // Insert new shape after the old shape and remove the old shape.
        shape.ParentNode.InsertAfter(image, shape);
        shape.Remove();
    }
}

doc.Save(ArtifactsDir + "Shape.ReplaceTextboxesWithImages.doc");
Shows how to add, update and delete child nodes from within a CompositeNode.
[C#]

Document doc = new Document();

// An empty document has one paragraph by default
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);

// A paragraph is a composite node because it can contain runs, which are another type of node
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
Run paragraphText = new Run(doc, "Initial text. ");
paragraph.AppendChild(paragraphText);

// We will place these 3 children into the main text of our paragraph
Run run1 = new Run(doc, "Run 1. ");
Run run2 = new Run(doc, "Run 2. ");
Run run3 = new Run(doc, "Run 3. ");

// We initialized them but not in our paragraph yet
Assert.AreEqual("Initial text. " + (char) 12, paragraph.GetText());

// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph.InsertBefore(run2, paragraphText);

// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph.InsertAfter(run3, paragraphText);

// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph.PrependChild(run1);

Assert.AreEqual("Run 1. Run 2. Initial text. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(4, paragraph.GetChildNodes(NodeType.Any, true).Count);

// Access the child node collection and update/delete children
((Run) paragraph.GetChildNodes(NodeType.Run, true)[1]).Text = "Updated run 2. ";
paragraph.GetChildNodes(NodeType.Run, true).Remove(paragraphText);

Assert.AreEqual("Run 1. Updated run 2. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(3, paragraph.GetChildNodes(NodeType.Any, true).Count);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.InsertBefore Method

Inserts the specified node immediately before the specified reference node.

[Visual Basic]
Public Function InsertBefore( _
ByVal newChild As Node, _
ByVal refChild As Node _
) As Node
[C#]
public Node InsertBefore(
Node newChild,
Node refChild
);

Parameters

newChild
The Node to insert.
refChild
The Node that is the reference node. The newChild is placed before this node.

Return Value

The inserted node.

Remarks

If refChild is null, inserts newChild at the end of the list of child nodes.

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use ImportNode to import the node to the current document. The imported node can then be inserted into the current document.

Example

Shows how to add, update and delete child nodes from within a CompositeNode.

[C#]

Document doc = new Document();

// An empty document has one paragraph by default
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);

// A paragraph is a composite node because it can contain runs, which are another type of node
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
Run paragraphText = new Run(doc, "Initial text. ");
paragraph.AppendChild(paragraphText);

// We will place these 3 children into the main text of our paragraph
Run run1 = new Run(doc, "Run 1. ");
Run run2 = new Run(doc, "Run 2. ");
Run run3 = new Run(doc, "Run 3. ");

// We initialized them but not in our paragraph yet
Assert.AreEqual("Initial text. " + (char) 12, paragraph.GetText());

// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph.InsertBefore(run2, paragraphText);

// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph.InsertAfter(run3, paragraphText);

// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph.PrependChild(run1);

Assert.AreEqual("Run 1. Run 2. Initial text. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(4, paragraph.GetChildNodes(NodeType.Any, true).Count);

// Access the child node collection and update/delete children
((Run) paragraph.GetChildNodes(NodeType.Run, true)[1]).Text = "Updated run 2. ";
paragraph.GetChildNodes(NodeType.Run, true).Remove(paragraphText);

Assert.AreEqual("Run 1. Updated run 2. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(3, paragraph.GetChildNodes(NodeType.Any, true).Count);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.PrependChild Method

Adds the specified node to the beginning of the list of child nodes for this node.

[Visual Basic]
Public Function PrependChild( _
ByVal newChild As Node _
) As Node
[C#]
public Node PrependChild(
Node newChild
);

Parameters

newChild
The node to add.

Return Value

The node added.

Remarks

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use ImportNode to import the node to the current document. The imported node can then be inserted into the current document.

Example

Shows how to add, update and delete child nodes from within a CompositeNode.

[C#]

Document doc = new Document();

// An empty document has one paragraph by default
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);

// A paragraph is a composite node because it can contain runs, which are another type of node
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
Run paragraphText = new Run(doc, "Initial text. ");
paragraph.AppendChild(paragraphText);

// We will place these 3 children into the main text of our paragraph
Run run1 = new Run(doc, "Run 1. ");
Run run2 = new Run(doc, "Run 2. ");
Run run3 = new Run(doc, "Run 3. ");

// We initialized them but not in our paragraph yet
Assert.AreEqual("Initial text. " + (char) 12, paragraph.GetText());

// Insert run2 before initial paragraph text. This will be at the start of the paragraph
paragraph.InsertBefore(run2, paragraphText);

// Insert run3 after initial paragraph text. This will be at the end of the paragraph
paragraph.InsertAfter(run3, paragraphText);

// Insert run1 before every other child node. run2 was the start of the paragraph, now it will be run1
paragraph.PrependChild(run1);

Assert.AreEqual("Run 1. Run 2. Initial text. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(4, paragraph.GetChildNodes(NodeType.Any, true).Count);

// Access the child node collection and update/delete children
((Run) paragraph.GetChildNodes(NodeType.Run, true)[1]).Text = "Updated run 2. ";
paragraph.GetChildNodes(NodeType.Run, true).Remove(paragraphText);

Assert.AreEqual("Run 1. Updated run 2. Run 3. " + (char) 12, paragraph.GetText());
Assert.AreEqual(3, paragraph.GetChildNodes(NodeType.Any, true).Count);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.RemoveAllChildren Method

Removes all the child nodes of the current node.

[Visual Basic]
Public Sub RemoveAllChildren()
[C#]
public void RemoveAllChildren();

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.RemoveChild Method

Removes the specified child node.

[Visual Basic]
Public Function RemoveChild( _
ByVal oldChild As Node _
) As Node
[C#]
public Node RemoveChild(
Node oldChild
);

Parameters

oldChild
The node to remove.

Return Value

The removed node.

Remarks

The parent of oldChild is set to null after the node is removed.

Example

Demonstrates use of methods of Node and CompositeNode to remove a section before the last section in the document.

[C#]

// Document is a CompositeNode and LastChild returns the last child node in the Document node.
// Since the Document can contain only Section nodes, the last child is the last section.
Node lastSection = doc.LastChild;

// Each node knows its next and previous sibling nodes.
// Previous sibling of a section is a section before the specified section.
// If the node is the first child, PreviousSibling will return null.
Node sectionBeforeLast = lastSection.PreviousSibling;

if (sectionBeforeLast != null)
    doc.RemoveChild(sectionBeforeLast);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.RemoveSmartTags Method

Removes all SmartTag descendant nodes of the current node.

[Visual Basic]
Public Sub RemoveSmartTags()
[C#]
public void RemoveSmartTags();

Remarks

This method does not remove the content of the smart tags.

Example

Shows how to remove all smart tags from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.RemoveSmartTags();
Removes all smart tags from descendant nodes of the composite node.
[C#]

Document doc = new Document(MyDir + "Document.doc");

// Remove smart tags from the first paragraph in the document.
doc.FirstSection.Body.FirstParagraph.RemoveSmartTags();

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.SelectNodes Method

Selects a list of nodes matching the XPath expression.

[Visual Basic]
Public Function SelectNodes( _
ByVal xpath As String _
) As NodeList
[C#]
public NodeList SelectNodes(
string xpath
);

Parameters

xpath
The XPath expression.

Return Value

A list of nodes matching the XPath query.

Remarks

Only expressions with element names are supported at the moment. Expressions that use attribute names are not supported.

Example

Shows how to select certain nodes by using an XPath expression.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// This expression will extract all paragraph nodes which are descendants of any table node in the document.
// This will return any paragraphs which are in a table.
NodeList nodeList = doc.SelectNodes("//Table//Paragraph");

// This expression will select any paragraphs that are direct children of any body node in the document.
nodeList = doc.SelectNodes("//Body/Paragraph");

// Use SelectSingleNode to select the first result of the same expression as above.
Node node = doc.SelectSingleNode("//Body/Paragraph");
Shows how to test if a node is inside a field by using an XPath expression.
[C#]

// Let's pick a document we know has some fields in.
Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

// Let's say we want to check if the Run below is inside a field.
Run run = (Run) doc.GetChild(NodeType.Run, 5, true);

// Evaluate the XPath expression. The resulting NodeList will contain all nodes found inside a field a field (between FieldStart
// and FieldEnd exclusive). There can however be FieldStart and FieldEnd nodes in the list if there are nested fields
// in the path. Currently does not find rare fields in which the FieldCode or FieldResult spans across multiple paragraphs.
NodeList resultList =
    doc.SelectNodes("//FieldStart/following-sibling::node()[following-sibling::FieldEnd]");

// Check if the specified run is one of the nodes that are inside the field.
foreach (Node node in resultList)
{
    if (node == run)
    {
        Console.WriteLine("The node is found inside a field");
        break;
    }
}

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.SelectSingleNode Method

Selects the first Node that matches the XPath expression.

[Visual Basic]
Public Function SelectSingleNode( _
ByVal xpath As String _
) As Node
[C#]
public Node SelectSingleNode(
string xpath
);

Parameters

xpath
The XPath expression.

Return Value

The first Node that matches the XPath query or null if no matching node is found.

Remarks

Only expressions with element names are supported at the moment. Expressions that use attribute names are not supported.

Example

Shows how to select certain nodes by using an XPath expression.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// This expression will extract all paragraph nodes which are descendants of any table node in the document.
// This will return any paragraphs which are in a table.
NodeList nodeList = doc.SelectNodes("//Table//Paragraph");

// This expression will select any paragraphs that are direct children of any body node in the document.
nodeList = doc.SelectNodes("//Body/Paragraph");

// Use SelectSingleNode to select the first result of the same expression as above.
Node node = doc.SelectSingleNode("//Body/Paragraph");

See Also

CompositeNode Class | Aspose.Words Namespace


ConditionalStyle Class

Represents special formatting applied to some area of a table with assigned table style.

For a list of all members of this type, see ConditionalStyle Members.

System.Object
Aspose.Words.ConditionalStyle

[Visual Basic]
NotInheritable Public Class ConditionalStyle
[C#]
public sealed class ConditionalStyle

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ConditionalStyle Members | Aspose.Words Namespace


ConditionalStyle Members

ConditionalStyle overview

Public Instance Properties

Borders | Gets the collection of default cell borders for the conditional style.
BottomPadding | Gets or sets the amount of space (in points) to add below the contents of table cells.
Font | Gets the character formatting of the conditional style.
LeftPadding | Gets or sets the amount of space (in points) to add to the left of the contents of table cells.
ParagraphFormat | Gets the paragraph formatting of the conditional style.
RightPadding | Gets or sets the amount of space (in points) to add to the right of the contents of table cells.
Shading | Gets a Shading object that refers to the shading formatting for this conditional style.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of table cells.
Type | Gets table area to which this conditional style relates.

Public Instance Methods

ClearFormatting Clears formatting of this conditional style.

See Also

ConditionalStyle Class | Aspose.Words Namespace


ConditionalStyle Properties

The properties of the ConditionalStyle class are listed below. For a complete list of ConditionalStyle class members, see the ConditionalStyle Members topic.

Public Instance Properties

Borders | Gets the collection of default cell borders for the conditional style.
BottomPadding | Gets or sets the amount of space (in points) to add below the contents of table cells.
Font | Gets the character formatting of the conditional style.
LeftPadding | Gets or sets the amount of space (in points) to add to the left of the contents of table cells.
ParagraphFormat | Gets the paragraph formatting of the conditional style.
RightPadding | Gets or sets the amount of space (in points) to add to the right of the contents of table cells.
Shading | Gets a Shading object that refers to the shading formatting for this conditional style.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of table cells.
Type | Gets table area to which this conditional style relates.

See Also

ConditionalStyle Class | Aspose.Words Namespace


Borders Property

Aspose.Words

ConditionalStyle.Borders Property

Gets the collection of default cell borders for the conditional style.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


BottomPadding Property

Aspose.Words

ConditionalStyle.BottomPadding Property

Gets or sets the amount of space (in points) to add below the contents of table cells.

[Visual Basic]
Public Property BottomPadding As Double
[C#]
public double BottomPadding {get; set;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


Font Property

Aspose.Words

ConditionalStyle.Font Property

Gets the character formatting of the conditional style.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


LeftPadding Property

Aspose.Words

ConditionalStyle.LeftPadding Property

Gets or sets the amount of space (in points) to add to the left of the contents of table cells.

[Visual Basic]
Public Property LeftPadding As Double
[C#]
public double LeftPadding {get; set;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


ParagraphFormat Property

Aspose.Words

ConditionalStyle.ParagraphFormat Property

Gets the paragraph formatting of the conditional style.

[Visual Basic]
Public ReadOnly Property ParagraphFormat As ParagraphFormat
[C#]
public ParagraphFormat ParagraphFormat {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


RightPadding Property

Aspose.Words

ConditionalStyle.RightPadding Property

Gets or sets the amount of space (in points) to add to the right of the contents of table cells.

[Visual Basic]
Public Property RightPadding As Double
[C#]
public double RightPadding {get; set;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


Shading Property

Aspose.Words

ConditionalStyle.Shading Property

Gets a Shading object that refers to the shading formatting for this conditional style.

[Visual Basic]
Public ReadOnly Property Shading As Shading
[C#]
public Shading Shading {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


TopPadding Property

Aspose.Words

ConditionalStyle.TopPadding Property

Gets or sets the amount of space (in points) to add above the contents of table cells.

[Visual Basic]
Public Property TopPadding As Double
[C#]
public double TopPadding {get; set;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyle Class | Aspose.Words Namespace


Type Property

Aspose.Words

ConditionalStyle.Type Property

Gets table area to which this conditional style relates.

[Visual Basic]
Public ReadOnly Property Type As ConditionalStyleType
[C#]
public ConditionalStyleType Type {get;}

Example

Shows how to enumerate all table styles in a collection.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");

// Get the enumerator from the document's ConditionalStyleCollection and iterate over the styles
using (IEnumerator<ConditionalStyle> enumerator = tableStyle.ConditionalStyles.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        ConditionalStyle currentStyle = enumerator.Current;

        if (currentStyle != null)
        {
            Console.WriteLine(currentStyle.Type);
        }
    }
}

See Also

ConditionalStyle Class | Aspose.Words Namespace


ConditionalStyle Methods

The methods of the ConditionalStyle class are listed below. For a complete list of ConditionalStyle class members, see the ConditionalStyle Members topic.

Public Instance Methods

ClearFormatting Clears formatting of this conditional style.

See Also

ConditionalStyle Class | Aspose.Words Namespace


ConditionalStyle.ClearFormatting Method

Clears formatting of this conditional style.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Example

Shows how to reset all table styles.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// You can reset styles from the specific table area
tableStyle.ConditionalStyles[0].ClearFormatting();
// Or clear all table styles
tableStyle.ConditionalStyles.ClearFormatting();

See Also

ConditionalStyle Class | Aspose.Words Namespace


ConditionalStyleCollection Class

Represents a collection of ConditionalStyle objects.

For a list of all members of this type, see ConditionalStyleCollection Members.

System.Object
Aspose.Words.ConditionalStyleCollection

[Visual Basic]
NotInheritable Public Class ConditionalStyleCollection
Implements IEnumerable`1([Aspose.Words.ConditionalStyle, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public sealed class ConditionalStyleCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

It is not possible to add or remove items from this collection. It contains permanent set of items: one item for each value of the ConditionalStyleType enumeration type.

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ConditionalStyleCollection Members | Aspose.Words Namespace


ConditionalStyleCollection Members

ConditionalStyleCollection overview

Public Instance Properties

BottomLeftCell | Gets the bottom left cell style.
BottomRightCell | Gets the bottom right cell style.
Count | Gets the number of conditional styles in the collection.
EvenColumnBanding | Gets the even column banding style.
EvenRowBanding | Gets the even row banding style.
FirstColumn | Gets the first column style.
FirstRow | Gets the first row style.
Item | Overloaded. Retrieves a ConditionalStyle object.
LastColumn | Gets the last column style.
LastRow | Gets the last row style.
OddColumnBanding | Gets the odd column banding style.
OddRowBanding | Gets the odd row banding style.
TopLeftCell | Gets the top left cell style.
TopRightCell | Gets the top right cell style.

Public Instance Methods

ClearFormatting | Clears all conditional styles of the table style.
GetEnumerator | Returns an enumerator object that can be used to iterate over all conditional styles in the collection.

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


ConditionalStyleCollection Properties

The properties of the ConditionalStyleCollection class are listed below. For a complete list of ConditionalStyleCollection class members, see the ConditionalStyleCollection Members topic.

Public Instance Properties

BottomLeftCell | Gets the bottom left cell style.
BottomRightCell | Gets the bottom right cell style.
Count | Gets the number of conditional styles in the collection.
EvenColumnBanding | Gets the even column banding style.
EvenRowBanding | Gets the even row banding style.
FirstColumn | Gets the first column style.
FirstRow | Gets the first row style.
Item | Overloaded. Retrieves a ConditionalStyle object.
LastColumn | Gets the last column style.
LastRow | Gets the last row style.
OddColumnBanding | Gets the odd column banding style.
OddRowBanding | Gets the odd row banding style.
TopLeftCell | Gets the top left cell style.
TopRightCell | Gets the top right cell style.

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


BottomLeftCell Property

Aspose.Words

ConditionalStyleCollection.BottomLeftCell Property

Gets the bottom left cell style.

[Visual Basic]
Public ReadOnly Property BottomLeftCell As ConditionalStyle
[C#]
public ConditionalStyle BottomLeftCell {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


BottomRightCell Property

Aspose.Words

ConditionalStyleCollection.BottomRightCell Property

Gets the bottom right cell style.

[Visual Basic]
Public ReadOnly Property BottomRightCell As ConditionalStyle
[C#]
public ConditionalStyle BottomRightCell {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

ConditionalStyleCollection.Count Property

Gets the number of conditional styles in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


EvenColumnBanding Property

Aspose.Words

ConditionalStyleCollection.EvenColumnBanding Property

Gets the even column banding style.

[Visual Basic]
Public ReadOnly Property EvenColumnBanding As ConditionalStyle
[C#]
public ConditionalStyle EvenColumnBanding {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


EvenRowBanding Property

Aspose.Words

ConditionalStyleCollection.EvenRowBanding Property

Gets the even row banding style.

[Visual Basic]
Public ReadOnly Property EvenRowBanding As ConditionalStyle
[C#]
public ConditionalStyle EvenRowBanding {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


FirstColumn Property

Aspose.Words

ConditionalStyleCollection.FirstColumn Property

Gets the first column style.

[Visual Basic]
Public ReadOnly Property FirstColumn As ConditionalStyle
[C#]
public ConditionalStyle FirstColumn {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


FirstRow Property

Aspose.Words

ConditionalStyleCollection.FirstRow Property

Gets the first row style.

[Visual Basic]
Public ReadOnly Property FirstRow As ConditionalStyle
[C#]
public ConditionalStyle FirstRow {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

ConditionalStyleCollection.Item Property

Retrieves a ConditionalStyle object.

Overload List

Retrieves a ConditionalStyle object by conditional style type.

public ConditionalStyle this[Aspose.Words.ConditionalStyleType] {get;}

Retrieves a ConditionalStyle object by index.

public ConditionalStyle this[int] {get;}

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


Item Property (ConditionalStyleType)

Aspose.Words

ConditionalStyleCollection.Item Property (ConditionalStyleType)

Retrieves a ConditionalStyle object by conditional style type.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal conditionalStyleType As ConditionalStyleType _
) As ConditionalStyle
[C#]
public ConditionalStyle this[
Aspose.Words.ConditionalStyleType conditionalStyleType
] {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace | ConditionalStyleCollection.Item Overload List


Item Property (Int32)

Aspose.Words

ConditionalStyleCollection.Item Property (Int32)

Retrieves a ConditionalStyle object by index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As ConditionalStyle
[C#]
public ConditionalStyle this[
int index
] {get;}

Parameters

index
Zero-based index of the conditional style to retrieve.

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace | ConditionalStyleCollection.Item Overload List


LastColumn Property

Aspose.Words

ConditionalStyleCollection.LastColumn Property

Gets the last column style.

[Visual Basic]
Public ReadOnly Property LastColumn As ConditionalStyle
[C#]
public ConditionalStyle LastColumn {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


LastRow Property

Aspose.Words

ConditionalStyleCollection.LastRow Property

Gets the last row style.

[Visual Basic]
Public ReadOnly Property LastRow As ConditionalStyle
[C#]
public ConditionalStyle LastRow {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


OddColumnBanding Property

Aspose.Words

ConditionalStyleCollection.OddColumnBanding Property

Gets the odd column banding style.

[Visual Basic]
Public ReadOnly Property OddColumnBanding As ConditionalStyle
[C#]
public ConditionalStyle OddColumnBanding {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


OddRowBanding Property

Aspose.Words

ConditionalStyleCollection.OddRowBanding Property

Gets the odd row banding style.

[Visual Basic]
Public ReadOnly Property OddRowBanding As ConditionalStyle
[C#]
public ConditionalStyle OddRowBanding {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


TopLeftCell Property

Aspose.Words

ConditionalStyleCollection.TopLeftCell Property

Gets the top left cell style.

[Visual Basic]
Public ReadOnly Property TopLeftCell As ConditionalStyle
[C#]
public ConditionalStyle TopLeftCell {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


TopRightCell Property

Aspose.Words

ConditionalStyleCollection.TopRightCell Property

Gets the top right cell style.

[Visual Basic]
Public ReadOnly Property TopRightCell As ConditionalStyle
[C#]
public ConditionalStyle TopRightCell {get;}

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


ConditionalStyleCollection Methods

The methods of the ConditionalStyleCollection class are listed below. For a complete list of ConditionalStyleCollection class members, see the ConditionalStyleCollection Members topic.

Public Instance Methods

ClearFormatting | Clears all conditional styles of the table style.
GetEnumerator | Returns an enumerator object that can be used to iterate over all conditional styles in the collection.

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


ConditionalStyleCollection.ClearFormatting Method

Clears all conditional styles of the table style.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Example

Shows how to reset all table styles.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// You can reset styles from the specific table area
tableStyle.ConditionalStyles[0].ClearFormatting();
// Or clear all table styles
tableStyle.ConditionalStyles.ClearFormatting();

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


ConditionalStyleCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all conditional styles in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of ConditionalStyle) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<ConditionalStyle> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to enumerate all table styles in a collection.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");

// Get the enumerator from the document's ConditionalStyleCollection and iterate over the styles
using (IEnumerator<ConditionalStyle> enumerator = tableStyle.ConditionalStyles.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        ConditionalStyle currentStyle = enumerator.Current;

        if (currentStyle != null)
        {
            Console.WriteLine(currentStyle.Type);
        }
    }
}

See Also

ConditionalStyleCollection Class | Aspose.Words Namespace


ConditionalStyleType Enumeration

Represents possible table areas to which conditional formatting may be defined in a table style.

[Visual Basic]
Public Enum ConditionalStyleType
[C#]
public enum ConditionalStyleType

Example

Shows how to work with certain area styles of a table.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// There is a different ways how to get conditional styles:
// by conditional style type
tableStyle.ConditionalStyles[ConditionalStyleType.FirstRow].Shading.BackgroundPatternColor = Color.AliceBlue;
// by index
tableStyle.ConditionalStyles[0].Borders.Color = Color.Black;
tableStyle.ConditionalStyles[0].Borders.LineStyle = LineStyle.DotDash;
Assert.AreEqual(ConditionalStyleType.FirstRow, tableStyle.ConditionalStyles[0].Type);
// directly from ConditionalStyleCollection
tableStyle.ConditionalStyles.FirstRow.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// To see this in Word document select Total Row checkbox in Design Tab
tableStyle.ConditionalStyles.LastRow.BottomPadding = 10;
tableStyle.ConditionalStyles.LastRow.LeftPadding = 10;
tableStyle.ConditionalStyles.LastRow.RightPadding = 10;
tableStyle.ConditionalStyles.LastRow.TopPadding = 10;
// To see this in Word document select Last Column checkbox in Design Tab
tableStyle.ConditionalStyles.LastColumn.Font.Bold = true;

Console.WriteLine(tableStyle.ConditionalStyles.Count);
Console.WriteLine(tableStyle.ConditionalStyles[0].Type);

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithTableConditionalStyles.docx");

Members

Member Name | Description | Value
FirstRow | Specifies formatting of the first row of a table. | 0
FirstColumn | Specifies formatting of the first column of a table. | 1
LastRow | Specifies formatting of the last row of a table. | 2
LastColumn | Specifies formatting of the last column of a table. | 3
OddRowBanding | Specifies formatting of odd-numbered row stripe. | 4
OddColumnBanding | Specifies formatting of odd-numbered column stripe. | 5
EvenRowBanding | Specifies formatting of even-numbered row stripe. | 6
EvenColumnBanding | Specifies formatting of even-numbered column stripe. | 7
TopLeftCell | Specifies formatting of the top left cell of a table. | 8
TopRightCell | Specifies formatting of the top right cell of a table. | 9
BottomLeftCell | Specifies formatting of the bottom left cell of a table. | 10
BottomRightCell | Specifies formatting of the bottom right cell of a table. | 11

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


ContentDisposition Enumeration

Enumerates different ways of presenting the document at the client browser.

[Visual Basic]
Public Enum ContentDisposition
[C#]
public enum ContentDisposition

Remarks

Note that the actual behavior on the client browser might be affected by security configuration of the browser.

Example

Performs a simple insertion of data into merge fields and sends the document to the browser inline.

[C#]

// Open an existing document.
Document doc = new Document(MyDir + "MailMerge.ExecuteArray.doc");

// Fill the fields in the document with user data.
doc.MailMerge.Execute(new String[] { "FullName", "Company", "Address", "Address2", "City" },
    new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });

// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
Assert.That(() => doc.Save(Response, "Artifacts/MailMerge.ExecuteArray.doc", ContentDisposition.Inline, null), Throws.TypeOf<ArgumentNullException>()); //Thrown because HttpResponse is null in the test.

Members

Member Name | Description | Value
Attachment | Send the document to the browser and present an option to save the document to disk or open in the application associated with the document's extension. | 0
Inline | Send the document to the browser and presents an option to save the document to disk or open inside the browser. | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


ControlChar Class

Control characters often encountered in documents.

For a list of all members of this type, see ControlChar Members.

System.Object
Aspose.Words.ControlChar

[Visual Basic]
MustInherit NotInheritable Public Class ControlChar
[C#]
public abstract sealed class ControlChar

Remarks

Provides both char and string versions of the same constants. For example: string ControlChar.LineBreak and char ControlChar.LineBreakChar have the same value.

Example

Shows how to use control characters.

[C#]

// Replace "\r" control character with "\r\n"
text = text.Replace(ControlChar.Cr, ControlChar.CrLf);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ControlChar Members | Aspose.Words Namespace


ControlChar Members

ControlChar overview

Public Static (Shared) Fields

Cell | End of a table cell or end of a table row character: "\x0007" or "\a".
CellChar | End of a table cell or end of a table row character: (char)7 or "\a".
ColumnBreak | End of column character: "\x000e".
ColumnBreakChar | End of column character: (char)14.
Cr | Carriage return character: "\x000d" or "\r". Same as ParagraphBreak.
CrLf | Carriage return followed by line feed character: "\x000d\x000a" or "\r\n". Not used as such in Microsoft Word documents, but commonly used in text files for paragraph breaks.
DefaultTextInputChar | This is the "o" character used as a default value in text input form fields.
FieldEndChar | End of MS Word field character: (char)21.
FieldSeparatorChar | Field separator character separates field code from field value. Optional in some fields. Value: (char)20.
FieldStartChar | Start of MS Word field character: (char)19.
Lf | Line feed character: "\x000a" or "\n". Same as LineFeed.
LineBreak | Line break character: "\x000b" or "\v".
LineBreakChar | Line break character: (char)11 or "\v".
LineFeed | Line feed character: "\x000a" or "\n". Same as Lf.
LineFeedChar | Line feed character: (char)10 or "\n".
NonBreakingHyphenChar | Nonbreaking Hyphen in Microsoft Word is (char)30.
NonBreakingSpace | Non-breaking space character: "\x00a0".
NonBreakingSpaceChar | Non-breaking space character: (char)160.
OptionalHyphenChar | Optional Hyphen in Microsoft Word is (char)31.
PageBreak | Page break character: "\x000c" or "\f". Note it has the same value as SectionBreak.
PageBreakChar | Page break character: (char)12 or "\f".
ParagraphBreak | End of paragraph character: "\x000d" or "\r". Same as Cr
ParagraphBreakChar | End of paragraph character: (char)13 or "\r".
SectionBreak | End of section character: "\x000c" or "\f". Note it has the same value as PageBreak.
SectionBreakChar | End of section character: (char)12 or "\f".
SpaceChar | Space character: (char)32.
Tab | Tab character: "\x0009" or "\t".
TabChar | Tab character: (char)9 or "\t".

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar Fields

The fields of the ControlChar class are listed below. For a complete list of ControlChar class members, see the ControlChar Members topic.

Public Static (Shared) Fields

Cell | End of a table cell or end of a table row character: "\x0007" or "\a".
CellChar | End of a table cell or end of a table row character: (char)7 or "\a".
ColumnBreak | End of column character: "\x000e".
ColumnBreakChar | End of column character: (char)14.
Cr | Carriage return character: "\x000d" or "\r". Same as ParagraphBreak.
CrLf | Carriage return followed by line feed character: "\x000d\x000a" or "\r\n". Not used as such in Microsoft Word documents, but commonly used in text files for paragraph breaks.
DefaultTextInputChar | This is the "o" character used as a default value in text input form fields.
FieldEndChar | End of MS Word field character: (char)21.
FieldSeparatorChar | Field separator character separates field code from field value. Optional in some fields. Value: (char)20.
FieldStartChar | Start of MS Word field character: (char)19.
Lf | Line feed character: "\x000a" or "\n". Same as LineFeed.
LineBreak | Line break character: "\x000b" or "\v".
LineBreakChar | Line break character: (char)11 or "\v".
LineFeed | Line feed character: "\x000a" or "\n". Same as Lf.
LineFeedChar | Line feed character: (char)10 or "\n".
NonBreakingHyphenChar | Nonbreaking Hyphen in Microsoft Word is (char)30.
NonBreakingSpace | Non-breaking space character: "\x00a0".
NonBreakingSpaceChar | Non-breaking space character: (char)160.
OptionalHyphenChar | Optional Hyphen in Microsoft Word is (char)31.
PageBreak | Page break character: "\x000c" or "\f". Note it has the same value as SectionBreak.
PageBreakChar | Page break character: (char)12 or "\f".
ParagraphBreak | End of paragraph character: "\x000d" or "\r". Same as Cr
ParagraphBreakChar | End of paragraph character: (char)13 or "\r".
SectionBreak | End of section character: "\x000c" or "\f". Note it has the same value as PageBreak.
SectionBreakChar | End of section character: (char)12 or "\f".
SpaceChar | Space character: (char)32.
Tab | Tab character: "\x0009" or "\t".
TabChar | Tab character: (char)9 or "\t".

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.Cell Field

End of a table cell or end of a table row character: "\x0007" or "\a".

[Visual Basic]
Public Shared ReadOnly Cell As String
[C#]
public static readonly string Cell;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.CellChar Field

End of a table cell or end of a table row character: (char)7 or "\a".

[Visual Basic]
Public Const CellChar As Char = 
[C#]
public const char CellChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.ColumnBreak Field

End of column character: "\x000e".

[Visual Basic]
Public Shared ReadOnly ColumnBreak As String
[C#]
public static readonly string ColumnBreak;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.ColumnBreakChar Field

End of column character: (char)14.

[Visual Basic]
Public Const ColumnBreakChar As Char = 
[C#]
public const char ColumnBreakChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.Cr Field

Carriage return character: "\x000d" or "\r". Same as ParagraphBreak.

[Visual Basic]
Public Shared ReadOnly Cr As String
[C#]
public static readonly string Cr;

Example

Shows how to use control characters.

[C#]

// Replace "\r" control character with "\r\n"
text = text.Replace(ControlChar.Cr, ControlChar.CrLf);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.CrLf Field

Carriage return followed by line feed character: "\x000d\x000a" or "\r\n". Not used as such in Microsoft Word documents, but commonly used in text files for paragraph breaks.

[Visual Basic]
Public Shared ReadOnly CrLf As String
[C#]
public static readonly string CrLf;

Example

Shows how to use control characters.

[C#]

// Replace "\r" control character with "\r\n"
text = text.Replace(ControlChar.Cr, ControlChar.CrLf);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.DefaultTextInputChar Field

This is the "o" character used as a default value in text input form fields.

[Visual Basic]
Public Const DefaultTextInputChar As Char =
[C#]
public const char DefaultTextInputChar =  ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.FieldEndChar Field

End of MS Word field character: (char)21.

[Visual Basic]
Public Const FieldEndChar As Char = 
[C#]
public const char FieldEndChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.FieldSeparatorChar Field

Field separator character separates field code from field value. Optional in some fields. Value: (char)20.

[Visual Basic]
Public Const FieldSeparatorChar As Char = 
[C#]
public const char FieldSeparatorChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.FieldStartChar Field

Start of MS Word field character: (char)19.

[Visual Basic]
Public Const FieldStartChar As Char = 
[C#]
public const char FieldStartChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.Lf Field

Line feed character: "\x000a" or "\n". Same as LineFeed.

[Visual Basic]
Public Shared ReadOnly Lf As String
[C#]
public static readonly string Lf;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.LineBreak Field

Line break character: "\x000b" or "\v".

[Visual Basic]
Public Shared ReadOnly LineBreak As String
[C#]
public static readonly string LineBreak;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.LineBreakChar Field

Line break character: (char)11 or "\v".

[Visual Basic]
Public Const LineBreakChar As Char =
[C#]
public const char LineBreakChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.LineFeed Field

Line feed character: "\x000a" or "\n". Same as Lf.

[Visual Basic]
Public Shared ReadOnly LineFeed As String
[C#]
public static readonly string LineFeed;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.LineFeedChar Field

Line feed character: (char)10 or "\n".

[Visual Basic]
Public Const LineFeedChar As Char =
[C#]
public const char LineFeedChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.NonBreakingHyphenChar Field

Nonbreaking Hyphen in Microsoft Word is (char)30.

[Visual Basic]
Public Const NonBreakingHyphenChar As Char =
[C#]
public const char NonBreakingHyphenChar = ;

Remarks

Nonbreaking Hyphen in Microsoft Word does not correspond to the Unicode character U+2011 non-breaking hyphen but instead represents internal information that tells Microsoft Word to display a hyphen and not to break a line.

Useful info: http://www.cs.tut.fi/~jkorpela/dashes.html#linebreaks.

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.NonBreakingSpace Field

Non-breaking space character: "\x00a0".

[Visual Basic]
Public Shared ReadOnly NonBreakingSpace As String
[C#]
public static readonly string NonBreakingSpace;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.NonBreakingSpaceChar Field

Non-breaking space character: (char)160.

[Visual Basic]
Public Const NonBreakingSpaceChar As Char =
[C#]
public const char NonBreakingSpaceChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.OptionalHyphenChar Field

Optional Hyphen in Microsoft Word is (char)31.

[Visual Basic]
Public Const OptionalHyphenChar As Char =
[C#]
public const char OptionalHyphenChar = ;

Remarks

Optional Hyphen in Microsoft Word does not correspond to the Unicode character U+00AD soft hyphen. Instead, it inserts internal information that tells Word about a possible hyphenation point.

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.PageBreak Field

Page break character: "\x000c" or "\f". Note it has the same value as SectionBreak.

[Visual Basic]
Public Shared ReadOnly PageBreak As String
[C#]
public static readonly string PageBreak;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.PageBreakChar Field

Page break character: (char)12 or "\f".

[Visual Basic]
Public Const PageBreakChar As Char =
[C#]
public const char PageBreakChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.ParagraphBreak Field

End of paragraph character: "\x000d" or "\r". Same as Cr

[Visual Basic]
Public Shared ReadOnly ParagraphBreak As String
[C#]
public static readonly string ParagraphBreak;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.ParagraphBreakChar Field

End of paragraph character: (char)13 or "\r".

[Visual Basic]
Public Const ParagraphBreakChar As Char =
[C#]
public const char ParagraphBreakChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.SectionBreak Field

End of section character: "\x000c" or "\f". Note it has the same value as PageBreak.

[Visual Basic]
Public Shared ReadOnly SectionBreak As String
[C#]
public static readonly string SectionBreak;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.SectionBreakChar Field

End of section character: (char)12 or "\f".

[Visual Basic]
Public Const SectionBreakChar As Char =
[C#]
public const char SectionBreakChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.SpaceChar Field

Space character: (char)32.

[Visual Basic]
Public Const SpaceChar As Char =
[C#]
public const char SpaceChar = ;

Example

Shows how to use various control characters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a regular space
builder.Write("Before space." + ControlChar.SpaceChar + "After space.");

// Add a NBSP, or non-breaking space
// Unlike the regular space, this space can't have an automatic line break at its position
builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space.");

// Add a tab character
builder.Write("Before tab." + ControlChar.Tab + "After tab.");

// Add a line break
builder.Write("Before line break." + ControlChar.LineBreak + "After line break.");

// This adds a new line and starts a new paragraph
// Same value as ControlChar.Lf
Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);
builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed.");
Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// The line feed character has two versions
Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf);

// Add a paragraph break, also adding a new paragraph
builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break.");
Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count);

// Add a section break. Note that this does not make a new section or paragraph
Assert.AreEqual(1, doc.Sections.Count);
builder.Write("Before section break." + ControlChar.SectionBreak + "After section break.");
Assert.AreEqual(1, doc.Sections.Count);

// A page break is the same value as a section break
builder.Write("Before page break." + ControlChar.PageBreak + "After page break.");

// We can add a new section like this
doc.AppendChild(new Section(doc));
builder.MoveToSection(1);

// If you have a section with more than one column, you can use a column break to make following text start on a new column
builder.CurrentSection.PageSetup.TextColumns.SetCount(2);
builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2.");

// Save document to see the characters we added
doc.Save(ArtifactsDir + "ControlChar.Misc.docx");

// There are char and string counterparts for most characters
Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar);
Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar);
Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar);
Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar);

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.Tab Field

Tab character: "\x0009" or "\t".

[Visual Basic]
Public Shared ReadOnly Tab As String
[C#]
public static readonly string Tab;

Example

Changes default tab positions for the document and inserts text with some tab characters.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Set default tab stop to 72 points (1 inch).
builder.Document.DefaultTabStop = 72;

builder.Writeln("Hello" + ControlChar.Tab + "World!");
builder.Writeln("Hello" + ControlChar.TabChar + "World!");

See Also

ControlChar Class | Aspose.Words Namespace


ControlChar.TabChar Field

Tab character: (char)9 or "\t".

[Visual Basic]
Public Const TabChar As Char =
[C#]
public const char TabChar = ;

Example

Changes default tab positions for the document and inserts text with some tab characters.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Set default tab stop to 72 points (1 inch).
builder.Document.DefaultTabStop = 72;

builder.Writeln("Hello" + ControlChar.Tab + "World!");
builder.Writeln("Hello" + ControlChar.TabChar + "World!");

See Also

ControlChar Class | Aspose.Words Namespace


ConvertUtil Class

Provides helper functions to convert between various measurement units.

For a list of all members of this type, see ConvertUtil Members.

System.Object
Aspose.Words.ConvertUtil

[Visual Basic]
MustInherit NotInheritable Public Class ConvertUtil
[C#]
public abstract sealed class ConvertUtil

Example

Shows how to specify page properties in inches.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.InchToPoint(1.0);
pageSetup.BottomMargin = ConvertUtil.InchToPoint(1.0);
pageSetup.LeftMargin = ConvertUtil.InchToPoint(1.5);
pageSetup.RightMargin = ConvertUtil.InchToPoint(1.5);
pageSetup.HeaderDistance = ConvertUtil.InchToPoint(0.2);
pageSetup.FooterDistance = ConvertUtil.InchToPoint(0.2);
Specifies paper size, orientation, margins and other settings for a section.
[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ConvertUtil Members | Aspose.Words Namespace


ConvertUtil Members

ConvertUtil overview

Public Static (Shared) Methods

InchToPoint | Converts inches to points.
MillimeterToPoint | Converts millimeters to points.
PixelToNewDpi | Converts pixels from one resolution to another.
PixelToPoint | Overloaded. Converts pixels to points.
PointToInch | Converts points to inches.
PointToPixel | Overloaded. Converts points to pixels.

See Also

ConvertUtil Class | Aspose.Words Namespace


ConvertUtil Methods

The methods of the ConvertUtil class are listed below. For a complete list of ConvertUtil class members, see the ConvertUtil Members topic.

Public Static (Shared) Methods

InchToPoint | Converts inches to points.
MillimeterToPoint | Converts millimeters to points.
PixelToNewDpi | Converts pixels from one resolution to another.
PixelToPoint | Overloaded. Converts pixels to points.
PointToInch | Converts points to inches.
PointToPixel | Overloaded. Converts points to pixels.

See Also

ConvertUtil Class | Aspose.Words Namespace


ConvertUtil.InchToPoint Method

Converts inches to points.

[Visual Basic]
Public Shared Function InchToPoint( _
ByVal inches As Double _
) As Double
[C#]
public static double InchToPoint(
double inches
);

Parameters

inches
The value to convert.

Remarks

1 inch equals 72 points.

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

ConvertUtil Class | Aspose.Words Namespace


ConvertUtil.MillimeterToPoint Method

Converts millimeters to points.

[Visual Basic]
Public Shared Function MillimeterToPoint( _
ByVal millimeters As Double _
) As Double
[C#]
public static double MillimeterToPoint(
double millimeters
);

Parameters

millimeters
The value to convert.

Remarks

1 inch equals 25.4 millimeters. 1 inch equals 72 points.

Example

Shows how to specify page properties in millimeters.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.MillimeterToPoint(25.0);
pageSetup.BottomMargin = ConvertUtil.MillimeterToPoint(25.0);
pageSetup.LeftMargin = ConvertUtil.MillimeterToPoint(37.5);
pageSetup.RightMargin = ConvertUtil.MillimeterToPoint(37.5);
pageSetup.HeaderDistance = ConvertUtil.MillimeterToPoint(5.0);
pageSetup.FooterDistance = ConvertUtil.MillimeterToPoint(5.0);

builder.Writeln("Hello world.");
builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

ConvertUtil Class | Aspose.Words Namespace


ConvertUtil.PixelToNewDpi Method

Converts pixels from one resolution to another.

[Visual Basic]
Public Shared Function PixelToNewDpi( _
ByVal pixels As Double, _
ByVal oldDpi As Double, _
ByVal newDpi As Double _
) As Integer
[C#]
public static int PixelToNewDpi(
double pixels,
double oldDpi,
double newDpi
);

Parameters

pixels
The value to convert.
oldDpi
The current dpi (dots per inch) resolution.
newDpi
The new dpi (dots per inch) resolution.

Example

Shows how to check how an amount of pixels changes when the dpi is changed.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = 72;
double oldDpi = 92.0;
double newDpi = 192.0;

Console.WriteLine("{0} pixels at {1} dpi becomes {2} pixels at {3} dpi.", pageSetup.TopMargin, oldDpi,
    ConvertUtil.PixelToNewDpi(pageSetup.TopMargin, oldDpi, newDpi), newDpi);

See Also

ConvertUtil Class | Aspose.Words Namespace


PixelToPoint Method

Aspose.Words

ConvertUtil.PixelToPoint Method

Converts pixels to points.

Overload List

Converts pixels to points at 96 dpi.

public static double PixelToPoint(double);

Converts pixels to points at the specified pixel resolution.

public static double PixelToPoint(double,double);

See Also

ConvertUtil Class | Aspose.Words Namespace


ConvertUtil.PixelToPoint Method (Double)

Converts pixels to points at 96 dpi.

[Visual Basic]
Overloads Public Shared Function PixelToPoint( _
ByVal pixels As Double _
) As Double
[C#]
public static double PixelToPoint(
double pixels
);

Parameters

pixels
The value to convert.

Remarks

1 inch equals 72 points.

Example

Shows how to specify page properties in pixels with default and custom resolution.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetupNoDpi = builder.PageSetup;
pageSetupNoDpi.TopMargin = ConvertUtil.PixelToPoint(100.0);
pageSetupNoDpi.BottomMargin = ConvertUtil.PixelToPoint(100.0);
pageSetupNoDpi.LeftMargin = ConvertUtil.PixelToPoint(150.0);
pageSetupNoDpi.RightMargin = ConvertUtil.PixelToPoint(150.0);
pageSetupNoDpi.HeaderDistance = ConvertUtil.PixelToPoint(20.0);
pageSetupNoDpi.FooterDistance = ConvertUtil.PixelToPoint(20.0);

builder.Writeln("Hello world.");
builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.DefaultResolution.doc");

double myDpi = 150.0;

PageSetup pageSetupWithDpi = builder.PageSetup;
pageSetupWithDpi.TopMargin = ConvertUtil.PixelToPoint(100.0, myDpi);
pageSetupWithDpi.BottomMargin = ConvertUtil.PixelToPoint(100.0, myDpi);
pageSetupWithDpi.LeftMargin = ConvertUtil.PixelToPoint(150.0, myDpi);
pageSetupWithDpi.RightMargin = ConvertUtil.PixelToPoint(150.0, myDpi);
pageSetupWithDpi.HeaderDistance = ConvertUtil.PixelToPoint(20.0, myDpi);
pageSetupWithDpi.FooterDistance = ConvertUtil.PixelToPoint(20.0, myDpi);

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.CustomResolution.doc");

See Also

ConvertUtil Class | Aspose.Words Namespace | ConvertUtil.PixelToPoint Overload List


ConvertUtil.PixelToPoint Method (Double, Double)

Converts pixels to points at the specified pixel resolution.

[Visual Basic]
Overloads Public Shared Function PixelToPoint( _
ByVal pixels As Double, _
ByVal resolution As Double _
) As Double
[C#]
public static double PixelToPoint(
double pixels,
double resolution
);

Parameters

pixels
The value to convert.
resolution
The dpi (dots per inch) resolution.

Remarks

1 inch equals 72 points.

Example

Shows how to specify page properties in pixels with default and custom resolution.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetupNoDpi = builder.PageSetup;
pageSetupNoDpi.TopMargin = ConvertUtil.PixelToPoint(100.0);
pageSetupNoDpi.BottomMargin = ConvertUtil.PixelToPoint(100.0);
pageSetupNoDpi.LeftMargin = ConvertUtil.PixelToPoint(150.0);
pageSetupNoDpi.RightMargin = ConvertUtil.PixelToPoint(150.0);
pageSetupNoDpi.HeaderDistance = ConvertUtil.PixelToPoint(20.0);
pageSetupNoDpi.FooterDistance = ConvertUtil.PixelToPoint(20.0);

builder.Writeln("Hello world.");
builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.DefaultResolution.doc");

double myDpi = 150.0;

PageSetup pageSetupWithDpi = builder.PageSetup;
pageSetupWithDpi.TopMargin = ConvertUtil.PixelToPoint(100.0, myDpi);
pageSetupWithDpi.BottomMargin = ConvertUtil.PixelToPoint(100.0, myDpi);
pageSetupWithDpi.LeftMargin = ConvertUtil.PixelToPoint(150.0, myDpi);
pageSetupWithDpi.RightMargin = ConvertUtil.PixelToPoint(150.0, myDpi);
pageSetupWithDpi.HeaderDistance = ConvertUtil.PixelToPoint(20.0, myDpi);
pageSetupWithDpi.FooterDistance = ConvertUtil.PixelToPoint(20.0, myDpi);

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.CustomResolution.doc");

See Also

ConvertUtil Class | Aspose.Words Namespace | ConvertUtil.PixelToPoint Overload List


ConvertUtil.PointToInch Method

Converts points to inches.

[Visual Basic]
Public Shared Function PointToInch( _
ByVal points As Double _
) As Double
[C#]
public static double PointToInch(
double points
);

Parameters

points
The value to convert.

Remarks

1 inch equals 72 points.

Example

Shows how to convert points to inches.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.InchToPoint(2.0);

Console.WriteLine("The size of my top margin is {0} points, or {1} inches.", pageSetup.TopMargin,
    ConvertUtil.PointToInch(pageSetup.TopMargin));

See Also

ConvertUtil Class | Aspose.Words Namespace


PointToPixel Method

Aspose.Words

ConvertUtil.PointToPixel Method

Converts points to pixels.

Overload List

Converts points to pixels at 96 dpi.

public static double PointToPixel(double);

Converts points to pixels at the specified pixel resolution.

public static double PointToPixel(double,double);

See Also

ConvertUtil Class | Aspose.Words Namespace


ConvertUtil.PointToPixel Method (Double)

Converts points to pixels at 96 dpi.

[Visual Basic]
Overloads Public Shared Function PointToPixel( _
ByVal points As Double _
) As Double
[C#]
public static double PointToPixel(
double points
);

Parameters

points
The value to convert.

Remarks

1 inch equals 72 points.

Example

Shows how to use convert points to pixels with default and custom resolution.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.PixelToPoint(2.0);

double myDpi = 192.0;

Console.WriteLine("The size of my top margin is {0} points, or {1} pixels with default resolution.",
    pageSetup.TopMargin, ConvertUtil.PointToPixel(pageSetup.TopMargin));

Console.WriteLine("The size of my top margin is {0} points, or {1} pixels with custom resolution.",
    pageSetup.TopMargin, ConvertUtil.PointToPixel(pageSetup.TopMargin, myDpi));

See Also

ConvertUtil Class | Aspose.Words Namespace | ConvertUtil.PointToPixel Overload List


ConvertUtil.PointToPixel Method (Double, Double)

Converts points to pixels at the specified pixel resolution.

[Visual Basic]
Overloads Public Shared Function PointToPixel( _
ByVal points As Double, _
ByVal resolution As Double _
) As Double
[C#]
public static double PointToPixel(
double points,
double resolution
);

Parameters

points
The value to convert.
resolution
The dpi (dots per inch) resolution.

Remarks

1 inch equals 72 points.

Example

Shows how to use convert points to pixels with default and custom resolution.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.PixelToPoint(2.0);

double myDpi = 192.0;

Console.WriteLine("The size of my top margin is {0} points, or {1} pixels with default resolution.",
    pageSetup.TopMargin, ConvertUtil.PointToPixel(pageSetup.TopMargin));

Console.WriteLine("The size of my top margin is {0} points, or {1} pixels with custom resolution.",
    pageSetup.TopMargin, ConvertUtil.PointToPixel(pageSetup.TopMargin, myDpi));

See Also

ConvertUtil Class | Aspose.Words Namespace | ConvertUtil.PointToPixel Overload List


DigitalSignature Class

Represents a digital signature on a document and the result of its verification.

For a list of all members of this type, see DigitalSignature Members.

System.Object
Aspose.Words.DigitalSignature

[Visual Basic]
Public Class DigitalSignature
[C#]
public class DigitalSignature

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DigitalSignature Members | Aspose.Words Namespace


DigitalSignature Members

DigitalSignature overview

Public Instance Properties

Certificate | Obsolete. Returns the certificate object that was used to sign the document.
CertificateHolder | Returns the certificate holder object that contains the certificate was used to sign the document.
Comments | Gets the signing purpose comment.
IssuerName | Returns the subject distinguished name of the certificate isuuer.
IsValid | Returns true if this digital signature is valid and the document has not been tampered with.
SignatureType | Gets the type of the digital signature.
SignTime | Gets the time the document was signed.
SubjectName | Returns the subject distinguished name of the certificate that was used to sign the document.

Public Instance Methods

ToString

See Also

DigitalSignature Class | Aspose.Words Namespace


DigitalSignature Properties

The properties of the DigitalSignature class are listed below. For a complete list of DigitalSignature class members, see the DigitalSignature Members topic.

Public Instance Properties

Certificate | Obsolete. Returns the certificate object that was used to sign the document.
CertificateHolder | Returns the certificate holder object that contains the certificate was used to sign the document.
Comments | Gets the signing purpose comment.
IssuerName | Returns the subject distinguished name of the certificate isuuer.
IsValid | Returns true if this digital signature is valid and the document has not been tampered with.
SignatureType | Gets the type of the digital signature.
SignTime | Gets the time the document was signed.
SubjectName | Returns the subject distinguished name of the certificate that was used to sign the document.

See Also

DigitalSignature Class | Aspose.Words Namespace


Certificate Property

Aspose.Words

DigitalSignature.Certificate Property

NOTE: This property is now obsolete.

This method is obsolete. Please use CertificateHolder.Certificate instead.

Returns the certificate object that was used to sign the document.

[Visual Basic]
Public ReadOnly Property Certificate As X509Certificate2
[C#]
public X509Certificate2 Certificate {get;}

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

DigitalSignature Class | Aspose.Words Namespace


CertificateHolder Property

Aspose.Words

DigitalSignature.CertificateHolder Property

Returns the certificate holder object that contains the certificate was used to sign the document.

[Visual Basic]
Public ReadOnly Property CertificateHolder As CertificateHolder
[C#]
public CertificateHolder CertificateHolder {get;}

Example

Shows how to sign documents with X.509 certificates.

[C#]

// Open an unsigned document
Document unSignedDoc = new Document(MyDir + "Document.docx");

// Verify that it isn't signed
Assert.False(FileFormatUtil.DetectFileFormat(MyDir + "Document.docx").HasDigitalSignature);
Assert.AreEqual(0, unSignedDoc.DigitalSignatures.Count);

// Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

// There are 2 ways of saving a signed copy of a document to the local file system
// 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.Signed.1.docx",
    certificateHolder, new SignOptions() { SignTime = DateTime.Now } );

// 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
using (FileStream inDoc = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    using (FileStream outDoc = new FileStream(ArtifactsDir + "Document.Signed.2.docx", FileMode.Create))
    {
        DigitalSignatureUtil.Sign(inDoc, outDoc, certificateHolder);
    }
}

// Verify that our documents are signed
Document signedDoc = new Document(ArtifactsDir + "Document.Signed.1.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.1.docx").HasDigitalSignature);
Assert.AreEqual(1,signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

signedDoc = new Document(ArtifactsDir + "Document.Signed.2.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.2.docx").HasDigitalSignature);
Assert.AreEqual(1, signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

// These digital signatures will have some of the properties from the X.509 certificate from the .pfx file we used
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].IssuerName);
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].SubjectName);

See Also

DigitalSignature Class | Aspose.Words Namespace


Comments Property

Aspose.Words

DigitalSignature.Comments Property

Gets the signing purpose comment.

[Visual Basic]
Public ReadOnly Property Comments As String
[C#]
public string Comments {get;}

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

DigitalSignature Class | Aspose.Words Namespace


IssuerName Property

Aspose.Words

DigitalSignature.IssuerName Property

Returns the subject distinguished name of the certificate isuuer.

[Visual Basic]
Public ReadOnly Property IssuerName As String
[C#]
public string IssuerName {get;}

Example

Shows how to sign documents with X.509 certificates.

[C#]

// Open an unsigned document
Document unSignedDoc = new Document(MyDir + "Document.docx");

// Verify that it isn't signed
Assert.False(FileFormatUtil.DetectFileFormat(MyDir + "Document.docx").HasDigitalSignature);
Assert.AreEqual(0, unSignedDoc.DigitalSignatures.Count);

// Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

// There are 2 ways of saving a signed copy of a document to the local file system
// 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.Signed.1.docx",
    certificateHolder, new SignOptions() { SignTime = DateTime.Now } );

// 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
using (FileStream inDoc = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    using (FileStream outDoc = new FileStream(ArtifactsDir + "Document.Signed.2.docx", FileMode.Create))
    {
        DigitalSignatureUtil.Sign(inDoc, outDoc, certificateHolder);
    }
}

// Verify that our documents are signed
Document signedDoc = new Document(ArtifactsDir + "Document.Signed.1.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.1.docx").HasDigitalSignature);
Assert.AreEqual(1,signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

signedDoc = new Document(ArtifactsDir + "Document.Signed.2.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.2.docx").HasDigitalSignature);
Assert.AreEqual(1, signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

// These digital signatures will have some of the properties from the X.509 certificate from the .pfx file we used
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].IssuerName);
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].SubjectName);

See Also

DigitalSignature Class | Aspose.Words Namespace


IsValid Property

Aspose.Words

DigitalSignature.IsValid Property

Returns true if this digital signature is valid and the document has not been tampered with.

[Visual Basic]
Public ReadOnly Property IsValid As Boolean
[C#]
public bool IsValid {get;}

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

DigitalSignature Class | Aspose.Words Namespace


SignatureType Property

Aspose.Words

DigitalSignature.SignatureType Property

Gets the type of the digital signature.

[Visual Basic]
Public ReadOnly Property SignatureType As DigitalSignatureType
[C#]
public DigitalSignatureType SignatureType {get;}

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

DigitalSignature Class | Aspose.Words Namespace


SignTime Property

Aspose.Words

DigitalSignature.SignTime Property

Gets the time the document was signed.

[Visual Basic]
Public ReadOnly Property SignTime As Date
[C#]
public DateTime SignTime {get;}

Example

Shows how to validate each signature in a document and display basic information about the signature.

[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

DigitalSignature Class | Aspose.Words Namespace


SubjectName Property

Aspose.Words

DigitalSignature.SubjectName Property

Returns the subject distinguished name of the certificate that was used to sign the document.

[Visual Basic]
Public ReadOnly Property SubjectName As String
[C#]
public string SubjectName {get;}

Example

Shows how to sign documents with X.509 certificates.

[C#]

// Open an unsigned document
Document unSignedDoc = new Document(MyDir + "Document.docx");

// Verify that it isn't signed
Assert.False(FileFormatUtil.DetectFileFormat(MyDir + "Document.docx").HasDigitalSignature);
Assert.AreEqual(0, unSignedDoc.DigitalSignatures.Count);

// Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

// There are 2 ways of saving a signed copy of a document to the local file system
// 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.Signed.1.docx",
    certificateHolder, new SignOptions() { SignTime = DateTime.Now } );

// 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
using (FileStream inDoc = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    using (FileStream outDoc = new FileStream(ArtifactsDir + "Document.Signed.2.docx", FileMode.Create))
    {
        DigitalSignatureUtil.Sign(inDoc, outDoc, certificateHolder);
    }
}

// Verify that our documents are signed
Document signedDoc = new Document(ArtifactsDir + "Document.Signed.1.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.1.docx").HasDigitalSignature);
Assert.AreEqual(1,signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

signedDoc = new Document(ArtifactsDir + "Document.Signed.2.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.2.docx").HasDigitalSignature);
Assert.AreEqual(1, signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

// These digital signatures will have some of the properties from the X.509 certificate from the .pfx file we used
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].IssuerName);
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].SubjectName);

See Also

DigitalSignature Class | Aspose.Words Namespace


DigitalSignature Methods

The methods of the DigitalSignature class are listed below. For a complete list of DigitalSignature class members, see the DigitalSignature Members topic.

Public Instance Methods

ToString

See Also

DigitalSignature Class | Aspose.Words Namespace


DigitalSignature.ToString Method

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();

See Also

DigitalSignature Class | Aspose.Words Namespace


DigitalSignatureCollection Class

Provides a read-only collection of digital signatures attached to a document.

For a list of all members of this type, see DigitalSignatureCollection Members.

System.Object
Aspose.Words.DigitalSignatureCollection

[Visual Basic]
Public Class DigitalSignatureCollection
Implements IEnumerable`1([Aspose.Words.DigitalSignature, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class DigitalSignatureCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

DigitalSignatures

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
DigitalSignatureCollection digitalSignatureCollection = doc.DigitalSignatures;

if (digitalSignatureCollection.IsValid)
{
    Console.WriteLine("Signatures belonging to this document are valid");
    Console.WriteLine(digitalSignatureCollection.Count);
    Console.WriteLine(digitalSignatureCollection[0].SignatureType);
}
else
{
    Console.WriteLine("Signatures belonging to this document are NOT valid");
}
Shows how to validate each signature in a document and display basic information about the signature.
[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DigitalSignatureCollection Members | Aspose.Words Namespace


DigitalSignatureCollection Members

DigitalSignatureCollection overview

Public Instance Constructors

DigitalSignatureCollection Constructor Initializes a new instance of the DigitalSignatureCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
IsValid | Returns true if all digital signatures in this collection are valid and the document has not been tampered with Also returns true if there are no digital signatures. Returns false if at least one digital signature is invalid.
Item | Gets a document signature at the specified index.

Public Instance Methods

GetEnumerator Returns a dictionary enumerator object that can be used to iterate over all items in the collection.

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


DigitalSignatureCollection Constructor

Initializes a new instance of the DigitalSignatureCollection class.

[Visual Basic]
Public Sub New()
[C#]
public DigitalSignatureCollection();

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


DigitalSignatureCollection Properties

The properties of the DigitalSignatureCollection class are listed below. For a complete list of DigitalSignatureCollection class members, see the DigitalSignatureCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
IsValid | Returns true if all digital signatures in this collection are valid and the document has not been tampered with Also returns true if there are no digital signatures. Returns false if at least one digital signature is invalid.
Item | Gets a document signature at the specified index.

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

DigitalSignatureCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
DigitalSignatureCollection digitalSignatureCollection = doc.DigitalSignatures;

if (digitalSignatureCollection.IsValid)
{
    Console.WriteLine("Signatures belonging to this document are valid");
    Console.WriteLine(digitalSignatureCollection.Count);
    Console.WriteLine(digitalSignatureCollection[0].SignatureType);
}
else
{
    Console.WriteLine("Signatures belonging to this document are NOT valid");
}

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


IsValid Property

Aspose.Words

DigitalSignatureCollection.IsValid Property

Returns true if all digital signatures in this collection are valid and the document has not been tampered with Also returns true if there are no digital signatures. Returns false if at least one digital signature is invalid.

[Visual Basic]
Public ReadOnly Property IsValid As Boolean
[C#]
public bool IsValid {get;}

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
DigitalSignatureCollection digitalSignatureCollection = doc.DigitalSignatures;

if (digitalSignatureCollection.IsValid)
{
    Console.WriteLine("Signatures belonging to this document are valid");
    Console.WriteLine(digitalSignatureCollection.Count);
    Console.WriteLine(digitalSignatureCollection[0].SignatureType);
}
else
{
    Console.WriteLine("Signatures belonging to this document are NOT valid");
}

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

DigitalSignatureCollection.Item Property

Gets a document signature at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As DigitalSignature
[C#]
public DigitalSignature this[
int index
] {get;}

Parameters

index
Zero-based index of the signature.

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
DigitalSignatureCollection digitalSignatureCollection = doc.DigitalSignatures;

if (digitalSignatureCollection.IsValid)
{
    Console.WriteLine("Signatures belonging to this document are valid");
    Console.WriteLine(digitalSignatureCollection.Count);
    Console.WriteLine(digitalSignatureCollection[0].SignatureType);
}
else
{
    Console.WriteLine("Signatures belonging to this document are NOT valid");
}

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


DigitalSignatureCollection Methods

The methods of the DigitalSignatureCollection class are listed below. For a complete list of DigitalSignatureCollection class members, see the DigitalSignatureCollection Members topic.

Public Instance Methods

GetEnumerator Returns a dictionary enumerator object that can be used to iterate over all items in the collection.

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


DigitalSignatureCollection.GetEnumerator Method

Returns a dictionary enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of DigitalSignature) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<DigitalSignature> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to load and enumerate all digital signatures of a document.

[C#]

DigitalSignatureCollection digitalSignatures =
    DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");

using (IEnumerator<DigitalSignature> enumerator = digitalSignatures.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        // Do something useful
        DigitalSignature ds = enumerator.Current;

        if (ds != null)
            Console.WriteLine(ds.ToString());
    }
}

See Also

DigitalSignatureCollection Class | Aspose.Words Namespace


DigitalSignatureType Enumeration

Specifies the type of a digital signature.

[Visual Basic]
Public Enum DigitalSignatureType
[C#]
public enum DigitalSignatureType

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
DigitalSignatureCollection digitalSignatureCollection = doc.DigitalSignatures;

if (digitalSignatureCollection.IsValid)
{
    Console.WriteLine("Signatures belonging to this document are valid");
    Console.WriteLine(digitalSignatureCollection.Count);
    Console.WriteLine(digitalSignatureCollection[0].SignatureType);
}
else
{
    Console.WriteLine("Signatures belonging to this document are NOT valid");
}

Members

Member Name | Description | Value
Unknown | Indicates an error, unknown digital signature type. | 0
CryptoApi | The Crypto API signature method used in Microsoft Word 97-2003 .DOC binary documents. | 1
XmlDsig | The XmlDsig signature method used in OOXML and OpenDocument documents. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


DigitalSignatureUtil Class

Provides methods for signing document.

For a list of all members of this type, see DigitalSignatureUtil Members.

System.Object
Aspose.Words.DigitalSignatureUtil

[Visual Basic]
MustInherit NotInheritable Public Class DigitalSignatureUtil
[C#]
public abstract sealed class DigitalSignatureUtil

Remarks

Since digital signature works with file content rather than Document Object Model these methods are put into a separate class.

Supported formats are Doc and Docx.

Example

Shows how to remove every signature from a document.

[C#]

// Remove all signatures from the document using string parameters
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
string outFileName = ArtifactsDir + "Document.NoSignatures.FromString.docx";

DigitalSignatureUtil.RemoveAllSignatures(doc.OriginalFileName, outFileName);

// Remove all signatures from the document using stream parameters
using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.NoSignatures.FromStream.docx", FileMode.Create))
    {
        DigitalSignatureUtil.RemoveAllSignatures(streamIn, streamOut);
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DigitalSignatureUtil Members | Aspose.Words Namespace


DigitalSignatureUtil Members

DigitalSignatureUtil overview

Public Static (Shared) Methods

LoadSignatures | Overloaded. Loads digital signatures from document.
RemoveAllSignatures | Overloaded. Removes all digital signatures from source file and writes unsigned file to destination file.
Sign | Overloaded. Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination stream. Document should be either Doc or Docx.Output will be written to the start of stream and stream size will be updated with content length.

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


DigitalSignatureUtil Methods

The methods of the DigitalSignatureUtil class are listed below. For a complete list of DigitalSignatureUtil class members, see the DigitalSignatureUtil Members topic.

Public Static (Shared) Methods

LoadSignatures | Overloaded. Loads digital signatures from document.
RemoveAllSignatures | Overloaded. Removes all digital signatures from source file and writes unsigned file to destination file.
Sign | Overloaded. Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination stream. Document should be either Doc or Docx.Output will be written to the start of stream and stream size will be updated with content length.

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


LoadSignatures Method

Aspose.Words

DigitalSignatureUtil.LoadSignatures Method

Loads digital signatures from document using stream.

Overload List

Loads digital signatures from document using stream.

public static DigitalSignatureCollection LoadSignatures(Stream);

Loads digital signatures from document.

public static DigitalSignatureCollection LoadSignatures(string);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


DigitalSignatureUtil.LoadSignatures Method (Stream)

Loads digital signatures from document using stream.

[Visual Basic]
Overloads Public Shared Function LoadSignatures( _
ByVal stream As Stream _
) As DigitalSignatureCollection
[C#]
public static DigitalSignatureCollection LoadSignatures(
Stream stream
);

Parameters

stream
Stream with the document.

Return Value

Collection of digital signatures. Returns empty collection if file is not signed.

Example

Shows how to load all existing signatures from a document.

[C#]

// Load all signatures from the document using string parameters
DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");
Assert.NotNull(digitalSignatures);

// Load all signatures from the document using stream parameters
Stream stream = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open);
digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.LoadSignatures Overload List


DigitalSignatureUtil.LoadSignatures Method (String)

Loads digital signatures from document.

[Visual Basic]
Overloads Public Shared Function LoadSignatures( _
ByVal fileName As String _
) As DigitalSignatureCollection
[C#]
public static DigitalSignatureCollection LoadSignatures(
string fileName
);

Parameters

fileName
Path to the document.

Return Value

Collection of digital signatures. Returns empty collection if file is not signed.

Example

Shows how to load all existing signatures from a document.

[C#]

// Load all signatures from the document using string parameters
DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.LoadSignatures(MyDir + "Document.DigitalSignature.docx");
Assert.NotNull(digitalSignatures);

// Load all signatures from the document using stream parameters
Stream stream = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open);
digitalSignatures = DigitalSignatureUtil.LoadSignatures(stream);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.LoadSignatures Overload List


RemoveAllSignatures Method

Aspose.Words

DigitalSignatureUtil.RemoveAllSignatures Method

Removes all digital signatures from document in source stream and writes unsigned document to destination stream.

Output will be written to the start of stream and stream size will be updated with content length.

Overload List

Removes all digital signatures from document in source stream and writes unsigned document to destination stream. Output will be written to the start of stream and stream size will be updated with content length.

public static void RemoveAllSignatures(Stream,Stream);

Removes all digital signatures from source file and writes unsigned file to destination file.

public static void RemoveAllSignatures(string,string);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


DigitalSignatureUtil.RemoveAllSignatures Method (Stream, Stream)

Removes all digital signatures from document in source stream and writes unsigned document to destination stream.

Output will be written to the start of stream and stream size will be updated with content length.

[Visual Basic]
Overloads Public Shared Sub RemoveAllSignatures( _
ByVal srcStream As Stream, _
ByVal dstStream As Stream _
)
[C#]
public static void RemoveAllSignatures(
Stream srcStream,
Stream dstStream
);

Example

Shows how to remove every signature from a document.

[C#]

// Remove all signatures from the document using string parameters
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
string outFileName = ArtifactsDir + "Document.NoSignatures.FromString.docx";

DigitalSignatureUtil.RemoveAllSignatures(doc.OriginalFileName, outFileName);

// Remove all signatures from the document using stream parameters
using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.NoSignatures.FromStream.docx", FileMode.Create))
    {
        DigitalSignatureUtil.RemoveAllSignatures(streamIn, streamOut);
    }
}

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.RemoveAllSignatures Overload List


DigitalSignatureUtil.RemoveAllSignatures Method (String, String)

Removes all digital signatures from source file and writes unsigned file to destination file.

[Visual Basic]
Overloads Public Shared Sub RemoveAllSignatures( _
ByVal srcFileName As String, _
ByVal dstFileName As String _
)
[C#]
public static void RemoveAllSignatures(
string srcFileName,
string dstFileName
);

Example

Shows how to remove every signature from a document.

[C#]

// Remove all signatures from the document using string parameters
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
string outFileName = ArtifactsDir + "Document.NoSignatures.FromString.docx";

DigitalSignatureUtil.RemoveAllSignatures(doc.OriginalFileName, outFileName);

// Remove all signatures from the document using stream parameters
using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.NoSignatures.FromStream.docx", FileMode.Create))
    {
        DigitalSignatureUtil.RemoveAllSignatures(streamIn, streamOut);
    }
}

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.RemoveAllSignatures Overload List


Sign Method

Aspose.Words

DigitalSignatureUtil.Sign Method

Signs source document using given CertificateHolder with digital signature and writes signed document to destination stream.

Document should be either Doc or Docx.

Output will be written to the start of stream and stream size will be updated with content length.

Overload List

Signs source document using given CertificateHolder with digital signature and writes signed document to destination stream. Document should be either Doc or Docx.Output will be written to the start of stream and stream size will be updated with content length.

public static void Sign(Stream,Stream,CertificateHolder);

Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination stream. Document should be either Doc or Docx.Output will be written to the start of stream and stream size will be updated with content length.

public static void Sign(Stream,Stream,CertificateHolder,SignOptions);

Signs source document using given CertificateHolder with digital signature and writes signed document to destination file. Document should be either Doc or Docx.

public static void Sign(string,string,CertificateHolder);

Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination file. Document should be either Doc or Docx.

public static void Sign(string,string,CertificateHolder,SignOptions);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


DigitalSignatureUtil.Sign Method (Stream, Stream, CertificateHolder)

Signs source document using given CertificateHolder with digital signature and writes signed document to destination stream.

Document should be either Doc or Docx.

Output will be written to the start of stream and stream size will be updated with content length.

[Visual Basic]
Overloads Public Shared Sub Sign( _
ByVal srcStream As Stream, _
ByVal dstStream As Stream, _
ByVal certHolder As CertificateHolder _
)
[C#]
public static void Sign(
Stream srcStream,
Stream dstStream,
CertificateHolder certHolder
);

Parameters

srcStream
The stream which contains the document to sign.
dstStream
The stream that signed document will be written to.
certHolder
CertificateHolder object with certificate that used to sign file. The certificate in holder MUST contain private keys and have the X509KeyStorageFlags.Exportable flag set.

Example

Shows how to sign documents with X.509 certificates.

[C#]

// Open an unsigned document
Document unSignedDoc = new Document(MyDir + "Document.docx");

// Verify that it isn't signed
Assert.False(FileFormatUtil.DetectFileFormat(MyDir + "Document.docx").HasDigitalSignature);
Assert.AreEqual(0, unSignedDoc.DigitalSignatures.Count);

// Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

// There are 2 ways of saving a signed copy of a document to the local file system
// 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.Signed.1.docx",
    certificateHolder, new SignOptions() { SignTime = DateTime.Now } );

// 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
using (FileStream inDoc = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    using (FileStream outDoc = new FileStream(ArtifactsDir + "Document.Signed.2.docx", FileMode.Create))
    {
        DigitalSignatureUtil.Sign(inDoc, outDoc, certificateHolder);
    }
}

// Verify that our documents are signed
Document signedDoc = new Document(ArtifactsDir + "Document.Signed.1.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.1.docx").HasDigitalSignature);
Assert.AreEqual(1,signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

signedDoc = new Document(ArtifactsDir + "Document.Signed.2.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.2.docx").HasDigitalSignature);
Assert.AreEqual(1, signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

// These digital signatures will have some of the properties from the X.509 certificate from the .pfx file we used
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].IssuerName);
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].SubjectName);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.Sign Overload List


DigitalSignatureUtil.Sign Method (Stream, Stream, CertificateHolder, SignOptions)

Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination stream.

Document should be either Doc or Docx.

Output will be written to the start of stream and stream size will be updated with content length.

[Visual Basic]
Overloads Public Shared Sub Sign( _
ByVal srcStream As Stream, _
ByVal dstStream As Stream, _
ByVal certHolder As CertificateHolder, _
ByVal signOptions As SignOptions _
)
[C#]
public static void Sign(
Stream srcStream,
Stream dstStream,
CertificateHolder certHolder,
SignOptions signOptions
);

Parameters

srcStream
The stream which contains the document to sign.
dstStream
The stream that signed document will be written to.
certHolder
CertificateHolder object with certificate that used to sign file. The certificate in holder MUST contain private keys and have the X509KeyStorageFlags.Exportable flag set.
signOptions
SignOptions object with various signing options.

Example

Shows how to sign documents using certificate holder and sign options.

[C#]

CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions { Comments = "My comment", SignTime = DateTime.Now };

using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.DigitalSignature.docx", FileMode.OpenOrCreate))
    {
        DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
    }
}

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.Sign Overload List


DigitalSignatureUtil.Sign Method (String, String, CertificateHolder)

Signs source document using given CertificateHolder with digital signature and writes signed document to destination file.

Document should be either Doc or Docx.

[Visual Basic]
Overloads Public Shared Sub Sign( _
ByVal srcFileName As String, _
ByVal dstFileName As String, _
ByVal certHolder As CertificateHolder _
)
[C#]
public static void Sign(
string srcFileName,
string dstFileName,
CertificateHolder certHolder
);

Parameters

srcFileName
The file name of the document to sign.
dstFileName
The file name of the signed document output.
certHolder
CertificateHolder object with certificate that used to sign file. The certificate in holder MUST contain private keys and have the X509KeyStorageFlags.Exportable flag set.

Example

Shows how to sign documents with X.509 certificates.

[C#]

// Open an unsigned document
Document unSignedDoc = new Document(MyDir + "Document.docx");

// Verify that it isn't signed
Assert.False(FileFormatUtil.DetectFileFormat(MyDir + "Document.docx").HasDigitalSignature);
Assert.AreEqual(0, unSignedDoc.DigitalSignatures.Count);

// Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

// There are 2 ways of saving a signed copy of a document to the local file system
// 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.Signed.1.docx",
    certificateHolder, new SignOptions() { SignTime = DateTime.Now } );

// 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
using (FileStream inDoc = new FileStream(MyDir + "Document.docx", FileMode.Open))
{
    using (FileStream outDoc = new FileStream(ArtifactsDir + "Document.Signed.2.docx", FileMode.Create))
    {
        DigitalSignatureUtil.Sign(inDoc, outDoc, certificateHolder);
    }
}

// Verify that our documents are signed
Document signedDoc = new Document(ArtifactsDir + "Document.Signed.1.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.1.docx").HasDigitalSignature);
Assert.AreEqual(1,signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

signedDoc = new Document(ArtifactsDir + "Document.Signed.2.docx");
Assert.True(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.Signed.2.docx").HasDigitalSignature);
Assert.AreEqual(1, signedDoc.DigitalSignatures.Count);
Assert.True(signedDoc.DigitalSignatures[0].IsValid);

// These digital signatures will have some of the properties from the X.509 certificate from the .pfx file we used
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].IssuerName);
Assert.AreEqual("CN=Morzal.Me", signedDoc.DigitalSignatures[0].SubjectName);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.Sign Overload List


DigitalSignatureUtil.Sign Method (String, String, CertificateHolder, SignOptions)

Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination file.

Document should be either Doc or Docx.

[Visual Basic]
Overloads Public Shared Sub Sign( _
ByVal srcFileName As String, _
ByVal dstFileName As String, _
ByVal certHolder As CertificateHolder, _
ByVal signOptions As SignOptions _
)
[C#]
public static void Sign(
string srcFileName,
string dstFileName,
CertificateHolder certHolder,
SignOptions signOptions
);

Parameters

srcFileName
The file name of the document to sign.
dstFileName
The file name of the signed document output.
certHolder
CertificateHolder object with certificate that used to sign file. The certificate in holder MUST contain private keys and have the X509KeyStorageFlags.Exportable flag set.
signOptions
SignOptions object with various signing options.

Example

Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.

[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.Sign Overload List


Document Class

Represents a Word document.

For a list of all members of this type, see Document Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.DocumentBase
Aspose.Words.Document

[Visual Basic]
Public Class Document
Inherits DocumentBase
[C#]
public class Document : DocumentBase

Remarks

The Document is a central object in the Aspose.Words library.

To load an existing document in any of the LoadFormat formats, pass a file name or a stream into one of the Document constructors. To create a blank document, call the constructor without parameters.

Use one of the Save method overloads to save the document in any of the SaveFormat formats.

To draw document pages directly onto a Graphics object use RenderToScale or RenderToSize method.

To print the document, use one of the Print methods.

MailMerge is the Aspose.Words's reporting engine that allows to populate reports designed in Microsoft Word with data from various data sources quickly and easily. The data can be from a DataSet, DataTable, DataView, IDataReader or an array of values. MailMerge will go through the records found in the data source and insert them into mail merge fields in the document growing it as necessary.

Document stores document-wide information such as Styles, BuiltInDocumentProperties, CustomDocumentProperties, lists and macros. Most of these objects are accessible via the corresponding properties of the Document.

The Document is a root node of a tree that contains all other nodes of the document. The tree is a Composite design pattern and in many ways similar to XmlDocument. The content of the document can be manipulated freely programmatically:

  • The nodes of the document can be accessed via typed collections, for example Sections, ParagraphCollection etc.
  • The nodes of the document can be selected by their node type using GetChildNodes or using an XPath query with SelectNodes or SelectSingleNode.
  • Content nodes can be added or removed from anywhere in the document using InsertBefore, InsertAfter, RemoveChild and other methods provided by the base class CompositeNode.
  • The formatting attributes of each node can be changed via the properties of that node.

Consider using DocumentBuilder that simplifies the task of programmatically creating or populating the document tree.

The Document can contain only Section objects.

In Microsoft Word, a valid document needs to have at least one section.

Example

Converts a whole document from DOC to PDF using default options.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Save(ArtifactsDir + "Document.Doc2PdfSave.pdf");
Executes mail merge from an ADO.NET DataTable.
[C#]

Document doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
DataTable table = new DataTable("Test");
table.Columns.Add("CustomerName");
table.Columns.Add("Address");
table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.MailMerge.Execute(table);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.doc");

// Open a fresh copy of our document to perform another mail merge.
doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// We can also source values for a mail merge from a single row in the table
doc.MailMerge.Execute(table.Rows[1]);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Document Members | Aspose.Words Namespace


Document Members

Document overview

Public Instance Constructors

Document Overloaded. Creates or loads a document.

Public Instance Properties

AttachedTemplate | Gets or sets the full path of the template attached to the document.
AutomaticallyUpdateSyles | Gets or sets a flag indicating whether the styles in the document are updated to match the styles in the attached template each time the document is opened in MS Word.
BackgroundShape (inherited from DocumentBase) | Gets or sets the background shape of the document. Can be null.
BuiltInDocumentProperties | Returns a collection that represents all the built-in document properties of the document.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CompatibilityOptions | Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
Compliance | Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
CustomDocumentProperties | Returns a collection that represents all the custom document properties of the document.
CustomXmlParts | Gets or sets the collection of Custom XML Data Storage Parts.
DefaultTabStop | Gets or sets the interval (in points) between the default tab stops.
DigitalSignatures | Gets the collection of digital signatures for this document and their validation results.
Document (inherited from Node) | Gets the document to which this node belongs.
EndnoteOptions | Provides options that control numbering and positioning of endnotes in this document.
FieldOptions | Gets a FieldOptions object that represents options to control field handling in the document.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstSection | Gets the first section in the document.
FontInfos (inherited from DocumentBase) | Provides access to properties of fonts used in this document.
FontSettings | Gets or sets document font settings.
FootnoteOptions | Provides options that control numbering and positioning of footnotes in this document.
GlossaryDocument | Gets or sets the glossary document within this document or template. A glossary document is a storage for AutoText, AutoCorrect and Building Block entries defined in a document.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HasMacros | Returns true if the document has a VBA project (macros).
HasRevisions | Returns true if the document has any tracked changes.
HyphenationOptions | Provides access to document hyphenation options.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastSection | Gets the last section in the document.
LayoutOptions | Gets a LayoutOptions object that represents options to control the layout process of this document.
Lists (inherited from DocumentBase) | Provides access to the list formatting used in the document.
MailMerge | Returns a MailMerge object that represents the mail merge functionality for the document.
MailMergeSettings | Gets or sets the object that contains all of the mail merge information for a document.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeChangingCallback (inherited from DocumentBase) | Called when a node is inserted or removed in the document.
NodeType | Returns NodeType.Document.
OriginalFileName | Gets the original file name of the document.
OriginalLoadFormat | Gets the format of the original document that was loaded into this object.
PackageCustomParts | Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using "unknown relationships".
PageColor (inherited from DocumentBase) | Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
PageCount | Gets the number of pages in the document as calculated by the most recent page layout operation.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
ProtectionType | Gets the currently active document protection type.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RemovePersonalInformation | Gets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.
ResourceLoadingCallback (inherited from DocumentBase) | Allows to control how external resources are loaded.
Revisions | Gets a collection of revisions (tracked changes) that exist in this document.
Sections | Returns a collection that represents all sections in the document.
ShadeFormData | Specifies whether to turn on the gray shading on form fields.
Styles (inherited from DocumentBase) | Returns a collection of styles defined in the document.
Theme | Gets the Theme object for this document.
TrackRevisions | True if changes are tracked when this document is edited in Microsoft Word.
Variables | Returns the collection of variables added to a document or template.
VbaProject | Gets VbaProject containing in the document.
VersionsCount | Gets the number of document versions that was stored in the DOC document.
ViewOptions | Provides options to control how the document is displayed in Microsoft Word.
WarningCallback (inherited from DocumentBase) | Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.
WriteProtection | Provides access to the document write protection options.

Public Instance Methods

Accept | Accepts a visitor.
AcceptAllRevisions | Accepts all tracked changes in the document.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendDocument | Overloaded. Appends the specified document to the end of this document.
Cleanup | Overloaded. Cleans unused styles and lists from the document.
Clone | Overloaded. Performs a deep copy of the Document.
Clone (inherited from Node) | Overloaded.
Compare | Overloaded. Compares this document with another document producing changes as number of edit and format revisions Revision.
CopyStylesFromTemplate | Overloaded. Copies styles from the specified template to a document.
EnsureMinimum | If the document contains no sections, creates one section with one paragraph.
ExpandTableStylesToDirectFormatting | Converts formatting specified in table styles into direct formatting on tables in the document.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetPageInfo | Gets the page size, orientation and other information about a page that might be useful for printing or rendering.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
ImportNode (inherited from DocumentBase) | Overloaded. Imports a node from another document to the current document.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
JoinRunsWithSameFormatting | Joins runs with same formatting in all paragraphs of the document.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
NormalizeFieldTypes | Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Print | Overloaded. Prints the document without bringing up any user interface forms.
Protect | Overloaded. Protects the document from changes.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveExternalSchemaReferences | Removes external XML schema references from this document.
RemoveMacros | Removes all macros (the VBA project) as well as toolbars and command customizations from the document.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
RenderToScale | Renders a document page into a Graphics object to a specified scale.
RenderToSize |
Save | Overloaded. Saves the document.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
StartTrackRevisions | Overloaded. Starts automatically marking all further changes you make to the document programmatically as revision changes.
StopTrackRevisions | Stops automatic marking of document changes as revisions.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.
UnlinkFields | Unlinks fields in the whole document.
Unprotect | Overloaded. Removes protection from the document.
UpdateFields | Updates the values of fields in the whole document.
UpdateListLabels | Updates list labels for all list items in the document.
UpdatePageLayout | Rebuilds the page layout of the document.
UpdateTableLayout | Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document.
UpdateThumbnail | Overloaded. Updates Thumbnail of the document according to the specified options.
UpdateWordCount | Overloaded. Updates word count properties of the document.

See Also

Document Class | Aspose.Words Namespace


Document Constructor

Creates or loads a document.

Overload List

Creates a blank Word document.

public Document();

Opens an existing document from a stream. Automatically detects the file format.

public Document(Stream);

Opens an existing document from a stream. Allows to specify additional options such as an encryption password.

public Document(Stream,LoadOptions);

Opens an existing document from a file. Automatically detects the file format.

public Document(string);

Opens an existing document from a file. Allows to specify additional options such as an encryption password.

public Document(string,LoadOptions);

See Also

Document Class | Aspose.Words Namespace


Document Constructor ()

Creates a blank Word document.

[Visual Basic]
Overloads Public Sub New()
[C#]
public Document();

Remarks

The document paper size is Letter by default. If you want to change page setup, use Section.PageSetup.

After creation, you can use DocumentBuilder to add document content easily.

Example

Shows how to add a formatted run of text to a document using the object model.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);

See Also

Document Class | Aspose.Words Namespace | Document Constructor Overload List


Document Constructor (String)

Opens an existing document from a file. Automatically detects the file format.

[Visual Basic]
Overloads Public Sub New( _
ByVal fileName As String _
)
[C#]
public Document(
string fileName
);

Parameters

fileName
File name of the document to open.

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentException | The name of the file cannot be null or empty string.

Example

Opens a document from a file.

[C#]

// Open a document. The file is opened read only and only for the duration of the constructor.
Document doc = new Document(MyDir + "Document.doc");

See Also

Document Class | Aspose.Words Namespace | Document Constructor Overload List


Document Constructor (String, LoadOptions)

Opens an existing document from a file. Allows to specify additional options such as an encryption password.

[Visual Basic]
Overloads Public Sub New( _
ByVal fileName As String, _
ByVal loadOptions As LoadOptions _
)
[C#]
public Document(
string fileName,
LoadOptions loadOptions
);

Parameters

fileName
File name of the document to open.
loadOptions
Additional options to use when loading a document. Can be null.

Remarks

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentException | The name of the file cannot be null or empty string.

Example

Loads a Microsoft Word document encrypted with a password.

[C#]

Document doc = new Document(MyDir + "Document.LoadEncrypted.doc", new LoadOptions("qwerty"));
Explicitly loads a document as HTML without automatic file format detection.
[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

Document doc = new Document(MyDir + "Document.LoadFormat.html", loadOptions);

See Also

Document Class | Aspose.Words Namespace | Document Constructor Overload List


Document Constructor (Stream)

Opens an existing document from a stream. Automatically detects the file format.

[Visual Basic]
Overloads Public Sub New( _
ByVal stream As Stream _
)
[C#]
public Document(
Stream stream
);

Parameters

stream
Stream where to load the document from.

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentNullException | The stream cannot be null.
NotSupportedException | The stream does not support reading or seeking.
ObjectDisposedException | The stream is a disposed object.

Example

Opens a document from a stream.

[C#]

// Open the stream. Read only access is enough for Aspose.Words to load a document.
using (Stream stream = File.OpenRead(MyDir + "Document.doc"))
{
    // Load the entire document into memory.
    Document doc = new Document(stream);
}
// ... do something with the document
Retrieves a document from a URL and saves it to disk in a different format.
[C#]

// This is the URL address pointing to where to find the document.
String url = "https://is.gd/URJluZ";
// The easiest way to load our document from the internet is make use of the
// System.Net.WebClient class. Create an instance of it and pass the URL
// to download from.
using (WebClient webClient = new WebClient())
{
    // Download the bytes from the location referenced by the URL.
    byte[] dataBytes = webClient.DownloadData(url);

    // Wrap the bytes representing the document in memory into a MemoryStream object.
    using (MemoryStream byteStream = new MemoryStream(dataBytes))
    {
        // Load this memory stream into a new Aspose.Words Document.
        // The file format of the passed data is inferred from the content of the bytes itself.
        // You can load any document format supported by Aspose.Words in the same way.
        Document doc = new Document(byteStream);

        // Convert the document to any format supported by Aspose.Words.
        doc.Save(ArtifactsDir + "Document.OpenFromWeb.docx");
    }
}

See Also

Document Class | Aspose.Words Namespace | Document Constructor Overload List


Document Constructor (Stream, LoadOptions)

Opens an existing document from a stream. Allows to specify additional options such as an encryption password.

[Visual Basic]
Overloads Public Sub New( _
ByVal stream As Stream, _
ByVal loadOptions As LoadOptions _
)
[C#]
public Document(
Stream stream,
LoadOptions loadOptions
);

Parameters

stream
The stream where to load the document from.
loadOptions
Additional options to use when loading a document. Can be null.

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentNullException | The stream cannot be null.
NotSupportedException | The stream does not support reading or seeking.
ObjectDisposedException | The stream is a disposed object.

Example

Loads a Microsoft Word document encrypted with a password from a stream.

[C#]

using (Stream stream = File.OpenRead(MyDir + "Document.LoadEncrypted.doc"))
{
    Document doc = new Document(stream, new LoadOptions("qwerty"));
}
Opens an HTML document with images from a stream using a base URI.
[C#]

Document doc = new Document();
// We are opening this HTML file:
//    <html>
//    <body>
//    <p>Simple file.</p>
//    <p><img src="Aspose.Words.gif" width="80" height="60"></p>
//    </body>
//    </html>
String fileName = MyDir + "Document.OpenFromStreamWithBaseUri.html";
// Open the stream.
using (Stream stream = File.OpenRead(fileName))
{
    // Open the document. Note the Document constructor detects HTML format automatically.
    // Pass the URI of the base folder so any images with relative URIs in the HTML document can be found.
    LoadOptions loadOptions = new LoadOptions();
    loadOptions.BaseUri = MyDir;

    doc = new Document(stream, loadOptions);
}

// Save in the DOC format.
doc.Save(ArtifactsDir + "Document.OpenFromStreamWithBaseUri.doc");
Shows how to insert the HTML contents from a web page into a new document.
[C#]

// The url of the page to load
String url = "http://www.aspose.com/";

// Create a WebClient object to easily extract the HTML from the page.
WebClient client = new WebClient();
String pageSource = client.DownloadString(url);
client.Dispose();

// Get the HTML as bytes for loading into a stream.
Encoding encoding = client.Encoding;
byte[] pageBytes = encoding.GetBytes(pageSource);

// Load the HTML into a stream.
using (MemoryStream stream = new MemoryStream(pageBytes))
{
    // The baseUri property should be set to ensure any relative img paths are retrieved correctly.
    LoadOptions options = new LoadOptions(Aspose.Words.LoadFormat.Html, "", url);

    // Load the HTML document from stream and pass the LoadOptions object.
    Document doc = new Document(stream, options);

    // Save the document to disk.
    // The extension of the filename can be changed to save the document into other formats. e.g PDF, DOCX, ODT, RTF.
    doc.Save(ArtifactsDir + "Document.HtmlPageFromWebpage.doc");
}

See Also

Document Class | Aspose.Words Namespace | Document Constructor Overload List


Document Properties

The properties of the Document class are listed below. For a complete list of Document class members, see the Document Members topic.

Public Instance Properties

AttachedTemplate | Gets or sets the full path of the template attached to the document.
AutomaticallyUpdateSyles | Gets or sets a flag indicating whether the styles in the document are updated to match the styles in the attached template each time the document is opened in MS Word.
BackgroundShape (inherited from DocumentBase) | Gets or sets the background shape of the document. Can be null.
BuiltInDocumentProperties | Returns a collection that represents all the built-in document properties of the document.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CompatibilityOptions | Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
Compliance | Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
CustomDocumentProperties | Returns a collection that represents all the custom document properties of the document.
CustomXmlParts | Gets or sets the collection of Custom XML Data Storage Parts.
DefaultTabStop | Gets or sets the interval (in points) between the default tab stops.
DigitalSignatures | Gets the collection of digital signatures for this document and their validation results.
Document (inherited from Node) | Gets the document to which this node belongs.
EndnoteOptions | Provides options that control numbering and positioning of endnotes in this document.
FieldOptions | Gets a FieldOptions object that represents options to control field handling in the document.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstSection | Gets the first section in the document.
FontInfos (inherited from DocumentBase) | Provides access to properties of fonts used in this document.
FontSettings | Gets or sets document font settings.
FootnoteOptions | Provides options that control numbering and positioning of footnotes in this document.
GlossaryDocument | Gets or sets the glossary document within this document or template. A glossary document is a storage for AutoText, AutoCorrect and Building Block entries defined in a document.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HasMacros | Returns true if the document has a VBA project (macros).
HasRevisions | Returns true if the document has any tracked changes.
HyphenationOptions | Provides access to document hyphenation options.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastSection | Gets the last section in the document.
LayoutOptions | Gets a LayoutOptions object that represents options to control the layout process of this document.
Lists (inherited from DocumentBase) | Provides access to the list formatting used in the document.
MailMerge | Returns a MailMerge object that represents the mail merge functionality for the document.
MailMergeSettings | Gets or sets the object that contains all of the mail merge information for a document.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeChangingCallback (inherited from DocumentBase) | Called when a node is inserted or removed in the document.
NodeType | Returns NodeType.Document.
OriginalFileName | Gets the original file name of the document.
OriginalLoadFormat | Gets the format of the original document that was loaded into this object.
PackageCustomParts | Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using "unknown relationships".
PageColor (inherited from DocumentBase) | Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
PageCount | Gets the number of pages in the document as calculated by the most recent page layout operation.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
ProtectionType | Gets the currently active document protection type.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RemovePersonalInformation | Gets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.
ResourceLoadingCallback (inherited from DocumentBase) | Allows to control how external resources are loaded.
Revisions | Gets a collection of revisions (tracked changes) that exist in this document.
Sections | Returns a collection that represents all sections in the document.
ShadeFormData | Specifies whether to turn on the gray shading on form fields.
Styles (inherited from DocumentBase) | Returns a collection of styles defined in the document.
Theme | Gets the Theme object for this document.
TrackRevisions | True if changes are tracked when this document is edited in Microsoft Word.
Variables | Returns the collection of variables added to a document or template.
VbaProject | Gets VbaProject containing in the document.
VersionsCount | Gets the number of document versions that was stored in the DOC document.
ViewOptions | Provides options to control how the document is displayed in Microsoft Word.
WarningCallback (inherited from DocumentBase) | Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.
WriteProtection | Provides access to the document write protection options.

See Also

Document Class | Aspose.Words Namespace


AttachedTemplate Property

Aspose.Words

Document.AttachedTemplate Property

Gets or sets the full path of the template attached to the document.

[Visual Basic]
Public Property AttachedTemplate As String
[C#]
public string AttachedTemplate {get; set;}

Remarks

Empty string means the document is attached to the Normal template.

Exceptions

Exception Type | Condition
ArgumentNullException | Throws if you attempt to set to a null value.

Example

Opens a document, makes sure it is no longer attached to a template and saves the document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.AttachedTemplate = "";
doc.Save(ArtifactsDir + "Document.DetachTemplate.doc");

See Also

Document Class | Aspose.Words Namespace | Template


AutomaticallyUpdateSyles Property

Aspose.Words

Document.AutomaticallyUpdateSyles Property

Gets or sets a flag indicating whether the styles in the document are updated to match the styles in the attached template each time the document is opened in MS Word.

[Visual Basic]
Public Property AutomaticallyUpdateSyles As Boolean
[C#]
public bool AutomaticallyUpdateSyles {get; set;}

Example

Shows how to update a document's styles based on its template.

[C#]

Document doc = new Document();

// Empty Microsoft Word documents by default come with an attached template called "Normal.dotm"
// There is no default template for Aspose Words documents
Assert.AreEqual(string.Empty, doc.AttachedTemplate);

// For AutomaticallyUpdateStyles to have any effect, we need a document with a template
// We can make a document with word and open it
// Or we can attach a template from our file system, as below
doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dotx";

Assert.IsTrue(doc.AttachedTemplate.EndsWith("Document.BusinessBrochureTemplate.dotx"));

// Any changes to the styles in this template will be propagated to those styles in the document
doc.AutomaticallyUpdateSyles = true;

doc.Save(ArtifactsDir + "TemplateStylesUpdating.docx");

See Also

Document Class | Aspose.Words Namespace


BuiltInDocumentProperties Property

Aspose.Words

Document.BuiltInDocumentProperties Property

Returns a collection that represents all the built-in document properties of the document.

[Visual Basic]
Public ReadOnly Property BuiltInDocumentProperties As BuiltInDocumentProperties
[C#]
public BuiltInDocumentProperties BuiltInDocumentProperties {get;}

Example

Enumerates through all built-in and custom properties in a document.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty docProperty in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

See Also

Document Class | Aspose.Words Namespace


CompatibilityOptions Property

Aspose.Words

Document.CompatibilityOptions Property

Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).

[Visual Basic]
Public ReadOnly Property CompatibilityOptions As CompatibilityOptions
[C#]
public CompatibilityOptions CompatibilityOptions {get;}

Example

Shows how to optimize our document for different word versions.

[C#]

Document doc = new Document();
CompatibilityOptions co = doc.CompatibilityOptions;

// Here are some default values
Assert.AreEqual(true, co.GrowAutofit);
Assert.AreEqual(false, co.DoNotBreakWrappedTables);
Assert.AreEqual(false, co.DoNotUseEastAsianBreakRules);
Assert.AreEqual(false, co.SelectFldWithFirstOrLastChar);
Assert.AreEqual(false, co.UseWord97LineBreakRules);
Assert.AreEqual(true, co.UseWord2002TableStyleRules);
Assert.AreEqual(false, co.UseWord2010TableStyleRules);

// This example covers only a small portion of all the compatibility attributes
// To see the entire list, in any of the output files go into File > Options > Advanced > Compatibility for...
doc.Save(ArtifactsDir + "DefaultCompatibility.docx");

// We can hand pick any value and change it to create a custom compatibility
// We can also change a bunch of values at once to suit a defined compatibility scheme with the OptimizeFor method
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2010);

Assert.AreEqual(false, co.GrowAutofit);
Assert.AreEqual(false, co.GrowAutofit);
Assert.AreEqual(false, co.DoNotBreakWrappedTables);
Assert.AreEqual(false, co.DoNotUseEastAsianBreakRules);
Assert.AreEqual(false, co.SelectFldWithFirstOrLastChar);
Assert.AreEqual(false, co.UseWord97LineBreakRules);
Assert.AreEqual(false, co.UseWord2002TableStyleRules);
Assert.AreEqual(true, co.UseWord2010TableStyleRules);

doc.Save(ArtifactsDir + "Optimised for Word 2010.docx");

doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2000);

Assert.AreEqual(true, co.GrowAutofit);
Assert.AreEqual(true, co.DoNotBreakWrappedTables);
Assert.AreEqual(true, co.DoNotUseEastAsianBreakRules);
Assert.AreEqual(true, co.SelectFldWithFirstOrLastChar);
Assert.AreEqual(false, co.UseWord97LineBreakRules);
Assert.AreEqual(true, co.UseWord2002TableStyleRules);
Assert.AreEqual(false, co.UseWord2010TableStyleRules);

doc.Save(ArtifactsDir + "Optimised for Word 2000.docx");

See Also

Document Class | Aspose.Words Namespace


Compliance Property

Aspose.Words

Document.Compliance Property

Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents.

[Visual Basic]
Public ReadOnly Property Compliance As OoxmlCompliance
[C#]
public OoxmlCompliance Compliance {get;}

Remarks

If you created a new blank document or load non OOXML document returns the Ecma376_2006 value.

Example

Shows how to get OOXML compliance version.

[C#]

Document doc = new Document(MyDir + "Document.doc");

OoxmlCompliance compliance = doc.Compliance;

See Also

Document Class | Aspose.Words Namespace


CustomDocumentProperties Property

Aspose.Words

Document.CustomDocumentProperties Property

Returns a collection that represents all the custom document properties of the document.

[Visual Basic]
Public ReadOnly Property CustomDocumentProperties As CustomDocumentProperties
[C#]
public CustomDocumentProperties CustomDocumentProperties {get;}

Example

Enumerates through all built-in and custom properties in a document.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty docProperty in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

See Also

Document Class | Aspose.Words Namespace


CustomXmlParts Property

Aspose.Words

Document.CustomXmlParts Property

Gets or sets the collection of Custom XML Data Storage Parts.

[Visual Basic]
Public Property CustomXmlParts As CustomXmlPartCollection
[C#]
public CustomXmlPartCollection CustomXmlParts {get; set;}

Remarks

Aspose.Words loads and saves Custom XML Parts into OOXML and DOC documents only.

This property cannot be null.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

Document Class | Aspose.Words Namespace | CustomXmlPart


DefaultTabStop Property

Aspose.Words

Document.DefaultTabStop Property

Gets or sets the interval (in points) between the default tab stops.

[Visual Basic]
Public Property DefaultTabStop As Double
[C#]
public double DefaultTabStop {get; set;}

Remarks

Example

Changes default tab positions for the document and inserts text with some tab characters.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Set default tab stop to 72 points (1 inch).
builder.Document.DefaultTabStop = 72;

builder.Writeln("Hello" + ControlChar.Tab + "World!");
builder.Writeln("Hello" + ControlChar.TabChar + "World!");

See Also

Document Class | Aspose.Words Namespace | TabStopCollection | TabStop


DigitalSignatures Property

Aspose.Words

Document.DigitalSignatures Property

Gets the collection of digital signatures for this document and their validation results.

[Visual Basic]
Public ReadOnly Property DigitalSignatures As DigitalSignatureCollection
[C#]
public DigitalSignatureCollection DigitalSignatures {get;}

Remarks

This collection contains digital signatures that were loaded from the original document. These digital signatures will not be saved when you save this Document object into a file or stream because saving or converting will produce a document that is different from the original and the original digital signatures will no longer be valid.

This collection is never null. If the document is not signed, it will contain zero elements.

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");
DigitalSignatureCollection digitalSignatureCollection = doc.DigitalSignatures;

if (digitalSignatureCollection.IsValid)
{
    Console.WriteLine("Signatures belonging to this document are valid");
    Console.WriteLine(digitalSignatureCollection.Count);
    Console.WriteLine(digitalSignatureCollection[0].SignatureType);
}
else
{
    Console.WriteLine("Signatures belonging to this document are NOT valid");
}
Shows how to validate each signature in a document and display basic information about the signature.
[C#]

// Load the document which contains signature.
Document doc = new Document(MyDir + "Document.DigitalSignature.docx");

foreach (DigitalSignature signature in doc.DigitalSignatures)
{
    Console.WriteLine("*** Signature Found ***");
    Console.WriteLine("Is valid: " + signature.IsValid);
    Console.WriteLine("Reason for signing: " +
                      signature.Comments); // This property is available in MS Word documents only.
    Console.WriteLine("Signature type: " + signature.SignatureType);
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName);
    Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
    Console.WriteLine();
}

See Also

Document Class | Aspose.Words Namespace


EndnoteOptions Property

Aspose.Words

Document.EndnoteOptions Property

Provides options that control numbering and positioning of endnotes in this document.

[Visual Basic]
Public ReadOnly Property EndnoteOptions As EndnoteOptions
[C#]
public EndnoteOptions EndnoteOptions {get;}

Example

Shows how access a document's endnote options and see some of its default values.

[C#]

Document doc = new Document();

Assert.AreEqual(1, doc.EndnoteOptions.StartNumber);
Assert.AreEqual(EndnotePosition.EndOfDocument, doc.EndnoteOptions.Position);
Assert.AreEqual(NumberStyle.LowercaseRoman, doc.EndnoteOptions.NumberStyle);
Assert.AreEqual(FootnoteNumberingRule.Default, doc.EndnoteOptions.RestartRule);

See Also

Document Class | Aspose.Words Namespace


FieldOptions Property

Aspose.Words

Document.FieldOptions Property

Gets a FieldOptions object that represents options to control field handling in the document.

[Visual Basic]
Public ReadOnly Property FieldOptions As FieldOptions
[C#]
public FieldOptions FieldOptions {get;}

Example

Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.

[C#]

// Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
doc.MailMerge.Execute(new[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });

See Also

Document Class | Aspose.Words Namespace


FirstSection Property

Aspose.Words

Document.FirstSection Property

Gets the first section in the document.

[Visual Basic]
Public ReadOnly Property FirstSection As Section
[C#]
public Section FirstSection {get;}

Remarks

Returns null if there are no sections.

Example

Shows how to replace text in the document footer.

[C#]

// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(MyDir + "HeaderFooter.ReplaceText.doc");

HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = false
};

footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options);

doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.doc");
Shows how you can enumerate through children of a composite node and detect types of the children nodes.
[C#]

// Open a document.
Document doc = new Document(MyDir + "Section.BodyNodeType.doc");

// Get the first section in the document.
Section section = doc.FirstSection;

// A Section is a composite node and therefore can contain child nodes.
// Section can contain only Body and HeaderFooter nodes.
foreach (Node node in section)
{
    // Every node has the NodeType property.
    switch (node.NodeType)
    {
        case NodeType.Body:
        {
            // If the node type is Body, we can cast the node to the Body class.
            Body body = (Body) node;

            // Write the content of the main story of the section to the console.
            Console.WriteLine("*** Body ***");
            Console.WriteLine(body.GetText());
            break;
        }
        case NodeType.HeaderFooter:
        {
            // If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
            HeaderFooter headerFooter = (HeaderFooter) node;

            // Write the content of the header footer to the console.
            Console.WriteLine("*** HeaderFooter ***");
            Console.WriteLine(headerFooter.HeaderFooterType);
            Console.WriteLine(headerFooter.GetText());
            break;
        }
        default:
        {
            // Other types of nodes never occur inside a Section node.
            throw new Exception("Unexpected node type in a section.");
        }
    }
}

See Also

Document Class | Aspose.Words Namespace


FontSettings Property

Aspose.Words

Document.FontSettings Property

Gets or sets document font settings.

[Visual Basic]
Public Property FontSettings As FontSettings
[C#]
public FontSettings FontSettings {get; set;}

Remarks

This property allows to specify font settings per document. If set to null, default static font settings DefaultInstance will be used.

The default value is null.

Example

Shows how to define alternative fonts if original does not exist

[C#]

FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.TableSubstitution.SetSubstitutes("Times New Roman", new String[] { "Slab", "Arvo" });

See Also

Document Class | Aspose.Words Namespace


FootnoteOptions Property

Aspose.Words

Document.FootnoteOptions Property

Provides options that control numbering and positioning of footnotes in this document.

[Visual Basic]
Public ReadOnly Property FootnoteOptions As FootnoteOptions
[C#]
public FootnoteOptions FootnoteOptions {get;}

Example

Shows how to add a footnote to a paragraph in the document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

for (int i = 0; i <= 100; i++)
{
    builder.Write("Some text " + i);

    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i);
    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i, "242");
}

See Also

Document Class | Aspose.Words Namespace


GlossaryDocument Property

Aspose.Words

Document.GlossaryDocument Property

Gets or sets the glossary document within this document or template. A glossary document is a storage for AutoText, AutoCorrect and Building Block entries defined in a document.

[Visual Basic]
Public Property GlossaryDocument As GlossaryDocument
[C#]
public GlossaryDocument GlossaryDocument {get; set;}

Remarks

This property returns null if the document does not have a glossary document.

You can add a glossary document to a document by creating a GlossaryDocument object and assigning to this property.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

Document Class | Aspose.Words Namespace | GlossaryDocument


HasMacros Property

Aspose.Words

Document.HasMacros Property

Returns true if the document has a VBA project (macros).

[Visual Basic]
Public ReadOnly Property HasMacros As Boolean
[C#]
public bool HasMacros {get;}

Remarks

Example

Shows how to use MACROBUTTON fields that enable us to run macros by clicking.

[C#]

// Open a document that contains macros
Document doc = new Document(MyDir + "Document.HasMacro.docm");
DocumentBuilder builder = new DocumentBuilder(doc);
Assert.IsTrue(doc.HasMacros);

// Insert a MACROBUTTON field and reference by name a macro that exists within the input document
FieldMacroButton field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "MyMacro";
field.DisplayText = "Double click to run macro: " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  MyMacro Double click to run macro: MyMacro", field.GetFieldCode());

builder.InsertParagraph();

// Reference "ViewZoom200", a macro that was shipped with Microsoft Word, found under "Word commands"
// If our document has a macro of the same name as one from another source, the field will select ours to run
field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "ViewZoom200";
field.DisplayText = "Run " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  ViewZoom200 Run ViewZoom200", field.GetFieldCode());

// Save the document as a macro-enabled document type
doc.Save(ArtifactsDir + "Field.MacroButton.docm");

See Also

Document Class | Aspose.Words Namespace | RemoveMacros


HasRevisions Property

Aspose.Words

Document.HasRevisions Property

Returns true if the document has any tracked changes.

[Visual Basic]
Public ReadOnly Property HasRevisions As Boolean
[C#]
public bool HasRevisions {get;}

Remarks

This property is a shortcut for comparing Count to zero.

Example

Shows how to check if a document has revisions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A blank document comes with no revisions
Assert.IsFalse(doc.HasRevisions);

builder.Writeln("This does not count as a revision.");

// Just adding text does not count as a revision
Assert.IsFalse(doc.HasRevisions);

// For our edits to count as revisions, we need to declare an author and start tracking them
doc.StartTrackRevisions("John Doe", DateTime.Now);

builder.Writeln("This is a revision.");

// The above text is now tracked as a revision and will show up accordingly in our output file
Assert.IsTrue(doc.HasRevisions);
Assert.AreEqual("John Doe", doc.Revisions[0].Author);

// Document.TrackRevisions corresponds to Microsoft Word tracking changes, not the ones we programmatically make here
Assert.IsFalse(doc.TrackRevisions);

// This takes us back to not counting changes as revisions
doc.StopTrackRevisions();

builder.Writeln("This does not count as a revision.");

doc.Save(ArtifactsDir + "Revisions.docx");

// We can get rid of all the changes we made that counted as revisions
doc.Revisions.RejectAll();
Assert.IsFalse(doc.HasRevisions);

// The second line that our builder wrote will not appear at all in the output
doc.Save(ArtifactsDir + "RevisionsRejected.docx");

// Alternatively, we can track revisions from Microsoft Word like this
// This is the same as turning on "Track Changes" in Word
doc.TrackRevisions = true;

doc.Save(ArtifactsDir + "RevisionsTrackedFromMSWord.docx");

See Also

Document Class | Aspose.Words Namespace


HyphenationOptions Property

Aspose.Words

Document.HyphenationOptions Property

Provides access to document hyphenation options.

[Visual Basic]
Public ReadOnly Property HyphenationOptions As HyphenationOptions
[C#]
public HyphenationOptions HyphenationOptions {get;}

Example

Shows how to configure document hyphenation options.

[C#]

Document doc = new Document();
// Create new Run with text that we want to move to the next line using the hyphen
Run run = new Run(doc)
{
    Text =
        "poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj"
};

Paragraph para = doc.FirstSection.Body.Paragraphs[0];
para.AppendChild(run);

doc.HyphenationOptions.AutoHyphenation = true;
doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
doc.HyphenationOptions.HyphenationZone = 720; // 0.5 inch
doc.HyphenationOptions.HyphenateCaps = true;

doc.Save(ArtifactsDir + "HyphenationOptions.docx");

See Also

Document Class | Aspose.Words Namespace


LastSection Property

Aspose.Words

Document.LastSection Property

Gets the last section in the document.

[Visual Basic]
Public ReadOnly Property LastSection As Section
[C#]
public Section LastSection {get;}

Remarks

Returns null if there are no sections.

Example

Shows how to edit the last section of a document.

[C#]

// Open the template document, containing obsolete copyright information in the footer
Document doc = new Document(MyDir + "HeaderFooter.ReplaceText.doc");

// We have a document with 2 sections, this way FirstSection and LastSection are not the same
Assert.AreEqual(2, doc.Sections.Count);

string newCopyrightInformation = string.Format("Copyright (C) {0} by Aspose Pty Ltd.", DateTime.Now.Year);
FindReplaceOptions findReplaceOptions =
    new FindReplaceOptions { MatchCase = false, FindWholeWordsOnly = false };

// Access the first and the last sections
HeaderFooter firstSectionFooter = doc.FirstSection.HeadersFooters[HeaderFooterType.FooterPrimary];
firstSectionFooter.Range.Replace("(C) 2006 Aspose Pty Ltd.", newCopyrightInformation, findReplaceOptions);

HeaderFooter lastSectionFooter = doc.LastSection.HeadersFooters[HeaderFooterType.FooterPrimary];
lastSectionFooter.Range.Replace("(C) 2006 Aspose Pty Ltd.", newCopyrightInformation, findReplaceOptions);

// Sections are also accessible via an array
Assert.AreEqual(doc.FirstSection, doc.Sections[0]);
Assert.AreEqual(doc.LastSection, doc.Sections[1]);

doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.doc");

See Also

Document Class | Aspose.Words Namespace


LayoutOptions Property

Aspose.Words

Document.LayoutOptions Property

Gets a LayoutOptions object that represents options to control the layout process of this document.

[Visual Basic]
Public ReadOnly Property LayoutOptions As LayoutOptions
[C#]
public LayoutOptions LayoutOptions {get;}

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

See Also

Document Class | Aspose.Words Namespace


MailMerge Property

Aspose.Words

Document.MailMerge Property

Returns a MailMerge object that represents the mail merge functionality for the document.

[Visual Basic]
Public ReadOnly Property MailMerge As MailMerge
[C#]
public MailMerge MailMerge {get;}

Example

Executes mail merge from an ADO.NET DataTable.

[C#]

Document doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
DataTable table = new DataTable("Test");
table.Columns.Add("CustomerName");
table.Columns.Add("Address");
table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.MailMerge.Execute(table);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.doc");

// Open a fresh copy of our document to perform another mail merge.
doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// We can also source values for a mail merge from a single row in the table
doc.MailMerge.Execute(table.Rows[1]);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.doc");

See Also

Document Class | Aspose.Words Namespace


MailMergeSettings Property

Aspose.Words

Document.MailMergeSettings Property

Gets or sets the object that contains all of the mail merge information for a document.

[Visual Basic]
Public Property MailMergeSettings As MailMergeSettings
[C#]
public MailMergeSettings MailMergeSettings {get; set;}

Remarks

You can use this object to specify a mail merge data source for a document and this information (along with the available data fields) will appear in Microsoft Word when the user opens this document. Or you can use this object to query mail merge settings that the user has specified in Microsoft Word for this document.

This object is never null.

Example

Shows how to execute a mail merge with MailMergeSettings.

[C#]

// We'll create a simple document that will act as a destination for mail merge data
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Dear ");
builder.InsertField("MERGEFIELD FirstName", "<FirstName>");
builder.Write(" ");
builder.InsertField("MERGEFIELD LastName", "<LastName>");
builder.Writeln(": ");
builder.InsertField("MERGEFIELD Message", "<Message>");

// Also we'll need a data source, in this case it will be an ASCII text file
// We can use any character we want as a delimiter, in this case we'll choose '|'
// The delimiter character is selected in the ODSO settings of mail merge settings
string[] lines = { "FirstName|LastName|Message",
    "John|Doe|Hello! This message was created with Aspose Words mail merge." };
File.WriteAllLines(ArtifactsDir + "Document.Lines.txt", lines);

// Set the data source, query and other things
MailMergeSettings mailMergeSettings = doc.MailMergeSettings;
mailMergeSettings.MainDocumentType = MailMergeMainDocumentType.MailingLabels;
mailMergeSettings.DataType = MailMergeDataType.Native;
mailMergeSettings.DataSource = ArtifactsDir + "Document.Lines.txt";
mailMergeSettings.Query = "SELECT * FROM " + doc.MailMergeSettings.DataSource;
mailMergeSettings.LinkToQuery = true;
mailMergeSettings.ViewMergedData = true;

// Office Data Source Object settings
Odso odso = mailMergeSettings.Odso;
odso.DataSourceType = OdsoDataSourceType.Text;
odso.ColumnDelimiter = '|';
odso.DataSource = ArtifactsDir + "Document.Lines.txt";
odso.FirstRowContainsColumnNames = true;

// The mail merge will be performed when this document is opened
doc.Save(ArtifactsDir + "Document.MailMergeSettings.docx");

See Also

Document Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Document.NodeType Property

Returns NodeType.Document.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Document Class | Aspose.Words Namespace


OriginalFileName Property

Aspose.Words

Document.OriginalFileName Property

Gets the original file name of the document.

[Visual Basic]
Public ReadOnly Property OriginalFileName As String
[C#]
public string OriginalFileName {get;}

Remarks

Returns null if the document was loaded from a stream or created blank.

Example

Shows how to retrieve the details of the path, filename and LoadFormat of a document from when the document was first loaded into memory.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// This property will return the full path and file name where the document was loaded from.
String originalFilePath = doc.OriginalFileName;
// Let's get just the file name from the full path.
String originalFileName = Path.GetFileName(originalFilePath);

// This is the original LoadFormat of the document.
LoadFormat loadFormat = doc.OriginalLoadFormat;
Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.
[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

Document Class | Aspose.Words Namespace


OriginalLoadFormat Property

Aspose.Words

Document.OriginalLoadFormat Property

Gets the format of the original document that was loaded into this object.

[Visual Basic]
Public ReadOnly Property OriginalLoadFormat As LoadFormat
[C#]
public LoadFormat OriginalLoadFormat {get;}

Remarks

If you created a new blank document, returns the Doc value.

Example

Shows how to retrieve the details of the path, filename and LoadFormat of a document from when the document was first loaded into memory.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// This property will return the full path and file name where the document was loaded from.
String originalFilePath = doc.OriginalFileName;
// Let's get just the file name from the full path.
String originalFileName = Path.GetFileName(originalFilePath);

// This is the original LoadFormat of the document.
LoadFormat loadFormat = doc.OriginalLoadFormat;

See Also

Document Class | Aspose.Words Namespace


PackageCustomParts Property

Aspose.Words

Document.PackageCustomParts Property

Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using "unknown relationships".

[Visual Basic]
Public Property PackageCustomParts As CustomPartCollection
[C#]
public CustomPartCollection PackageCustomParts {get; set;}

Remarks

Do not confuse these custom parts with Custom XML Data. If you need to access Custom XML parts, use the CustomXmlParts property.

This collection contains OOXML parts whose parent is the OOXML package and they targets are of an "unknown relationship". For more information see CustomPart.

Aspose.Words loads and saves custom parts into OOXML documents only.

This property cannot be null.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

Document Class | Aspose.Words Namespace | CustomPart


PageCount Property

Aspose.Words

Document.PageCount Property

Gets the number of pages in the document as calculated by the most recent page layout operation.

[Visual Basic]
Public ReadOnly Property PageCount As Integer
[C#]
public int PageCount {get;}

Remarks

Example

Shows how to invoke page layout and retrieve the number of pages in the document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// This invokes page layout which builds the document in memory so note that with large documents this
// property can take time. After invoking this property, any rendering operation e.g rendering to PDF or image
// will be instantaneous.
int pageCount = doc.PageCount;

See Also

Document Class | Aspose.Words Namespace | UpdatePageLayout


ProtectionType Property

Aspose.Words

Document.ProtectionType Property

Gets the currently active document protection type.

[Visual Basic]
Public ReadOnly Property ProtectionType As ProtectionType
[C#]
public ProtectionType ProtectionType {get;}

Remarks

This property allows to retrieve the currently set document protection type. To change the document protection type use the Protect and Unprotect methods.

When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

Note that document protection is different from write protection. Write protection is specified using the WriteProtection

Example

Shows how to get protection type currently set in the document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
ProtectionType protectionType = doc.ProtectionType;

See Also

Document Class | Aspose.Words Namespace | Protect | Unprotect | WriteProtection


RemovePersonalInformation Property

Aspose.Words

Document.RemovePersonalInformation Property

Gets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.

[Visual Basic]
Public Property RemovePersonalInformation As Boolean
[C#]
public bool RemovePersonalInformation {get; set;}

Example

Shows how to get or set a flag to remove all user information upon saving the MS Word document.

[C#]

Document doc = new Document(MyDir + "Document.docx")
{
    // If flag sets to 'true' that MS Word will remove all user information from comments, revisions and
    // document properties upon saving the document. In MS Word 2013 and 2016 you can see this using
    // File -> Options -> Trust Center -> Trust Center Settings -> Privacy Options -> then the
    // checkbox "Remove personal information from file properties on save".
    RemovePersonalInformation = true
};

doc.Save(ArtifactsDir + "Document.RemovePersonalInformation.docx");

See Also

Document Class | Aspose.Words Namespace


Revisions Property

Aspose.Words

Document.Revisions Property

Gets a collection of revisions (tracked changes) that exist in this document.

[Visual Basic]
Public ReadOnly Property Revisions As RevisionCollection
[C#]
public RevisionCollection Revisions {get;}

Remarks

The returned collection is a "live" collection, which means if you remove parts of a document that contain revisions, the deleted revisions will automatically disappear from this collection.

Example

Shows how to check if a document has revisions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A blank document comes with no revisions
Assert.IsFalse(doc.HasRevisions);

builder.Writeln("This does not count as a revision.");

// Just adding text does not count as a revision
Assert.IsFalse(doc.HasRevisions);

// For our edits to count as revisions, we need to declare an author and start tracking them
doc.StartTrackRevisions("John Doe", DateTime.Now);

builder.Writeln("This is a revision.");

// The above text is now tracked as a revision and will show up accordingly in our output file
Assert.IsTrue(doc.HasRevisions);
Assert.AreEqual("John Doe", doc.Revisions[0].Author);

// Document.TrackRevisions corresponds to Microsoft Word tracking changes, not the ones we programmatically make here
Assert.IsFalse(doc.TrackRevisions);

// This takes us back to not counting changes as revisions
doc.StopTrackRevisions();

builder.Writeln("This does not count as a revision.");

doc.Save(ArtifactsDir + "Revisions.docx");

// We can get rid of all the changes we made that counted as revisions
doc.Revisions.RejectAll();
Assert.IsFalse(doc.HasRevisions);

// The second line that our builder wrote will not appear at all in the output
doc.Save(ArtifactsDir + "RevisionsRejected.docx");

// Alternatively, we can track revisions from Microsoft Word like this
// This is the same as turning on "Track Changes" in Word
doc.TrackRevisions = true;

doc.Save(ArtifactsDir + "RevisionsTrackedFromMSWord.docx");

See Also

Document Class | Aspose.Words Namespace


Sections Property

Aspose.Words

Document.Sections Property

Returns a collection that represents all sections in the document.

[Visual Basic]
Public ReadOnly Property Sections As SectionCollection
[C#]
public SectionCollection Sections {get;}

Example

Specifies how the section starts, from a new page, on the same page or other.

[C#]

Document doc = new Document();
doc.Sections[0].PageSetup.SectionStart = Aspose.Words.SectionStart.Continuous;
Shows how to add/remove sections in a document.
[C#]

// Open the document.
Document doc = new Document(MyDir + "Section.AddRemove.doc");

// This shows what is in the document originally. The document has two sections.
Console.WriteLine(doc.GetText());

// Delete the first section from the document
doc.Sections.RemoveAt(0);

// Duplicate the last section and append the copy to the end of the document.
int lastSectionIdx = doc.Sections.Count - 1;
Section newSection = doc.Sections[lastSectionIdx].Clone();
doc.Sections.Add(newSection);

// Check what the document contains after we changed it.
Console.WriteLine(doc.GetText());

See Also

Document Class | Aspose.Words Namespace


ShadeFormData Property

Aspose.Words

Document.ShadeFormData Property

Specifies whether to turn on the gray shading on form fields.

[Visual Basic]
Public Property ShadeFormData As Boolean
[C#]
public bool ShadeFormData {get; set;}

Example

Shows how to apply gray shading to bookmarks.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// By default, bookmarked text is highlighted gray
Assert.IsTrue(doc.ShadeFormData);

builder.Write("Text before bookmark. ");

builder.InsertTextInput("My bookmark", TextFormFieldType.Regular, "",
    "If gray shading is turned on, this is the text that will have a gray background.", 0);

// Our bookmarked text will appear gray here
doc.Save(ArtifactsDir + "Document.ShadeFormDataTrue.docx");

// In this file, shading will be turned off and the bookmarked text will blend in with the other text
doc.ShadeFormData = false;
doc.Save(ArtifactsDir + "Document.ShadeFormDataFalse.docx");

See Also

Document Class | Aspose.Words Namespace


Theme Property

Aspose.Words

Document.Theme Property

Gets the Theme object for this document.

[Visual Basic]
Public ReadOnly Property Theme As Theme
[C#]
public Theme Theme {get;}

Example

Shows what we can do with the Themes property of Document.

[C#]

Document doc = new Document();

// When creating a blank document, Aspose Words creates a default theme object
Theme theme = doc.Theme;

// These color properties correspond to the 10 color columns that you see
// in the "Theme colors" section in the color selector menu when changing font or shading color
// We can view and edit the leading color for each column, and the five different tints that
// make up the rest of the column will be derived automatically from each leading color
// Aspose Words sets the defaults to what they are in the Microsoft Word default theme
Assert.AreEqual(Color.FromArgb(255, 255, 255, 255), theme.Colors.Light1);
Assert.AreEqual(Color.FromArgb(255, 0, 0, 0), theme.Colors.Dark1);
Assert.AreEqual(Color.FromArgb(255, 238, 236, 225), theme.Colors.Light2);
Assert.AreEqual(Color.FromArgb(255, 31, 73, 125), theme.Colors.Dark2);
Assert.AreEqual(Color.FromArgb(255, 79, 129, 189), theme.Colors.Accent1);
Assert.AreEqual(Color.FromArgb(255, 192, 80, 77), theme.Colors.Accent2);
Assert.AreEqual(Color.FromArgb(255, 155, 187, 89), theme.Colors.Accent3);
Assert.AreEqual(Color.FromArgb(255, 128, 100, 162), theme.Colors.Accent4);
Assert.AreEqual(Color.FromArgb(255, 75, 172, 198), theme.Colors.Accent5);
Assert.AreEqual(Color.FromArgb(255, 247, 150, 70), theme.Colors.Accent6);

// Hyperlink colors
Assert.AreEqual(Color.FromArgb(255, 0, 0, 255), theme.Colors.Hyperlink);
Assert.AreEqual(Color.FromArgb(255, 128, 0, 128), theme.Colors.FollowedHyperlink);

// These appear at the very top of the font selector in the "Theme Fonts" section
Assert.AreEqual("Cambria", theme.MajorFonts.Latin);
Assert.AreEqual("Calibri", theme.MinorFonts.Latin);

// Change some values to make a custom theme
theme.MinorFonts.Latin = "Bodoni MT";
theme.MajorFonts.Latin = "Tahoma";
theme.Colors.Accent1 = Color.Cyan;
theme.Colors.Accent2 = Color.Yellow;

// Save the document to use our theme
doc.Save(ArtifactsDir + "Document.Theme.docx");

See Also

Document Class | Aspose.Words Namespace


TrackRevisions Property

Aspose.Words

Document.TrackRevisions Property

True if changes are tracked when this document is edited in Microsoft Word.

[Visual Basic]
Public Property TrackRevisions As Boolean
[C#]
public bool TrackRevisions {get; set;}

Remarks

Setting this option only instructs Microsoft Word whether the track changes is turned on or off. This property has no effect on changes to the document that you make programmatically via Aspose.Words.

If you want to automatically track changes as they are made programmatically by Aspose.Words to this document use the StartTrackRevisions method.

Example

Shows how to check if a document has revisions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// A blank document comes with no revisions
Assert.IsFalse(doc.HasRevisions);

builder.Writeln("This does not count as a revision.");

// Just adding text does not count as a revision
Assert.IsFalse(doc.HasRevisions);

// For our edits to count as revisions, we need to declare an author and start tracking them
doc.StartTrackRevisions("John Doe", DateTime.Now);

builder.Writeln("This is a revision.");

// The above text is now tracked as a revision and will show up accordingly in our output file
Assert.IsTrue(doc.HasRevisions);
Assert.AreEqual("John Doe", doc.Revisions[0].Author);

// Document.TrackRevisions corresponds to Microsoft Word tracking changes, not the ones we programmatically make here
Assert.IsFalse(doc.TrackRevisions);

// This takes us back to not counting changes as revisions
doc.StopTrackRevisions();

builder.Writeln("This does not count as a revision.");

doc.Save(ArtifactsDir + "Revisions.docx");

// We can get rid of all the changes we made that counted as revisions
doc.Revisions.RejectAll();
Assert.IsFalse(doc.HasRevisions);

// The second line that our builder wrote will not appear at all in the output
doc.Save(ArtifactsDir + "RevisionsRejected.docx");

// Alternatively, we can track revisions from Microsoft Word like this
// This is the same as turning on "Track Changes" in Word
doc.TrackRevisions = true;

doc.Save(ArtifactsDir + "RevisionsTrackedFromMSWord.docx");

See Also

Document Class | Aspose.Words Namespace


Variables Property

Aspose.Words

Document.Variables Property

Returns the collection of variables added to a document or template.

[Visual Basic]
Public ReadOnly Property Variables As VariableCollection
[C#]
public VariableCollection Variables {get;}

Example

Shows how to enumerate over document variables.

[C#]

Document doc = new Document(MyDir + "Document.doc");

foreach (KeyValuePair<string, string> entry in doc.Variables)
{
    String name = entry.Key;
    String value = entry.Value;

    // Do something useful.
    Console.WriteLine("Name: {0}, Value: {1}", name, value);
}

See Also

Document Class | Aspose.Words Namespace


VbaProject Property

Aspose.Words

Document.VbaProject Property

Gets VbaProject containing in the document.

[Visual Basic]
Public ReadOnly Property VbaProject As VbaProject
[C#]
public VbaProject VbaProject {get;}

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

See Also

Document Class | Aspose.Words Namespace


VersionsCount Property

Aspose.Words

Document.VersionsCount Property

Gets the number of document versions that was stored in the DOC document.

[Visual Basic]
Public ReadOnly Property VersionsCount As Integer
[C#]
public int VersionsCount {get;}

Remarks

Versions in Microsoft Word are accessed via the File/Versions menu. Microsoft Word supports versions only for DOC files.

This property allows to detect if there were document versions stored in this document before it was opened in Aspose.Words. Aspose.Words provides no other support for document versions. If you save this document using Aspose.Words, the document will be saved without versions.

Example

Shows how to count how many previous versions a document has.

[C#]

Document doc = new Document();

// No versions are in the document by default
// We also can't add any since they are not supported
Assert.AreEqual(0, doc.VersionsCount);

// Let's open a document with versions
doc = new Document(MyDir + "Versions.doc");

// We can use this property to see how many there are
Assert.AreEqual(4, doc.VersionsCount);

doc.Save(ArtifactsDir + "Document.Versions.docx");
doc = new Document(ArtifactsDir + "Document.Versions.docx");

// If we save and open the document, the versions are lost
Assert.AreEqual(0, doc.VersionsCount);

See Also

Document Class | Aspose.Words Namespace


ViewOptions Property

Aspose.Words

Document.ViewOptions Property

Provides options to control how the document is displayed in Microsoft Word.

[Visual Basic]
Public ReadOnly Property ViewOptions As ViewOptions
[C#]
public ViewOptions ViewOptions {get;}

Example

The following code shows how to make sure the document is displayed at 50% zoom when opened in Microsoft Word.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
doc.Save(ArtifactsDir + "Document.SetZoom.doc");

See Also

Document Class | Aspose.Words Namespace


WriteProtection Property

Aspose.Words

Document.WriteProtection Property

Provides access to the document write protection options.

[Visual Basic]
Public ReadOnly Property WriteProtection As WriteProtection
[C#]
public WriteProtection WriteProtection {get;}

Example

Shows how to protect a document with a password.

[C#]

Document doc = new Document();
Assert.IsFalse(doc.WriteProtection.IsWriteProtected);
Assert.IsFalse(doc.WriteProtection.ReadOnlyRecommended);

// Enter a password that's 15 or less characters long
doc.WriteProtection.SetPassword("docpassword123");
Assert.IsTrue(doc.WriteProtection.IsWriteProtected);

Assert.IsFalse(doc.WriteProtection.ValidatePassword("wrongpassword"));

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("We can still edit the document at this stage.");

// Save the document
// Without the password, we can only read this document in Microsoft Word
// With the password, we can read and write
doc.Save(ArtifactsDir + "Document.WriteProtection.docx");

// Re-open our document
Document docProtected = new Document(ArtifactsDir + "Document.WriteProtection.docx");
DocumentBuilder docProtectedBuilder = new DocumentBuilder(docProtected);
docProtectedBuilder.MoveToDocumentEnd();

// We can programmatically edit this document without using our password
Assert.IsTrue(docProtected.WriteProtection.IsWriteProtected);
docProtectedBuilder.Writeln("Writing text in a protected document.");

// We will still need the password if we want to open this one with Word
docProtected.Save(ArtifactsDir + "Document.WriteProtectionEditedAfter.docx");

See Also

Document Class | Aspose.Words Namespace


Document Methods

The methods of the Document class are listed below. For a complete list of Document class members, see the Document Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AcceptAllRevisions | Accepts all tracked changes in the document.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendDocument | Overloaded. Appends the specified document to the end of this document.
Cleanup | Overloaded. Cleans unused styles and lists from the document.
Clone | Overloaded. Performs a deep copy of the Document.
Clone (inherited from Node) | Overloaded.
Compare | Overloaded. Compares this document with another document producing changes as number of edit and format revisions Revision.
CopyStylesFromTemplate | Overloaded. Copies styles from the specified template to a document.
EnsureMinimum | If the document contains no sections, creates one section with one paragraph.
ExpandTableStylesToDirectFormatting | Converts formatting specified in table styles into direct formatting on tables in the document.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetPageInfo | Gets the page size, orientation and other information about a page that might be useful for printing or rendering.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
ImportNode (inherited from DocumentBase) | Overloaded. Imports a node from another document to the current document.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
JoinRunsWithSameFormatting | Joins runs with same formatting in all paragraphs of the document.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
NormalizeFieldTypes | Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Print | Overloaded. Prints the document without bringing up any user interface forms.
Protect | Overloaded. Protects the document from changes.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveExternalSchemaReferences | Removes external XML schema references from this document.
RemoveMacros | Removes all macros (the VBA project) as well as toolbars and command customizations from the document.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
RenderToScale | Renders a document page into a Graphics object to a specified scale.
RenderToSize |
Save | Overloaded. Saves the document.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
StartTrackRevisions | Overloaded. Starts automatically marking all further changes you make to the document programmatically as revision changes.
StopTrackRevisions | Stops automatic marking of document changes as revisions.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.
UnlinkFields | Unlinks fields in the whole document.
Unprotect | Overloaded. Removes protection from the document.
UpdateFields | Updates the values of fields in the whole document.
UpdateListLabels | Updates list labels for all list items in the document.
UpdatePageLayout | Rebuilds the page layout of the document.
UpdateTableLayout | Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document.
UpdateThumbnail | Overloaded. Updates Thumbnail of the document according to the specified options.
UpdateWordCount | Overloaded. Updates word count properties of the document.

See Also

Document Class | Aspose.Words Namespace


Document.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitDocumentStart, then calls Accept for all child nodes of the document and calls DocumentVisitor.VisitDocumentEnd at the end.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

Document Class | Aspose.Words Namespace


Document.AcceptAllRevisions Method

Accepts all tracked changes in the document.

[Visual Basic]
Public Sub AcceptAllRevisions()
[C#]
public void AcceptAllRevisions();

Remarks

This method is a shortcut for AcceptAll.

Example

Shows how to accept all tracking changes in the document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Start tracking and make some revisions.
doc.StartTrackRevisions("Author");
doc.FirstSection.Body.AppendParagraph("Hello world!");

// Revisions will now show up as normal text in the output document.
doc.AcceptAllRevisions();
doc.Save(ArtifactsDir + "Document.AcceptedRevisions.doc");

See Also

Document Class | Aspose.Words Namespace


AppendDocument Method

Aspose.Words

Document.AppendDocument Method

Appends the specified document to the end of this document.

Overload List

Appends the specified document to the end of this document.

public void AppendDocument(Document,ImportFormatMode);

Appends the specified document to the end of this document.

public void AppendDocument(Document,ImportFormatMode,ImportFormatOptions);

See Also

Document Class | Aspose.Words Namespace


Document.AppendDocument Method (Document, ImportFormatMode)

Appends the specified document to the end of this document.

[Visual Basic]
Overloads Public Sub AppendDocument( _
ByVal srcDoc As Document, _
ByVal importFormatMode As ImportFormatMode _
)
[C#]
public void AppendDocument(
Document srcDoc,
ImportFormatMode importFormatMode
);

Parameters

srcDoc
The document to append.
importFormatMode
Specifies how to merge style formatting that clashes.

Example

Shows how to append a document to the end of another document.

[C#]

// The document that the content will be appended to.
Document dstDoc = new Document(MyDir + "Document.doc");

// The document to append.
Document srcDoc = new Document(MyDir + "DocumentBuilder.doc");

// Append the source document to the destination document.
// Pass format mode to retain the original formatting of the source document when importing it.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);

// Save the document.
dstDoc.Save(ArtifactsDir + "Document.AppendDocument.doc");
Shows how to use the AppendDocument method to combine all the documents in a folder to the end of a template document.
[C#]

// Lets start with a simple template and append all the documents in a folder to this document.
Document baseDoc = new Document();

// Add some content to the template.
DocumentBuilder builder = new DocumentBuilder(baseDoc);
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Template Document");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
builder.Writeln("Some content here");

// Gather the files which will be appended to our template document.
// In this case we add the optional parameter to include the search only for files with the ".doc" extension.
ArrayList files = new ArrayList(Directory.GetFiles(MyDir, "*.doc")
    .Where(file => file.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase)).ToArray());
// The list of files may come in any order, let's sort the files by name so the documents are enumerated alphabetically.
files.Sort();

// Iterate through every file in the directory and append each one to the end of the template document.
foreach (String fileName in files)
{
    // We have some encrypted test documents in our directory, Aspose.Words can open encrypted documents
    // but only with the correct password. Let's just skip them here for simplicity.
    FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
    if (info.IsEncrypted)
        continue;

    Document subDoc = new Document(fileName);
    baseDoc.AppendDocument(subDoc, ImportFormatMode.UseDestinationStyles);
}

// Save the combined document to disk.
baseDoc.Save(path);

See Also

Document Class | Aspose.Words Namespace | Document.AppendDocument Overload List


Document.AppendDocument Method (Document, ImportFormatMode, ImportFormatOptions)

Appends the specified document to the end of this document.

[Visual Basic]
Overloads Public Sub AppendDocument( _
ByVal srcDoc As Document, _
ByVal importFormatMode As ImportFormatMode, _
ByVal importFormatOptions As ImportFormatOptions _
)
[C#]
public void AppendDocument(
Document srcDoc,
ImportFormatMode importFormatMode,
ImportFormatOptions importFormatOptions
);

Parameters

srcDoc
The document to append.
importFormatMode
Specifies how to merge style formatting that clashes.
importFormatOptions
Allows to specify options that affect formatting of a result document.

Example

Shows how to resolve styles behavior while append document.

[C#]

Document srcDoc = new Document(MyDir + "DocumentBuilder.ResolveStyleBehaviorWhileAppendDocument.Source.docx");
Document dstDoc = new Document(MyDir + "DocumentBuilder.ResolveStyleBehaviorWhileAppendDocument.Destination.docx");

ImportFormatOptions options = new ImportFormatOptions();
// Specify that if numbering clashes in source and destination documents
// then a numbering from the source document will be used.
options.KeepSourceNumbering = true;
dstDoc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles, options);
dstDoc.UpdateListLabels();

See Also

Document Class | Aspose.Words Namespace | Document.AppendDocument Overload List


Cleanup Method

Aspose.Words

Document.Cleanup Method

Cleans unused styles and lists from the document.

Overload List

Cleans unused styles and lists from the document.

public void Cleanup();

Cleans unused styles and lists from the document depending on given CleanupOptions.

public void Cleanup(CleanupOptions);

See Also

Document Class | Aspose.Words Namespace


Document.Cleanup Method ()

Cleans unused styles and lists from the document.

[Visual Basic]
Overloads Public Sub Cleanup()
[C#]
public void Cleanup();

Example

Shows how to remove unused styles and lists from a document.

[C#]

// Create a new document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Brand new documents have 4 styles and 0 lists by default
Assert.AreEqual(4, doc.Styles.Count);
Assert.AreEqual(0, doc.Lists.Count);

// We will add one style and one list and mark them as "used" by applying them to the builder
builder.ParagraphFormat.Style = doc.Styles.Add(StyleType.Paragraph, "My Used Style");
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// These items were added to their respective collections
Assert.AreEqual(5, doc.Styles.Count);
Assert.AreEqual(1, doc.Lists.Count);

// doc.Cleanup() removes all unused styles and lists
doc.Cleanup();

// It currently has no effect because the 2 items we added plus the original 4 styles are all used
Assert.AreEqual(5, doc.Styles.Count);
Assert.AreEqual(1, doc.Lists.Count);

// These two items will be added but will not associated with any part of the document
doc.Styles.Add(StyleType.Paragraph, "My Unused Style");
doc.Lists.Add(ListTemplate.NumberArabicDot);

// They also get stored in the document and are ready to be used
Assert.AreEqual(6, doc.Styles.Count);
Assert.AreEqual(2, doc.Lists.Count);

doc.Cleanup();

// Since we didn't apply them anywhere, the two unused items are removed by doc.Cleanup()
Assert.AreEqual(5, doc.Styles.Count);
Assert.AreEqual(1, doc.Lists.Count);

See Also

Document Class | Aspose.Words Namespace | Document.Cleanup Overload List


Document.Cleanup Method (CleanupOptions)

Cleans unused styles and lists from the document depending on given CleanupOptions.

[Visual Basic]
Overloads Public Sub Cleanup( _
ByVal options As CleanupOptions _
)
[C#]
public void Cleanup(
CleanupOptions options
);

Example

Shows how to remove all unused styles and lists from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

CleanupOptions cleanupOptions = new CleanupOptions
{
    UnusedLists = true,
    UnusedStyles = true
};

doc.Cleanup(cleanupOptions);

See Also

Document Class | Aspose.Words Namespace | Document.Cleanup Overload List


Clone Method

Aspose.Words

Document.Clone Method

Performs a deep copy of the Document.

Overload List

Performs a deep copy of the Document.

public Document Clone();

Inherited from Node.

public Node Clone(bool);

See Also

Document Class | Aspose.Words Namespace


Document.Clone Method ()

Performs a deep copy of the Document.

[Visual Basic]
Overloads Public Function Clone() As Document
[C#]
public Document Clone();

Return Value

The cloned document.

Example

Shows how to deep clone a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Document clone = doc.Clone();

See Also

Document Class | Aspose.Words Namespace | Document.Clone Overload List


Compare Method

Aspose.Words

Document.Compare Method

Compares this document with another document producing changes as number of edit and format revisions Revision.

Overload List

Compares this document with another document producing changes as number of edit and format revisions Revision.

public void Compare(Document,string,DateTime);

Compares this document with another document producing changes as a number of edit and format revisions Revision. Allows to specify comparison options using CompareOptions.

public void Compare(Document,string,DateTime,CompareOptions);

See Also

Document Class | Aspose.Words Namespace


Document.Compare Method (Document, String, DateTime)

Compares this document with another document producing changes as number of edit and format revisions Revision.

[Visual Basic]
Overloads Public Sub Compare( _
ByVal document As Document, _
ByVal author As String, _
ByVal dateTime As Date _
)
[C#]
public void Compare(
Document document,
string author,
DateTime dateTime
);

Parameters

document
Document to compare.
author
Initials of the author to use for revisions.
dateTime
The date and time to use for revisions.

Remarks

The following document nodes are not compared at the moment:

  • StructuredDocumentTag
  • Item3
Note Documents must not have revisions before comparison.

Example

Shows how to apply the compare method to two documents and then use the results.

[C#]

Document doc1 = new Document(MyDir + "Document.Compare.1.doc");
Document doc2 = new Document(MyDir + "Document.Compare.2.doc");

// If either document has a revision, an exception will be thrown.
if (doc1.Revisions.Count == 0 && doc2.Revisions.Count == 0)
    doc1.Compare(doc2, "authorName", DateTime.Now);

// If doc1 and doc2 are different, doc1 now has some revisions after the comparison, which can now be viewed and processed.
foreach (Revision r in doc1.Revisions)
    Console.WriteLine(r.RevisionType);

// All the revisions in doc1 are differences between doc1 and doc2, so accepting them on doc1 transforms doc1 into doc2.
doc1.Revisions.AcceptAll();

// doc1, when saved, now resembles doc2.
doc1.Save(ArtifactsDir + "Document.Compare.doc");

See Also

Document Class | Aspose.Words Namespace | Document.Compare Overload List


Document.Compare Method (Document, String, DateTime, CompareOptions)

Compares this document with another document producing changes as a number of edit and format revisions Revision. Allows to specify comparison options using CompareOptions.

[Visual Basic]
Overloads Public Sub Compare( _
ByVal document As Document, _
ByVal author As String, _
ByVal dateTime As Date, _
ByVal options As CompareOptions _
)
[C#]
public void Compare(
Document document,
string author,
DateTime dateTime,
CompareOptions options
);

Example

Shows how to specify which document shall be used as a target during comparison

[C#]

Document doc1 = new Document(MyDir + "Document.CompareOptions.1.docx");
Document doc2 = new Document(MyDir + "Document.CompareOptions.2.docx");

// ComparisonTargetType with IgnoreFormatting setting determines which document has to be used as formatting source for ranges of equal text.
CompareOptions compareOptions = new CompareOptions
{
    IgnoreFormatting = true,
    IgnoreCaseChanges = false,
    IgnoreComments = false,
    IgnoreTables = false,
    IgnoreFields = false,
    IgnoreFootnotes = false,
    IgnoreTextboxes = false,
    IgnoreHeadersAndFooters = false,
    Target = ComparisonTargetType.New
};
doc1.Compare(doc2, "vderyushev", DateTime.Now, compareOptions);

doc1.Save(ArtifactsDir + "Document.CompareOptions.docx");

See Also

Document Class | Aspose.Words Namespace | Document.Compare Overload List


CopyStylesFromTemplate Method

Aspose.Words

Document.CopyStylesFromTemplate Method

Copies styles from the specified template to a document.

Overload List

Copies styles from the specified template to a document.

public void CopyStylesFromTemplate(Document);

Copies styles from the specified template to a document.

public void CopyStylesFromTemplate(string);

See Also

Document Class | Aspose.Words Namespace


Document.CopyStylesFromTemplate Method (Document)

Copies styles from the specified template to a document.

[Visual Basic]
Overloads Public Sub CopyStylesFromTemplate( _
ByVal template As Document _
)
[C#]
public void CopyStylesFromTemplate(
Document template
);

Remarks

When styles are copied from a template to a document, like-named styles in the document are redefined to match the style descriptions in the template. Unique styles from the template are copied to the document. Unique styles in the document remain intact.

Example

Shows how to copies styles from the template to a document via Document.

[C#]

Document template = new Document(MyDir + "Rendering.doc");

Document target = new Document(MyDir + "Document.docx");
target.CopyStylesFromTemplate(template);

target.Save(ArtifactsDir + "CopyStylesFromTemplateViaDocument.docx");

See Also

Document Class | Aspose.Words Namespace | Document.CopyStylesFromTemplate Overload List


Document.CopyStylesFromTemplate Method (String)

Copies styles from the specified template to a document.

[Visual Basic]
Overloads Public Sub CopyStylesFromTemplate( _
ByVal template As String _
)
[C#]
public void CopyStylesFromTemplate(
string template
);

Remarks

When styles are copied from a template to a document, like-named styles in the document are redefined to match the style descriptions in the template. Unique styles from the template are copied to the document. Unique styles in the document remain intact.

Example

Shows how to copies styles from the template to a document via string.

[C#]

string templatePath = MyDir + "Rendering.doc";

Document target = new Document(MyDir + "Document.docx");
target.CopyStylesFromTemplate(templatePath);

target.Save(ArtifactsDir + "CopyStylesFromTemplateViaString.docx");

See Also

Document Class | Aspose.Words Namespace | Document.CopyStylesFromTemplate Overload List


Document.EnsureMinimum Method

If the document contains no sections, creates one section with one paragraph.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Shows how to ensure the Document is valid (has the minimum nodes required to be valid).

[C#]

// Create a blank document then remove all nodes from it, the result will be a completely empty document.
Document doc = new Document();
doc.RemoveAllChildren();

// Ensure that the document is valid. Since the document has no nodes this method will create an empty section
// and add an empty paragraph to make it valid.
doc.EnsureMinimum();

See Also

Document Class | Aspose.Words Namespace


Document.ExpandTableStylesToDirectFormatting Method

Converts formatting specified in table styles into direct formatting on tables in the document.

[Visual Basic]
Public Sub ExpandTableStylesToDirectFormatting()
[C#]
public void ExpandTableStylesToDirectFormatting();

Remarks

This method exists because this version of Aspose.Words provides only limited support for table styles (see below). This method might be useful when you load a DOCX or WordprocessingML document that contains tables formatted with table styles and you need to query formatting of tables, cells, paragraphs or text.

This version of Aspose.Words provides limited support for table styles as follows:

  • Table styles defined in DOCX or WordprocessingML documents are preserved as table styles when saving the document as DOCX or WordprocessingML.
  • Table styles defined in DOCX or WordprocessingML documents are automatically converted to direct formatting on tables when saving the document into any other format, rendering or printing.
  • Table styles defined in DOC documents are preserved as table styles when saving the document as DOC only.

Example

Shows how to expand the formatting from styles onto the rows and cells of the table as direct formatting.

[C#]

Document doc = new Document(MyDir + "Table.TableStyle.docx");

// Get the first cell of the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Cell firstCell = table.FirstRow.FirstCell;

// First print the color of the cell shading. This should be empty as the current shading
// is stored in the table style.
double cellShadingBefore = table.FirstRow.RowFormat.Height;
Console.WriteLine("Cell shading before style expansion: " + cellShadingBefore);

// Expand table style formatting to direct formatting.
doc.ExpandTableStylesToDirectFormatting();

// Now print the cell shading after expanding table styles. A blue background pattern color
// should have been applied from the table style.
double cellShadingAfter = table.FirstRow.RowFormat.Height;
Console.WriteLine("Cell shading after style expansion: " + cellShadingAfter);

See Also

Document Class | Aspose.Words Namespace


Document.GetPageInfo Method

Gets the page size, orientation and other information about a page that might be useful for printing or rendering.

[Visual Basic]
Public Function GetPageInfo( _
ByVal pageIndex As Integer _
) As PageInfo
[C#]
public PageInfo GetPageInfo(
int pageIndex
);

Parameters

pageIndex
The 0-based page index.

Example

Renders a page of a Word document into a bitmap using a specified zoom factor.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            PageInfo pageInfo = doc.GetPageInfo(0);

            // Let's say we want the image at 50% zoom.
            const float myScale = 0.50f;

            // Let's say we want the image at this resolution.
            const float myResolution = 200.0f;

            Size pageSize = pageInfo.GetSizeInPixels(myScale, myResolution);
#if NETSTANDARD2_0 || __MOBILE__
            using (SKBitmap bitmap = new SKBitmap(pageSize.Width, pageSize.Height))
            {
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    // Scale to compensate for the larger bitmap
                    canvas.Scale(2);

                    // Fill the page background.
                    // If you need to set color without specific options, you can use "canvas.Clear(SKColors.White);"
                    SKPaint paint = new SKPaint
                    {
                        Color = SKColors.White,
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High
                    };

                    canvas.DrawPaint(paint);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, canvas, 0, 0, myScale);
                }

                using (SKFileWStream fs = new SKFileWStream(ArtifactsDir + "Rendering.RenderToScale.png"))
                {
                    bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100);
                }
            }
#else
            using (Bitmap img = new Bitmap(pageSize.Width, pageSize.Height))
            {
                img.SetResolution(myResolution, myResolution);

                using (Graphics gr = Graphics.FromImage(img))
                {
                    // You can apply various settings to the Graphics object.
                    gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    // Fill the page background.
                    gr.FillRectangle(Brushes.White, 0, 0, pageSize.Width, pageSize.Height);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, gr, 0, 0, myScale);
                }

                img.Save(ArtifactsDir + "Rendering.RenderToScale.png");
            }
#endif

See Also

Document Class | Aspose.Words Namespace


Document.JoinRunsWithSameFormatting Method

Joins runs with same formatting in all paragraphs of the document.

[Visual Basic]
Public Function JoinRunsWithSameFormatting() As Integer
[C#]
public int JoinRunsWithSameFormatting();

Return Value

Number of joins performed. When N adjacent runs are being joined they count as N - 1 joins.

Remarks

This is an optimization method. Some documents contain adjacent runs with same formatting. Usually this occurs if a document was intensively edited manually. You can reduce the document size and speed up further processing by joining these runs.

The operation checks every Paragraph node in the document for adjacent Run nodes having identical properties. It ignores unique identifiers used to track editing sessions of run creation and modification. First run in every joining sequence accumulates all text. Remaining runs are deleted from the document.

Example

Shows how to join runs in a document to reduce unneeded runs.

[C#]

// Let's load this particular document. It contains a lot of content that has been edited many times.
// This means the document will most likely contain a large number of runs with duplicate formatting.
Document doc = new Document(MyDir + "Rendering.doc");

// This is for illustration purposes only, remember how many run nodes we had in the original document.
int runsBefore = doc.GetChildNodes(NodeType.Run, true).Count;

// Join runs with the same formatting. This is useful to speed up processing and may also reduce redundant
// tags when exporting to HTML which will reduce the output file size.
int joinCount = doc.JoinRunsWithSameFormatting();

// This is for illustration purposes only, see how many runs are left after joining.
int runsAfter = doc.GetChildNodes(NodeType.Run, true).Count;

Console.WriteLine("Number of runs before:{0}, after:{1}, joined:{2}", runsBefore, runsAfter, joinCount);

// Save the optimized document to disk.
doc.Save(ArtifactsDir + "Document.JoinRunsWithSameFormatting.html");

See Also

Document Class | Aspose.Words Namespace


Document.NormalizeFieldTypes Method

Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.

[Visual Basic]
Public Sub NormalizeFieldTypes()
[C#]
public void NormalizeFieldTypes();

Remarks

Use this method after document changes that affect field types.

To change field type values in a specific part of the document use NormalizeFieldTypes.

Example

Shows how to get the keep a field's type up to date with its field code.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// We'll add a date field
Field field = builder.InsertField("DATE", null);

// The FieldDate field type corresponds to the "DATE" field so our field's type property gets automatically set to it
Assert.AreEqual(FieldType.FieldDate, field.Type);
Assert.AreEqual(1, doc.Range.Fields.Count);

// We can manually access the content of the field we added and change it
Run fieldText = (Run) doc.FirstSection.Body.FirstParagraph.GetChildNodes(NodeType.Run, true)[0];
Assert.AreEqual("DATE", fieldText.Text);
fieldText.Text = "PAGE";

// We changed the text to "PAGE" but the field's type property did not update accordingly
Assert.AreEqual("PAGE", fieldText.GetText());
Assert.AreNotEqual(FieldType.FieldPage, field.Type);

// The type of the field as well as its components is still "FieldDate"
Assert.AreEqual(FieldType.FieldDate, field.Type);
Assert.AreEqual(FieldType.FieldDate, field.Start.FieldType);
Assert.AreEqual(FieldType.FieldDate, field.Separator.FieldType);
Assert.AreEqual(FieldType.FieldDate, field.End.FieldType);

doc.NormalizeFieldTypes();

// After running this method the type changes everywhere to "FieldPage", which matches the text "PAGE"
Assert.AreEqual(FieldType.FieldPage, field.Type);
Assert.AreEqual(FieldType.FieldPage, field.Start.FieldType);
Assert.AreEqual(FieldType.FieldPage, field.Separator.FieldType);
Assert.AreEqual(FieldType.FieldPage, field.End.FieldType);

See Also

Document Class | Aspose.Words Namespace


Print Method

Aspose.Words

Document.Print Method

Prints the document without bringing up any user interface forms.

Overload List

Prints the whole document to the default printer.

public void Print();

Prints the document according to the specified printer settings, using the standard (no User Interface) print controller.

public void Print(PrinterSettings);

Prints the document according to the specified printer settings, using the standard (no User Interface) print controller and a document name.

public void Print(PrinterSettings,string);

Print the whole document to the specified printer, using the standard (no User Interface) print controller.

public void Print(string);

See Also

Document Class | Aspose.Words Namespace


Document.Print Method ()

Prints the whole document to the default printer.

[Visual Basic]
Overloads Public Sub Print()
[C#]
public void Print();

Example

Prints the whole document to the default printer.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Print();

See Also

Document Class | Aspose.Words Namespace | Document.Print Overload List


Document.Print Method (PrinterSettings)

Prints the document according to the specified printer settings, using the standard (no User Interface) print controller.

[Visual Basic]
Overloads Public Sub Print( _
ByVal printerSettings As PrinterSettings _
)
[C#]
public void Print(
PrinterSettings printerSettings
);

Parameters

printerSettings
The printer settings to use.

Remarks

The PrinterSettings object allows you to specify the printer to print on, the range of pages of to print and other options.

Example

Prints a range of pages.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PrinterSettings printerSettings = new PrinterSettings();
// Page numbers in the .NET printing framework are 1-based.
printerSettings.FromPage = 1;
printerSettings.ToPage = 3;

doc.Print(printerSettings);

See Also

Document Class | Aspose.Words Namespace | Document.Print Overload List


Document.Print Method (PrinterSettings, String)

Prints the document according to the specified printer settings, using the standard (no User Interface) print controller and a document name.

[Visual Basic]
Overloads Public Sub Print( _
ByVal printerSettings As PrinterSettings, _
ByVal documentName As String _
)
[C#]
public void Print(
PrinterSettings printerSettings,
string documentName
);

Parameters

printerSettings
The printer settings to use.
documentName
The document name to display (for example, in a print status dialog box or printer queue) while printing the document.

Remarks

The PrinterSettings object allows you to specify the printer to print on, the range of pages of to print and other options.

Example

Prints a range of pages along with the name of the document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PrinterSettings printerSettings = new PrinterSettings();
// Page numbers in the .NET printing framework are 1-based.
printerSettings.FromPage = 1;
printerSettings.ToPage = 3;

doc.Print(printerSettings, "My Print Document.doc");

See Also

Document Class | Aspose.Words Namespace | Document.Print Overload List


Document.Print Method (String)

Print the whole document to the specified printer, using the standard (no User Interface) print controller.

[Visual Basic]
Overloads Public Sub Print( _
ByVal printerName As String _
)
[C#]
public void Print(
string printerName
);

Parameters

printerName
The name of the printer.

Example

Prints the whole document to a specified printer.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Print("KONICA MINOLTA magicolor 2400W");

See Also

Document Class | Aspose.Words Namespace | Document.Print Overload List


Protect Method

Aspose.Words

Document.Protect Method

Protects the document from changes.

Overload List

Protects the document from changes without changing the existing password or assigns a random password.

public void Protect(ProtectionType);

Protects the document from changes and optionally sets a protection password.

public void Protect(ProtectionType,string);

See Also

Document Class | Aspose.Words Namespace


Document.Protect Method (ProtectionType)

Protects the document from changes without changing the existing password or assigns a random password.

[Visual Basic]
Overloads Public Sub Protect( _
ByVal type As ProtectionType _
)
[C#]
public void Protect(
ProtectionType type
);

Parameters

type
Specifies the protection type for the document.

Remarks

When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

When you protect a document, and the document already has a protection password, the existing protection password is not changed.

When you protect a document, and the document does not have a protection password, this method assigns a random password that makes it impossible to unprotect the document in Microsoft Word, but you still can unprotect the document in Aspose.Words as it does not require a password when unprotecting.

Example

Protects a section so only editing in form fields is possible.

[C#]

// Create a blank document
Document doc = new Document();

// Insert two sections with some text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Section 1. Unprotected.");
builder.InsertBreak(BreakType.SectionBreakContinuous);
builder.Writeln("Section 2. Protected.");

// Section protection only works when document protection is turned and only editing in form fields is allowed.
doc.Protect(ProtectionType.AllowOnlyFormFields);

// By default, all sections are protected, but we can selectively turn protection off.
doc.Sections[0].ProtectedForForms = false;

builder.Document.Save(ArtifactsDir + "Section.Protect.doc");

See Also

Document Class | Aspose.Words Namespace | Document.Protect Overload List


Document.Protect Method (ProtectionType, String)

Protects the document from changes and optionally sets a protection password.

[Visual Basic]
Overloads Public Sub Protect( _
ByVal type As ProtectionType, _
ByVal password As String _
)
[C#]
public void Protect(
ProtectionType type,
string password
);

Parameters

type
Specifies the protection type for the document.
password
The password to protect the document with. Specify null or empty string if you want to protect the document without a password.

Remarks

When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

Note that document protection is different from write protection. Write protection is specified using the WriteProtection.

Example

Shows how to protect a document.

[C#]

Document doc = new Document();
doc.Protect(ProtectionType.AllowOnlyFormFields, "password");

See Also

Document Class | Aspose.Words Namespace | Document.Protect Overload List


Document.RemoveExternalSchemaReferences Method

Removes external XML schema references from this document.

[Visual Basic]
Public Sub RemoveExternalSchemaReferences()
[C#]
public void RemoveExternalSchemaReferences();

Example

Shows how to remove all external XML schema references from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.RemoveExternalSchemaReferences();

See Also

Document Class | Aspose.Words Namespace


Document.RemoveMacros Method

Removes all macros (the VBA project) as well as toolbars and command customizations from the document.

[Visual Basic]
Public Sub RemoveMacros()
[C#]
public void RemoveMacros();

Remarks

By removing all macros from a document you can ensure the document contains no macro viruses.

Example

Shows how to remove all macros from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.RemoveMacros();

See Also

Document Class | Aspose.Words Namespace


Document.RenderToScale Method

Renders a document page into a Graphics object to a specified scale.

[Visual Basic]
Public Function RenderToScale( _
ByVal pageIndex As Integer, _
ByVal graphics As Graphics, _
ByVal x As Single, _
ByVal y As Single, _
ByVal scale As Single _
) As SizeF
[C#]
public SizeF RenderToScale(
int pageIndex,
Graphics graphics,
float x,
float y,
float scale
);

Parameters

pageIndex
The 0-based page index.
graphics
The object where to render to.
x
The X coordinate (in world units) of the top left corner of the rendered page.
y
The Y coordinate (in world units) of the top left corner of the rendered page.
scale
The scale for rendering the page (1.0 is 100%).

Return Value

The width and height (in world units) of the rendered page.

Example

Renders a page of a Word document into a bitmap using a specified zoom factor.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            PageInfo pageInfo = doc.GetPageInfo(0);

            // Let's say we want the image at 50% zoom.
            const float myScale = 0.50f;

            // Let's say we want the image at this resolution.
            const float myResolution = 200.0f;

            Size pageSize = pageInfo.GetSizeInPixels(myScale, myResolution);
#if NETSTANDARD2_0 || __MOBILE__
            using (SKBitmap bitmap = new SKBitmap(pageSize.Width, pageSize.Height))
            {
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    // Scale to compensate for the larger bitmap
                    canvas.Scale(2);

                    // Fill the page background.
                    // If you need to set color without specific options, you can use "canvas.Clear(SKColors.White);"
                    SKPaint paint = new SKPaint
                    {
                        Color = SKColors.White,
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High
                    };

                    canvas.DrawPaint(paint);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, canvas, 0, 0, myScale);
                }

                using (SKFileWStream fs = new SKFileWStream(ArtifactsDir + "Rendering.RenderToScale.png"))
                {
                    bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100);
                }
            }
#else
            using (Bitmap img = new Bitmap(pageSize.Width, pageSize.Height))
            {
                img.SetResolution(myResolution, myResolution);

                using (Graphics gr = Graphics.FromImage(img))
                {
                    // You can apply various settings to the Graphics object.
                    gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    // Fill the page background.
                    gr.FillRectangle(Brushes.White, 0, 0, pageSize.Width, pageSize.Height);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, gr, 0, 0, myScale);
                }

                img.Save(ArtifactsDir + "Rendering.RenderToScale.png");
            }
#endif
Renders individual pages to graphics to create one image with thumbnails of all pages.
[C#]

// The user opens or builds a document.
            Document doc = new Document(MyDir + "Rendering.doc");

            // This defines the number of columns to display the thumbnails in.
            const int thumbColumns = 2;

            // Calculate the required number of rows for thumbnails.
            // We can now get the number of pages in the document.
            int remainder;
            int thumbRows = Math.DivRem(doc.PageCount, thumbColumns, out remainder);
            if (remainder > 0)
                thumbRows++;

            // Lets say I want thumbnails to be of this zoom.
            const float scale = 0.25f;

            // For simplicity lets pretend all pages in the document are of the same size,
            // so we can use the size of the first page to calculate the size of the thumbnail.
            Size thumbSize = doc.GetPageInfo(0).GetSizeInPixels(scale, 96);

            // Calculate the size of the image that will contain all the thumbnails.
            int imgWidth = thumbSize.Width * thumbColumns;
            int imgHeight = thumbSize.Height * thumbRows;
#if NETSTANDARD2_0 || __MOBILE__
            using (SKBitmap bitmap = new SKBitmap(imgWidth, imgHeight))
            {
                // The user has to provides a Graphics object to draw on.
                // The Graphics object can be created from a bitmap, from a metafile, printer or window.
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    // Fill the "paper" with white, otherwise it will be transparent.
                    canvas.Clear(SKColors.White);

                    for (int pageIndex = 0; pageIndex < doc.PageCount; pageIndex++)
                    {
                        int columnIdx;
                        int rowIdx = Math.DivRem(pageIndex, thumbColumns, out columnIdx);

                        // Specify where we want the thumbnail to appear.
                        float thumbLeft = columnIdx * thumbSize.Width;
                        float thumbTop = rowIdx * thumbSize.Height;

                        SizeF size = doc.RenderToScale(pageIndex, canvas, thumbLeft, thumbTop, scale);

                        // Draw the page rectangle.
                        SKRect rect = new SKRect(0, 0, size.Width, size.Height);
                        rect.Offset(thumbLeft, thumbTop);
                        canvas.DrawRect(rect, new SKPaint
                        {
                            Color = SKColors.Black,
                            Style = SKPaintStyle.Stroke
                        });
                    }

                    using (SKFileWStream fs = new SKFileWStream(ArtifactsDir + "Rendering.Thumbnails.png"))
                    {
                        bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100);
                    }
                }
            }
#else
            using (Bitmap img = new Bitmap(imgWidth, imgHeight))
            {
                // The user has to provides a Graphics object to draw on.
                // The Graphics object can be created from a bitmap, from a metafile, printer or window.
                using (Graphics gr = Graphics.FromImage(img))
                {
                    gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    // Fill the "paper" with white, otherwise it will be transparent.
                    gr.FillRectangle(new SolidBrush(Color.White), 0, 0, imgWidth, imgHeight);

                    for (int pageIndex = 0; pageIndex < doc.PageCount; pageIndex++)
                    {
                        int columnIdx;
                        int rowIdx = Math.DivRem(pageIndex, thumbColumns, out columnIdx);

                        // Specify where we want the thumbnail to appear.
                        float thumbLeft = columnIdx * thumbSize.Width;
                        float thumbTop = rowIdx * thumbSize.Height;

                        SizeF size = doc.RenderToScale(pageIndex, gr, thumbLeft, thumbTop, scale);

                        // Draw the page rectangle.
                        gr.DrawRectangle(Pens.Black, thumbLeft, thumbTop, size.Width, size.Height);
                    }

                    img.Save(ArtifactsDir + "Rendering.Thumbnails.png");
                }
            }
#endif

See Also

Document Class | Aspose.Words Namespace


Document.RenderToSize Method

[Visual Basic]
Public Function RenderToSize( _
ByVal pageIndex As Integer, _
ByVal graphics As Graphics, _
ByVal x As Single, _
ByVal y As Single, _
ByVal width As Single, _
ByVal height As Single _
) As Single
[C#]
public float RenderToSize(
int pageIndex,
Graphics graphics,
float x,
float y,
float width,
float height
);

Parameters

pageIndex
The 0-based page index.
graphics
The object where to render to.
x
The X coordinate (in world units) of the top left corner of the rendered page.
y
The Y coordinate (in world units) of the top left corner of the rendered page.
width
The maximum width (in world units) that can be occupied by the rendered page.
height
The maximum height (in world units) that can be occupied by the rendered page.

Return Value

The scale that was automatically calculated for the rendered page to fit the specified size.

Example

Render to a bitmap at a specified location and size.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");
#if NETSTANDARD2_0 || __MOBILE__
            using (SKBitmap bitmap = new SKBitmap(700, 700))
            {
                // User has some sort of a Graphics object. In this case created from a bitmap.
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    // Apply scale transform.
                    canvas.Scale(70);

                    // The output should be offset 0.5" from the edge and rotated.
                    canvas.Translate(0.5f, 0.5f);
                    canvas.RotateDegrees(10);

                    // This is our test rectangle.
                    SKRect rect = new SKRect(0f, 0f, 3f, 3f);
                    canvas.DrawRect(rect, new SKPaint
                    {
                        Color = SKColors.Black,
                        Style = SKPaintStyle.Stroke,
                        StrokeWidth = 3f / 72f
                    });

                    // User specifies (in world coordinates) where on the Graphics to render and what size.
                    float returnedScale = doc.RenderToSize(0, canvas, 0f, 0f, 3f, 3f);

                    Console.WriteLine("The image was rendered at {0:P0} zoom.", returnedScale);

                    // One more example, this time in millimeters.
                    canvas.ResetMatrix();

                    // Apply scale transform.
                    canvas.Scale(5);

                    // Move the origin 10mm
                    canvas.Translate(10, 10);

                    // This is our test rectangle.
                    rect = new SKRect(0, 0, 50, 100);
                    rect.Offset(90, 10);
                    canvas.DrawRect(rect, new SKPaint
                    {
                        Color = SKColors.Black,
                        Style = SKPaintStyle.Stroke,
                        StrokeWidth = 1
                    });

                    // User specifies (in world coordinates) where on the Graphics to render and what size.
                    doc.RenderToSize(0, canvas, 90, 10, 50, 100);

                    using (SKFileWStream fs = new SKFileWStream(ArtifactsDir + "Rendering.RenderToSize.png"))
                    {
                        bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100);
                    }
                }
            }
#else
            using (Bitmap bmp = new Bitmap(700, 700))
            {
                // User has some sort of a Graphics object. In this case created from a bitmap.
                using (Graphics gr = Graphics.FromImage(bmp))
                {
                    // The user can specify any options on the Graphics object including
                    // transform, anti-aliasing, page units, etc.
                    gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    // Let's say we want to fit the page into a 3" x 3" square on the screen so use inches as units.
                    gr.PageUnit = GraphicsUnit.Inch;

                    // The output should be offset 0.5" from the edge and rotated.
                    gr.TranslateTransform(0.5f, 0.5f);
                    gr.RotateTransform(10);

                    // This is our test rectangle.
                    gr.DrawRectangle(new Pen(Color.Black, 3f / 72f), 0f, 0f, 3f, 3f);

                    // User specifies (in world coordinates) where on the Graphics to render and what size.
                    float returnedScale = doc.RenderToSize(0, gr, 0f, 0f, 3f, 3f);

                    // This is the calculated scale factor to fit 297mm into 3".
                    Console.WriteLine("The image was rendered at {0:P0} zoom.", returnedScale);

                    // One more example, this time in millimeters.
                    gr.PageUnit = GraphicsUnit.Millimeter;

                    gr.ResetTransform();

                    // Move the origin 10mm
                    gr.TranslateTransform(10, 10);

                    // Apply both scale transform and page scale for fun.
                    gr.ScaleTransform(0.5f, 0.5f);
                    gr.PageScale = 2f;

                    // This is our test rectangle.
                    gr.DrawRectangle(new Pen(Color.Black, 1), 90, 10, 50, 100);

                    // User specifies (in world coordinates) where on the Graphics to render and what size.
                    doc.RenderToSize(1, gr, 90, 10, 50, 100);

                    bmp.Save(ArtifactsDir + "Rendering.RenderToSize.png");
                }
            }
#endif

See Also

Document Class | Aspose.Words Namespace


Save Method

Aspose.Words

Document.Save Method

Saves the document.

Overload List

Saves the document to a stream using the specified format.

public SaveOutputParameters Save(Stream,SaveFormat);

Saves the document to a stream using the specified save options.

public SaveOutputParameters Save(Stream,SaveOptions);

Saves the document to a file. Automatically determines the save format from the extension.

public SaveOutputParameters Save(string);

Saves the document to a file in the specified format.

public SaveOutputParameters Save(string,SaveFormat);

Saves the document to a file using the specified save options.

public SaveOutputParameters Save(string,SaveOptions);

Sends the document to the client browser.

public SaveOutputParameters Save(HttpResponse,string,ContentDisposition,SaveOptions);

See Also

Document Class | Aspose.Words Namespace


Document.Save Method (Stream, SaveFormat)

Saves the document to a stream using the specified format.

[Visual Basic]
Overloads Public Function Save( _
ByVal stream As Stream, _
ByVal saveFormat As SaveFormat _
) As SaveOutputParameters
[C#]
public SaveOutputParameters Save(
Stream stream,
SaveFormat saveFormat
);

Parameters

stream
Stream where to save the document.
saveFormat
The format in which to save the document.

Return Value

Additional information that you can optionally use.

Example

Shows how to save a document to a stream.

[C#]

Document doc = new Document(MyDir + "Document.doc");

using (MemoryStream dstStream = new MemoryStream())
{
    doc.Save(dstStream, SaveFormat.Docx);

    // Rewind the stream position back to zero so it is ready for next reader.
    dstStream.Position = 0;
}
Saves a document page as a BMP image into a stream.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            MemoryStream stream = new MemoryStream();
            doc.Save(stream, SaveFormat.Bmp);

            // Rewind the stream and create a .NET image from it.
            stream.Position = 0;
#if NETSTANDARD2_0 || __MOBILE__
// Read the stream back into an image.
            SkiaSharp.SKBitmap image = SkiaSharp.SKBitmap.Decode(stream);
#else
            // Read the stream back into an image.
            using (Image image = Image.FromStream(stream))
            {
                // ...Do something.
            }
#endif
Shows how to save a document to the XPS format using the Save method and the XpsSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save document to file in the XPS format with default options
doc.Save(ArtifactsDir + "Rendering.XpsDefaultOptions.xps");

// Save document to stream in the XPS format with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Xps);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to file in the XPS format with specified options
// Render the first page only
XpsSaveOptions xpsOptions = new XpsSaveOptions();
xpsOptions.PageIndex = 0;
xpsOptions.PageCount = 1;
doc.Save(ArtifactsDir + "Rendering.XpsCustomOptions.xps", xpsOptions);
Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");

// Option 1: Save document to file in the PDF format with default options
doc.Save(ArtifactsDir + "Rendering.PdfDefaultOptions.pdf");

// Option 2: Save the document to stream in the PDF format with default options
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Pdf);
// Rewind the stream position back to the beginning, ready for use
stream.Seek(0, SeekOrigin.Begin);

// Option 3: Save document to the PDF format with specified options
// Render the first page only and preserve form fields as usable controls and not as plain text
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.PageIndex = 0;
pdfOptions.PageCount = 1;
pdfOptions.PreserveFormFields = true;
doc.Save(ArtifactsDir + "Rendering.PdfCustomOptions.pdf", pdfOptions);
Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save as a JPEG image file with default options
doc.Save(ArtifactsDir + "Rendering.JpegDefaultOptions.jpg");

// Save document to stream as a JPEG with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to a JPEG image with specified options.
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg);
imageOptions.PageIndex = 2;
imageOptions.PageCount = 1;
imageOptions.JpegQuality = 80;
doc.Save(ArtifactsDir + "Rendering.JpegCustomOptions.jpg", imageOptions);

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


Document.Save Method (Stream, SaveOptions)

Saves the document to a stream using the specified save options.

[Visual Basic]
Overloads Public Function Save( _
ByVal stream As Stream, _
ByVal saveOptions As SaveOptions _
) As SaveOutputParameters
[C#]
public SaveOutputParameters Save(
Stream stream,
SaveOptions saveOptions
);

Parameters

stream
Stream where to save the document.
saveOptions
Specifies the options that control how the document is saved. Can be null. If this is null, the document will be saved in the binary DOC format.

Return Value

Additional information that you can optionally use.

Example

Converts just one page (third page in this example) of the document to PDF.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

using (Stream stream = File.Create(ArtifactsDir + "Rendering.SaveToPdfStreamOnePage.pdf"))
{
    PdfSaveOptions options = new PdfSaveOptions();
    options.PageIndex = 2;
    options.PageCount = 1;
    doc.Save(stream, options);
}

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


Document.Save Method (String)

Saves the document to a file. Automatically determines the save format from the extension.

[Visual Basic]
Overloads Public Function Save( _
ByVal fileName As String _
) As SaveOutputParameters
[C#]
public SaveOutputParameters Save(
string fileName
);

Parameters

fileName
The name for the document. If a document with the specified file name already exists, the existing document is overwritten.

Return Value

Additional information that you can optionally use.

Example

Saves a document to a file.

[C#]

doc.Save(ArtifactsDir + "Document.OpenFromFile.doc");
Converts a whole document from DOC to PDF using default options.
[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Save(ArtifactsDir + "Document.Doc2PdfSave.pdf");
Converts from DOC to MHTML format.
[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Save(ArtifactsDir + "Document.ConvertToMhtml.mht");
Converts a whole document to PDF using default options.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

doc.Save(ArtifactsDir + "Rendering.SaveToPdfDefault.pdf");
Converts a whole document into a multipage TIFF file using default options.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

doc.Save(ArtifactsDir + "Rendering.SaveToTiffDefault.tiff");
Shows how to save a document to the XPS format using the Save method and the XpsSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save document to file in the XPS format with default options
doc.Save(ArtifactsDir + "Rendering.XpsDefaultOptions.xps");

// Save document to stream in the XPS format with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Xps);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to file in the XPS format with specified options
// Render the first page only
XpsSaveOptions xpsOptions = new XpsSaveOptions();
xpsOptions.PageIndex = 0;
xpsOptions.PageCount = 1;
doc.Save(ArtifactsDir + "Rendering.XpsCustomOptions.xps", xpsOptions);
Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");

// Option 1: Save document to file in the PDF format with default options
doc.Save(ArtifactsDir + "Rendering.PdfDefaultOptions.pdf");

// Option 2: Save the document to stream in the PDF format with default options
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Pdf);
// Rewind the stream position back to the beginning, ready for use
stream.Seek(0, SeekOrigin.Begin);

// Option 3: Save document to the PDF format with specified options
// Render the first page only and preserve form fields as usable controls and not as plain text
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.PageIndex = 0;
pdfOptions.PageCount = 1;
pdfOptions.PreserveFormFields = true;
doc.Save(ArtifactsDir + "Rendering.PdfCustomOptions.pdf", pdfOptions);
Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save as a JPEG image file with default options
doc.Save(ArtifactsDir + "Rendering.JpegDefaultOptions.jpg");

// Save document to stream as a JPEG with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to a JPEG image with specified options.
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg);
imageOptions.PageIndex = 2;
imageOptions.PageCount = 1;
imageOptions.JpegQuality = 80;
doc.Save(ArtifactsDir + "Rendering.JpegCustomOptions.jpg", imageOptions);

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


Document.Save Method (String, SaveFormat)

Saves the document to a file in the specified format.

[Visual Basic]
Overloads Public Function Save( _
ByVal fileName As String, _
ByVal saveFormat As SaveFormat _
) As SaveOutputParameters
[C#]
public SaveOutputParameters Save(
string fileName,
SaveFormat saveFormat
);

Parameters

fileName
The name for the document. If a document with the specified file name already exists, the existing document is overwritten.
saveFormat
The format in which to save the document.

Return Value

Additional information that you can optionally use.

Example

Converts from DOC to HTML format.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Save(ArtifactsDir + "Document.ConvertToHtml.html", SaveFormat.Html);

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


Document.Save Method (String, SaveOptions)

Saves the document to a file using the specified save options.

[Visual Basic]
Overloads Public Function Save( _
ByVal fileName As String, _
ByVal saveOptions As SaveOptions _
) As SaveOutputParameters
[C#]
public SaveOutputParameters Save(
string fileName,
SaveOptions saveOptions
);

Parameters

fileName
The name for the document. If a document with the specified file name already exists, the existing document is overwritten.
saveOptions
Specifies the options that control how the document is saved. Can be null.

Return Value

Additional information that you can optionally use.

Example

Converts a whole document to PDF with three levels in the document outline.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.OutlineOptions.HeadingsOutlineLevels = 3;
options.OutlineOptions.ExpandedOutlineLevels = 1;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfWithOutline.pdf", options);
Converts a page of a Word document into a TIFF image and uses the CCITT compression.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff)
{
    TiffCompression = TiffCompression.Ccitt3,
    PageIndex = 0,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToTiffCompression.tiff", options);
Converts every page of a DOC file into a separate scalable EMF file.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Emf) { PageCount = 1 };

for (int i = 0; i < doc.PageCount; i++)
{
    options.PageIndex = i;
    doc.Save(ArtifactsDir + "Rendering.SaveToEmf." + i.ToString() + ".emf", options);
}
Shows how to save a document to the XPS format using the Save method and the XpsSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save document to file in the XPS format with default options
doc.Save(ArtifactsDir + "Rendering.XpsDefaultOptions.xps");

// Save document to stream in the XPS format with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Xps);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to file in the XPS format with specified options
// Render the first page only
XpsSaveOptions xpsOptions = new XpsSaveOptions();
xpsOptions.PageIndex = 0;
xpsOptions.PageCount = 1;
doc.Save(ArtifactsDir + "Rendering.XpsCustomOptions.xps", xpsOptions);
Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");

// Option 1: Save document to file in the PDF format with default options
doc.Save(ArtifactsDir + "Rendering.PdfDefaultOptions.pdf");

// Option 2: Save the document to stream in the PDF format with default options
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Pdf);
// Rewind the stream position back to the beginning, ready for use
stream.Seek(0, SeekOrigin.Begin);

// Option 3: Save document to the PDF format with specified options
// Render the first page only and preserve form fields as usable controls and not as plain text
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.PageIndex = 0;
pdfOptions.PageCount = 1;
pdfOptions.PreserveFormFields = true;
doc.Save(ArtifactsDir + "Rendering.PdfCustomOptions.pdf", pdfOptions);
Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.
[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save as a JPEG image file with default options
doc.Save(ArtifactsDir + "Rendering.JpegDefaultOptions.jpg");

// Save document to stream as a JPEG with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to a JPEG image with specified options.
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg);
imageOptions.PageIndex = 2;
imageOptions.PageCount = 1;
imageOptions.JpegQuality = 80;
doc.Save(ArtifactsDir + "Rendering.JpegCustomOptions.jpg", imageOptions);

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


Document.Save Method (HttpResponse, String, ContentDisposition, SaveOptions)

Sends the document to the client browser.

[Visual Basic]
Overloads Public Function Save( _
ByVal response As HttpResponse, _
ByVal fileName As String, _
ByVal contentDisposition As ContentDisposition, _
ByVal saveOptions As SaveOptions _
) As SaveOutputParameters
[C#]
public SaveOutputParameters Save(
HttpResponse response,
string fileName,
ContentDisposition contentDisposition,
SaveOptions saveOptions
);

Parameters

response
Response object where to save the document.
fileName
The name for the document that will appear at the client browser. The name should not contain path.
contentDisposition
A ContentDisposition value that specifies how the document is presented at the client browser.
saveOptions
Specifies the options that control how the document is saved. Can be null.

Return Value

Additional information that you can optionally use.

Remarks

Internally, this method saves to a memory stream first and then copies to the response stream because the response stream does not support seek.

Example

Performs a simple insertion of data into merge fields and sends the document to the browser inline.

[C#]

// Open an existing document.
Document doc = new Document(MyDir + "MailMerge.ExecuteArray.doc");

// Fill the fields in the document with user data.
doc.MailMerge.Execute(new String[] { "FullName", "Company", "Address", "Address2", "City" },
    new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });

// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
Assert.That(() => doc.Save(Response, "Artifacts/MailMerge.ExecuteArray.doc", ContentDisposition.Inline, null), Throws.TypeOf<ArgumentNullException>()); //Thrown because HttpResponse is null in the test.

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


StartTrackRevisions Method

Aspose.Words

Document.StartTrackRevisions Method

Starts automatically marking all further changes you make to the document programmatically as revision changes.

Overload List

Starts automatically marking all further changes you make to the document programmatically as revision changes.

public void StartTrackRevisions(string);

Starts automatically marking all further changes you make to the document programmatically as revision changes.

public void StartTrackRevisions(string,DateTime);

See Also

Document Class | Aspose.Words Namespace | StopTrackRevisions


Document.StartTrackRevisions Method (String)

Starts automatically marking all further changes you make to the document programmatically as revision changes.

[Visual Basic]
Overloads Public Sub StartTrackRevisions( _
ByVal author As String _
)
[C#]
public void StartTrackRevisions(
string author
);

Parameters

author
Initials of the author to use for revisions.

Remarks

If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using DocumentBuilder

This method does not change the TrackRevisions option and does not use its value for the purposes of revision tracking.

Example

Shows how tracking revisions affects document editing.

[C#]

Document doc = new Document();

// This text will appear as normal text in the document and no revisions will be counted.
doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, "Hello world!"));
Console.WriteLine(doc.Revisions.Count); // 0

doc.StartTrackRevisions("Author");

// This text will appear as a revision.
// We did not specify a time while calling StartTrackRevisions(), so the date/time that's noted
// on the revision will be the real time when StartTrackRevisions() executes.
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 2

// Stopping the tracking of revisions makes this text appear as normal text.
// Revisions are not counted when the document is changed.
doc.StopTrackRevisions();
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 2

// Specifying some date/time will apply that date/time to all subsequent revisions until StopTrackRevisions() is called.
// Note that placing values such as DateTime.MinValue as an argument will create revisions that do not have a date/time at all.
doc.StartTrackRevisions("Author", new DateTime(1970, 1, 1));
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 4

doc.Save(ArtifactsDir + "Document.StartTrackRevisions.doc");

See Also

Document Class | Aspose.Words Namespace | Document.StartTrackRevisions Overload List | StopTrackRevisions


Document.StartTrackRevisions Method (String, DateTime)

Starts automatically marking all further changes you make to the document programmatically as revision changes.

[Visual Basic]
Overloads Public Sub StartTrackRevisions( _
ByVal author As String, _
ByVal dateTime As Date _
)
[C#]
public void StartTrackRevisions(
string author,
DateTime dateTime
);

Parameters

author
Initials of the author to use for revisions.
dateTime
The date and time to use for revisions.

Remarks

If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using DocumentBuilder

This method does not change the TrackRevisions option and does not use its value for the purposes of revision tracking.

Example

Shows how tracking revisions affects document editing.

[C#]

Document doc = new Document();

// This text will appear as normal text in the document and no revisions will be counted.
doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, "Hello world!"));
Console.WriteLine(doc.Revisions.Count); // 0

doc.StartTrackRevisions("Author");

// This text will appear as a revision.
// We did not specify a time while calling StartTrackRevisions(), so the date/time that's noted
// on the revision will be the real time when StartTrackRevisions() executes.
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 2

// Stopping the tracking of revisions makes this text appear as normal text.
// Revisions are not counted when the document is changed.
doc.StopTrackRevisions();
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 2

// Specifying some date/time will apply that date/time to all subsequent revisions until StopTrackRevisions() is called.
// Note that placing values such as DateTime.MinValue as an argument will create revisions that do not have a date/time at all.
doc.StartTrackRevisions("Author", new DateTime(1970, 1, 1));
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 4

doc.Save(ArtifactsDir + "Document.StartTrackRevisions.doc");

See Also

Document Class | Aspose.Words Namespace | Document.StartTrackRevisions Overload List | StopTrackRevisions


Document.StopTrackRevisions Method

Stops automatic marking of document changes as revisions.

[Visual Basic]
Public Sub StopTrackRevisions()
[C#]
public void StopTrackRevisions();

Example

Shows how tracking revisions affects document editing.

[C#]

Document doc = new Document();

// This text will appear as normal text in the document and no revisions will be counted.
doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, "Hello world!"));
Console.WriteLine(doc.Revisions.Count); // 0

doc.StartTrackRevisions("Author");

// This text will appear as a revision.
// We did not specify a time while calling StartTrackRevisions(), so the date/time that's noted
// on the revision will be the real time when StartTrackRevisions() executes.
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 2

// Stopping the tracking of revisions makes this text appear as normal text.
// Revisions are not counted when the document is changed.
doc.StopTrackRevisions();
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 2

// Specifying some date/time will apply that date/time to all subsequent revisions until StopTrackRevisions() is called.
// Note that placing values such as DateTime.MinValue as an argument will create revisions that do not have a date/time at all.
doc.StartTrackRevisions("Author", new DateTime(1970, 1, 1));
doc.FirstSection.Body.AppendParagraph("Hello again!");
Console.WriteLine(doc.Revisions.Count); // 4

doc.Save(ArtifactsDir + "Document.StartTrackRevisions.doc");

See Also

Document Class | Aspose.Words Namespace | StartTrackRevisions


Document.UnlinkFields Method

Unlinks fields in the whole document.

[Visual Basic]
Public Sub UnlinkFields()
[C#]
public void UnlinkFields();

Remarks

Replaces all the fields in the whole document with their most recent results.

To unlink fields in a specific part of the document use UnlinkFields.

Example

Shows how to unlink all fields in the document

[C#]

Document doc = new Document(MyDir + "Field.UnlinkFields.docx");

doc.UnlinkFields();

See Also

Document Class | Aspose.Words Namespace


Unprotect Method

Aspose.Words

Document.Unprotect Method

Removes protection from the document.

Overload List

Removes protection from the document regardless of the password.

public void Unprotect();

Removes protection from the document if a correct password is specified.

public bool Unprotect(string);

See Also

Document Class | Aspose.Words Namespace


Document.Unprotect Method ()

Removes protection from the document regardless of the password.

[Visual Basic]
Overloads Public Sub Unprotect()
[C#]
public void Unprotect();

Remarks

This method unprotects the document even if it has a protection password.

Note that document protection is different from write protection. Write protection is specified using the WriteProtection.

Example

Shows how to unprotect a document. Note that the password is not required.

[C#]

doc.Unprotect();

See Also

Document Class | Aspose.Words Namespace | Document.Unprotect Overload List


Document.Unprotect Method (String)

Removes protection from the document if a correct password is specified.

[Visual Basic]
Overloads Public Function Unprotect( _
ByVal password As String _
) As Boolean
[C#]
public bool Unprotect(
string password
);

Parameters

password
The password to unprotect the document with.

Return Value

True if a correct password was specified and the document was unprotected.

Remarks

This method unprotects the document only if a correct password is specified.

Note that document protection is different from write protection. Write protection is specified using the WriteProtection.

Example

Shows how to unprotect a document using a password.

[C#]

doc.Unprotect("password");

See Also

Document Class | Aspose.Words Namespace | Document.Unprotect Overload List


Document.UpdateFields Method

Updates the values of fields in the whole document.

[Visual Basic]
Public Sub UpdateFields()
[C#]
public void UpdateFields();

Remarks

When you open, modify and then save a document, Aspose.Words does not update fields automatically, it keeps them intact. Therefore, you would usually want to call this method before saving if you have modified the document programmatically and want to make sure the proper (calculated) field values appear in the saved document.

There is no need to update fields after executing a mail merge because mail merge is a kind of field update and automatically updates all fields in the document.

This method does not update all field types. For the detailed list of supported field types, see the Programmers Guide.

This method does not update fields that are related to the page layout algorithms (e.g. PAGE, PAGES, PAGEREF). The page layout-related fields are updated when you render a document or call UpdatePageLayout.

Use the NormalizeFieldTypes method before fields updating if there were document changes that affected field types.

To update fields in a specific part of the document use UpdateFields.

Example

Shows how to update all fields in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.UpdateFields();
Shows how to update all fields before rendering a document.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// This updates all fields in the document.
doc.UpdateFields();

doc.Save(ArtifactsDir + "Rendering.UpdateFields.pdf");
Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.
[C#]

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 2");
builder.Writeln("Heading 3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");

// Call the method below to update the TOC.
doc.UpdateFields();

See Also

Document Class | Aspose.Words Namespace


Document.UpdateListLabels Method

Updates list labels for all list items in the document.

[Visual Basic]
Public Sub UpdateListLabels()
[C#]
public void UpdateListLabels();

Remarks

This method updates list label properties such as LabelValue and LabelString for each ListLabel object in the document.

Also, this method is sometimes implicitly called when updating fields in the document. This is required because some fields that may reference list numbers (such as TOC or REF) need them be up-to-date.

Example

Shows how to extract the label of each paragraph in a list as a value or a String.

[C#]

Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
doc.UpdateListLabels();
int listParaCount = 1;

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
    // which start at three and ends at six.
    if (paragraph.ListFormat.IsListItem)
    {
        Console.WriteLine("Paragraph #{0}", listParaCount);

        // This is the text we get when actually getting when we output this node to text format.
        // The list labels are not included in this text output. Trim any paragraph formatting characters.
        String paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
        Console.WriteLine("Exported Text: " + paragraphText);

        ListLabel label = paragraph.ListLabel;
        // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
        // will tell us what position it is on that particular level.
        Console.WriteLine("Numerical Id: " + label.LabelValue);

        // Combine them together to include the list label with the text in the output.
        Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

        listParaCount++;
    }
}

See Also

Document Class | Aspose.Words Namespace


Document.UpdatePageLayout Method

Rebuilds the page layout of the document.

[Visual Basic]
Public Sub UpdatePageLayout()
[C#]
public void UpdatePageLayout();

Remarks

This method formats a document into pages and updates the page number related fields in the document such as PAGE, PAGES, PAGEREF and REF. The up-to-date page layout information is required for a correct rendering of the document to fixed-page formats.

This method is automatically invoked when you first convert a document to PDF, XPS, image or print it. However, if you modify the document after rendering and then attempt to render it again - Aspose.Words will not update the page layout automatically. In this case you should call UpdatePageLayout before rendering again.

Example

Shows when to request page layout of the document to be recalculated.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Saving a document to PDF or to image or printing for the first time will automatically
// layout document pages and this information will be cached inside the document.
doc.Save(ArtifactsDir + "Rendering.UpdatePageLayout1.pdf");

// Modify the document in any way.
doc.Styles["Normal"].Font.Size = 6;
doc.Sections[0].PageSetup.Orientation = Aspose.Words.Orientation.Landscape;

// In the current version of Aspose.Words, modifying the document does not automatically rebuild
// the cached page layout. If you want to save to PDF or render a modified document again,
// you need to manually request page layout to be updated.
doc.UpdatePageLayout();

doc.Save(ArtifactsDir + "Rendering.UpdatePageLayout2.pdf");

See Also

Document Class | Aspose.Words Namespace


Document.UpdateTableLayout Method

Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document.

[Visual Basic]
Public Sub UpdateTableLayout()
[C#]
public void UpdateTableLayout();

Remarks

You do not normally need to call this method as cell and table widths are maintained automatically. You can call this method before exporting to PDF (or any other fixed-page format), only in rare cases where you confirmed that tables appear incorrectly laid out in the output document. Calling this method might help to correct the output.

Example

Shows how to update the layout of tables in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Normally this method is not necessary to call, as cell and table widths are maintained automatically.
// This method may need to be called when exporting to PDF in rare cases when the table layout appears
// incorrectly in the rendered output.
doc.UpdateTableLayout();

See Also

Document Class | Aspose.Words Namespace


UpdateThumbnail Method

Aspose.Words

Document.UpdateThumbnail Method

Updates Thumbnail of the document using default options.

Overload List

Updates Thumbnail of the document using default options.

public void UpdateThumbnail();

Updates Thumbnail of the document according to the specified options.

public void UpdateThumbnail(ThumbnailGeneratingOptions);

See Also

Document Class | Aspose.Words Namespace


Document.UpdateThumbnail Method ()

Updates Thumbnail of the document using default options.

[Visual Basic]
Overloads Public Sub UpdateThumbnail()
[C#]
public void UpdateThumbnail();

Example

Shows how to update a document's thumbnail.

[C#]

Document doc = new Document();

// Update document's thumbnail the default way.
doc.UpdateThumbnail();

// Review/change thumbnail options and then update document's thumbnail.
ThumbnailGeneratingOptions tgo = new ThumbnailGeneratingOptions();

Console.WriteLine("Thumbnail size: {0}", tgo.ThumbnailSize);
tgo.GenerateFromFirstPage = true;

doc.UpdateThumbnail(tgo);

See Also

Document Class | Aspose.Words Namespace | Document.UpdateThumbnail Overload List


Document.UpdateThumbnail Method (ThumbnailGeneratingOptions)

Updates Thumbnail of the document according to the specified options.

[Visual Basic]
Overloads Public Sub UpdateThumbnail( _
ByVal options As ThumbnailGeneratingOptions _
)
[C#]
public void UpdateThumbnail(
ThumbnailGeneratingOptions options
);

Parameters

options
The generating options to use.

Remarks

The ThumbnailGeneratingOptions allows you to specify the source of thumbnail, size and other options. If attempt to generate thumbnail fails, doesn't change one.

Example

Shows how to update a document's thumbnail.

[C#]

Document doc = new Document();

// Update document's thumbnail the default way.
doc.UpdateThumbnail();

// Review/change thumbnail options and then update document's thumbnail.
ThumbnailGeneratingOptions tgo = new ThumbnailGeneratingOptions();

Console.WriteLine("Thumbnail size: {0}", tgo.ThumbnailSize);
tgo.GenerateFromFirstPage = true;

doc.UpdateThumbnail(tgo);

See Also

Document Class | Aspose.Words Namespace | Document.UpdateThumbnail Overload List


UpdateWordCount Method

Aspose.Words

Document.UpdateWordCount Method

Updates word count properties of the document.

Overload List

Updates word count properties of the document.

public void UpdateWordCount();

Updates word count properties of the document, optionally updates Lines property.

public void UpdateWordCount(bool);

See Also

Document Class | Aspose.Words Namespace


Document.UpdateWordCount Method ()

Updates word count properties of the document.

[Visual Basic]
Overloads Public Sub UpdateWordCount()
[C#]
public void UpdateWordCount();

Remarks

UpdateWordCount recalculates and updates Characters, Words and Paragraphs properties in the BuiltInDocumentProperties collection of the Document.

Note that UpdateWordCount does not update number of lines and pages properties. Use the UpdateWordCount overload and pass True value as a parameter to do that.

When you use an evaluation version, the evaluation watermark will also be included in the word count.

Example

Shows how to update all list labels in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Some work should be done here that changes the document's content.

// Update the word, character and paragraph count of the document.
doc.UpdateWordCount();

// Display the updated document properties.
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);

See Also

Document Class | Aspose.Words Namespace | Document.UpdateWordCount Overload List


Document.UpdateWordCount Method (Boolean)

Updates word count properties of the document, optionally updates Lines property.

[Visual Basic]
Overloads Public Sub UpdateWordCount( _
ByVal updateLinesCount As Boolean _
)
[C#]
public void UpdateWordCount(
bool updateLinesCount
);

Parameters

updateLinesCount
True if number of lines in the document shall be calculated.

Remarks

This method will rebuild page layout of the document.

Example

Shows how to keep track of the word count.

[C#]

// Create an empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("This is the first line.");
builder.Writeln("This is the second line.");
builder.Writeln("These three lines contain eighteen words in total.");

// The fields that keep track of how many lines and words a document has are not automatically updated
// An empty document has one paragraph by default, which contains one empty line
Assert.AreEqual(0, doc.BuiltInDocumentProperties.Words);
Assert.AreEqual(1, doc.BuiltInDocumentProperties.Lines);

// To update them we have to use this method
// The default constructor updates just the word count
doc.UpdateWordCount();

Assert.AreEqual(18, doc.BuiltInDocumentProperties.Words);
Assert.AreEqual(1, doc.BuiltInDocumentProperties.Lines);

// If we want to update the line count as well, we have to use this overload
doc.UpdateWordCount(true);

Assert.AreEqual(18, doc.BuiltInDocumentProperties.Words);
Assert.AreEqual(3, doc.BuiltInDocumentProperties.Lines);

See Also

Document Class | Aspose.Words Namespace | Document.UpdateWordCount Overload List


DocumentBase Class

Provides the abstract base class for a main document and a glossary document of a Word document.

For a list of all members of this type, see DocumentBase Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.DocumentBase
Aspose.Words.BuildingBlocks.GlossaryDocument
Aspose.Words.Document

[Visual Basic]
MustInherit Public Class DocumentBase
Inherits CompositeNode
[C#]
public abstract class DocumentBase : CompositeNode

Remarks

Aspose.Words represents a Word document as a tree of nodes. DocumentBase is a root node of the tree that contains all other nodes of the document.

DocumentBase also stores document-wide information such as Styles and Lists that the tree nodes might refer to.

Example

Shows how to initialize the subclasses of DocumentBase.

[C#]

// DocumentBase is the abstract base class for the Document and GlossaryDocument classes
Document doc = new Document();

GlossaryDocument glossaryDoc = new GlossaryDocument();
doc.GlossaryDocument = glossaryDoc;

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocumentBase Members | Aspose.Words Namespace | Document | DocumentBase


DocumentBase Members

DocumentBase overview

Public Instance Properties

BackgroundShape | Gets or sets the background shape of the document. Can be null.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FontInfos | Provides access to properties of fonts used in this document.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Lists | Provides access to the list formatting used in the document.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeChangingCallback | Called when a node is inserted or removed in the document.
NodeType (inherited from Node) | Gets the type of this node.
PageColor | Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
ResourceLoadingCallback | Allows to control how external resources are loaded.
Styles | Returns a collection of styles defined in the document.
WarningCallback | Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
ImportNode | Overloaded. Imports a node from another document to the current document.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

DocumentBase Class | Aspose.Words Namespace | Document | DocumentBase


DocumentBase Properties

The properties of the DocumentBase class are listed below. For a complete list of DocumentBase class members, see the DocumentBase Members topic.

Public Instance Properties

BackgroundShape | Gets or sets the background shape of the document. Can be null.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FontInfos | Provides access to properties of fonts used in this document.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Lists | Provides access to the list formatting used in the document.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeChangingCallback | Called when a node is inserted or removed in the document.
NodeType (inherited from Node) | Gets the type of this node.
PageColor | Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
ResourceLoadingCallback | Allows to control how external resources are loaded.
Styles | Returns a collection of styles defined in the document.
WarningCallback | Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.

See Also

DocumentBase Class | Aspose.Words Namespace | Document | DocumentBase


BackgroundShape Property

Aspose.Words

DocumentBase.BackgroundShape Property

Gets or sets the background shape of the document. Can be null.

[Visual Basic]
Public Property BackgroundShape As Shape
[C#]
public Shape BackgroundShape {get; set;}

Remarks

Microsoft Word allows only a shape that has its ShapeType property equal to Rectangle to be used as a background shape for a document.

Microsoft Word supports only the fill properties of a background shape. All other properties are ignored.

Setting this property to a non-null value will also set the DisplayBackgroundShape to true.

Example

Shows how to set the background shape of a document.

[C#]

Document doc = new Document();
Assert.IsNull(doc.BackgroundShape);

// A background shape can only be a rectangle
// We will set the colour of this rectangle to light blue
Shape shapeRectangle = new Shape(doc, ShapeType.Rectangle);
doc.BackgroundShape = shapeRectangle;

// This rectangle covers the entire page in the output document
// We can also do this by setting doc.PageColor
shapeRectangle.FillColor = System.Drawing.Color.LightBlue;
doc.Save(ArtifactsDir + "DocumentBase.BackgroundShapeFlatColor.docx");

// Setting the image will override the flat background colour with the image
shapeRectangle.ImageData.SetImage(MyDir + "Images/Watermark.png");
Assert.IsTrue(doc.BackgroundShape.HasImage);

// This image is a photo with a white background
// To make it suitable as a watermark, we will need to do some image processing
// The default values for these variables are 0.5, so here we are lowering the contrast and increasing the brightness
shapeRectangle.ImageData.Contrast = 0.2;
shapeRectangle.ImageData.Brightness = 0.7;

// Microsoft Word does not support images in background shapes, so even though we set the background as an image,
// the output will show a light blue background like before
// However, we can see our watermark in an output pdf
doc.Save(ArtifactsDir + "DocumentBase.BackgroundShapeWatermark.pdf");

See Also

DocumentBase Class | Aspose.Words Namespace | DisplayBackgroundShape | PageColor


FontInfos Property

Aspose.Words

DocumentBase.FontInfos Property

Provides access to properties of fonts used in this document.

[Visual Basic]
Public ReadOnly Property FontInfos As FontInfoCollection
[C#]
public FontInfoCollection FontInfos {get;}

Remarks

This collection of font definitions is loaded as is from the document. Font definitions might be optional, missing or incomplete in some documents.

Do not rely on this collection to ascertain that a particular font is used in the document. You should only use this collection to get information about fonts that might be used in the document.

Example

Shows how to save a document with embedded TrueType fonts

[C#]

Document doc = new Document(MyDir + "Document.docx");

FontInfoCollection fontInfos = doc.FontInfos;
fontInfos.EmbedTrueTypeFonts = true;
fontInfos.EmbedSystemFonts = false;
fontInfos.SaveSubsetFonts = false;

doc.Save(ArtifactsDir + "Document.docx");
Shows how to gather the details of what fonts are present in a document.
[C#]

Document doc = new Document(MyDir + "Document.doc");

FontInfoCollection fonts = doc.FontInfos;
int fontIndex = 1;

// The fonts info extracted from this document does not necessarily mean that the fonts themselves are
// used in the document. If a font is present but not used then most likely they were referenced at some time
// and then removed from the Document.
foreach (FontInfo info in fonts)
{
    // Print out some important details about the font.
    Console.WriteLine("Font #{0}", fontIndex);
    Console.WriteLine("Name: {0}", info.Name);
    Console.WriteLine("IsTrueType: {0}", info.IsTrueType);
    fontIndex++;
}

See Also

DocumentBase Class | Aspose.Words Namespace | FontInfoCollection | FontInfo


Lists Property

Aspose.Words

DocumentBase.Lists Property

Provides access to the list formatting used in the document.

[Visual Basic]
Public ReadOnly Property Lists As ListCollection
[C#]
public ListCollection Lists {get;}

Remarks

For more information see the description of the ListCollection class.

Example

Shows how to specify list level number when building a list using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");

See Also

DocumentBase Class | Aspose.Words Namespace | ListCollection | List | ListFormat


NodeChangingCallback Property

Aspose.Words

DocumentBase.NodeChangingCallback Property

Called when a node is inserted or removed in the document.

[Visual Basic]
Public Property NodeChangingCallback As INodeChangingCallback
[C#]
public INodeChangingCallback NodeChangingCallback {get; set;}

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

See Also

DocumentBase Class | Aspose.Words Namespace


PageColor Property

Aspose.Words

DocumentBase.PageColor Property

Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.

[Visual Basic]
Public Property PageColor As Color
[C#]
public Color PageColor {get; set;}

Remarks

This property provides a simple way to specify a solid page color for the document. Setting this property creates and sets an appropriate BackgroundShape.

If the page color is not set (e.g. there is no background shape in the document) returns Empty.

Example

Shows how to set the page color.

[C#]

Document doc = new Document();

doc.PageColor = System.Drawing.Color.LightGray;

doc.Save(ArtifactsDir + "DocumentBase.SetPageColor.docx");

See Also

DocumentBase Class | Aspose.Words Namespace | BackgroundShape


ResourceLoadingCallback Property

Aspose.Words

DocumentBase.ResourceLoadingCallback Property

Allows to control how external resources are loaded.

[Visual Basic]
Public Property ResourceLoadingCallback As IResourceLoadingCallback
[C#]
public IResourceLoadingCallback ResourceLoadingCallback {get; set;}

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

See Also

DocumentBase Class | Aspose.Words Namespace


Styles Property

Aspose.Words

DocumentBase.Styles Property

Returns a collection of styles defined in the document.

[Visual Basic]
Public ReadOnly Property Styles As StyleCollection
[C#]
public StyleCollection Styles {get;}

Remarks

For more information see the description of the StyleCollection class.

Example

Shows how to get access to the collection of styles defined in the document.

[C#]

Document doc = new Document();
StyleCollection styles = doc.Styles;

foreach (Style style in styles)
    Console.WriteLine(style.Name);
Shows how to create and use a paragraph style with list formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

See Also

DocumentBase Class | Aspose.Words Namespace | StyleCollection | Style


WarningCallback Property

Aspose.Words

DocumentBase.WarningCallback Property

Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.

[Visual Basic]
Public Property WarningCallback As IWarningCallback
[C#]
public IWarningCallback WarningCallback {get; set;}

Remarks

Document may generate warnings at any stage of its existence, so it's important to setup warning callback as early as possible to avoid the warnings loss. E.g. such properties as PageCount actually build the document layout which is used later for rendering, and the layout warnings may be lost if warning callback is specified just for the rendering calls later.

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}
Demonstrates how to receive notifications of font substitutions by using IWarningCallback.
[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Document.doc");

// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;

// We can choose the default font to use in the case of any missing fonts.
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial";

// For testing we will set Aspose.Words to look for fonts only in a folder which doesn't exist. Since Aspose.Words won't
// find any fonts in the specified directory, then during rendering the fonts in the document will be substituted with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this substitution using our callback.
FontSettings.DefaultInstance.SetFontsFolder(String.Empty, false);

// Pass the save options along with the save path to the save method.
doc.Save(ArtifactsDir + "Rendering.MissingFontNotification.pdf");

See Also

DocumentBase Class | Aspose.Words Namespace


DocumentBase Methods

The methods of the DocumentBase class are listed below. For a complete list of DocumentBase class members, see the DocumentBase Members topic.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
ImportNode | Overloaded. Imports a node from another document to the current document.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

DocumentBase Class | Aspose.Words Namespace | Document | DocumentBase


ImportNode Method

Aspose.Words

DocumentBase.ImportNode Method

Imports a node from another document to the current document.

Overload List

Imports a node from another document to the current document.

public Node ImportNode(Node,bool);

Imports a node from another document to the current document with an option to control formatting.

public Node ImportNode(Node,bool,ImportFormatMode);

See Also

DocumentBase Class | Aspose.Words Namespace | NodeImporter


DocumentBase.ImportNode Method (Node, Boolean)

Imports a node from another document to the current document.

[Visual Basic]
Overloads Public Function ImportNode( _
ByVal srcNode As Node, _
ByVal isImportChildren As Boolean _
) As Node
[C#]
public Node ImportNode(
Node srcNode,
bool isImportChildren
);

Parameters

srcNode
The node being imported.
isImportChildren
True to import all child nodes recursively; otherwise, false.

Return Value

The cloned node that belongs to the current document.

Remarks

This method uses the UseDestinationStyles option to resolve formatting.

Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using InsertBefore or InsertAfter.

If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

Example

Shows how to import node from source document to destination document.

[C#]

Document src = new Document();
Document dst = new Document();

// Add text to both documents
src.FirstSection.Body.FirstParagraph.AppendChild(new Run(src, "Source document first paragraph text."));
dst.FirstSection.Body.FirstParagraph.AppendChild(new Run(dst,
    "Destination document first paragraph text."));

// If we want to add the section from doc2 to doc1, we can't just append them like this:
// dst.AppendChild(src.FirstSection);
// Uncommenting that line throws an exception because doc2's first section belongs to doc2,
// but each node in a document must belong to the document
Assert.AreNotEqual(dst, src.FirstSection.Document);

// We can create a new node that belongs to the destination document
Section importedSection = (Section) dst.ImportNode(src.FirstSection, true);

// It has the same content but it is not the same node nor do they have the same owner
Assert.AreNotEqual(importedSection, src.FirstSection);
Assert.AreNotEqual(importedSection.Document, src.FirstSection.Document);
Assert.AreEqual(importedSection.Body.FirstParagraph.GetText(),
    src.FirstSection.Body.FirstParagraph.GetText());

// Now it is ready to be placed in the document
dst.AppendChild(importedSection);

// Our document does indeed contain both the original and imported section
Assert.AreEqual("Destination document first paragraph text.\r\nSource document first paragraph text.\r\n",
    dst.ToString(SaveFormat.Text));

See Also

DocumentBase Class | Aspose.Words Namespace | DocumentBase.ImportNode Overload List | NodeImporter


DocumentBase.ImportNode Method (Node, Boolean, ImportFormatMode)

Imports a node from another document to the current document with an option to control formatting.

[Visual Basic]
Overloads Public Function ImportNode( _
ByVal srcNode As Node, _
ByVal isImportChildren As Boolean, _
ByVal importFormatMode As ImportFormatMode _
) As Node
[C#]
public Node ImportNode(
Node srcNode,
bool isImportChildren,
ImportFormatMode importFormatMode
);

Parameters

srcNode
The node to imported.
isImportChildren
True to import all child nodes recursively; otherwise, false.
importFormatMode
Specifies how to merge style formatting that clashes.

Return Value

The cloned, imported node. The node belongs to the destination document, but has no parent.

Remarks

This overload is useful to control how styles and list formatting are imported.

Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using InsertBefore or InsertAfter.

If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

Example

Shows how to import node from source document to destination document with specific options.

[C#]

// Create two documents with two styles that aren't the same but have the same name
Document src = new Document();
Style srcStyle = src.Styles.Add(StyleType.Character, "My style");
DocumentBuilder srcBuilder = new DocumentBuilder(src);
srcBuilder.Font.Style = srcStyle;
srcBuilder.Writeln("Source document text.");

Document dst = new Document();
Style dstStyle = dst.Styles.Add(StyleType.Character, "My style");
dstStyle.Font.Bold = true;
DocumentBuilder dstBuilder = new DocumentBuilder(dst);
dstBuilder.Font.Style = dstStyle;
srcBuilder.Writeln("Destination document text.");

dst.ImportNode(src.FirstSection, true, ImportFormatMode.UseDestinationStyles);

Assert.IsNull(dst.Styles["My style_0"]);

dst.ImportNode(src.FirstSection, true, ImportFormatMode.KeepDifferentStyles);

Assert.IsNotNull(dst.Styles["My style_0"]);

See Also

DocumentBase Class | Aspose.Words Namespace | DocumentBase.ImportNode Overload List | ImportFormatMode | NodeImporter


DocumentBuilder Class

Provides methods to insert text, images and other content, specify font, paragraph and section formatting.

For a list of all members of this type, see DocumentBuilder Members.

System.Object
Aspose.Words.DocumentBuilder

[Visual Basic]
Public Class DocumentBuilder
[C#]
public class DocumentBuilder

Remarks

DocumentBuilder makes the process of building a Document easier. Document is a composite object consisting of a tree of nodes and while inserting content nodes directly into the tree is possible, it requires good understanding of the tree structure. DocumentBuilder is a "facade" for the complex structure of Document and allows to insert content and formatting quickly and easily.

Create a DocumentBuilder and associate it with a Document.

The DocumentBuilder has an internal cursor where the text will be inserted when you call Write, Writeln, InsertBreak and other methods. You can navigate the DocumentBuilder cursor to a different location in a document using various MoveToXXX methods.

Use the Font property to specify character formatting that will apply to all text inserted from the current position in the document onwards.

Use the ParagraphFormat property to specify paragraph formatting for the current and all paragraphs that will be inserted.

Use the PageSetup property to specify page and section properties for the current section and all section that will be inserted.

Use the CellFormat and RowFormat properties to specify formatting properties for table cells and rows. User the InsertCell and EndRow methods to build a table.

Note that Font, ParagraphFormat and PageSetup properties are updated whenever you navigate to a different place in the document to reflect formatting properties available at the new location.

Example

Adds some text into the document and encloses the text in a bookmark using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.StartBookmark("MyBookmark");
builder.Writeln("Text inside a bookmark.");
builder.EndBookmark("MyBookmark");
Inserts HTML into a document. The formatting specified in the HTML is applied.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

string html = "<P align='right'>Paragraph right</P>" + "<b>Implicit paragraph left</b>" +
              "<div align='center'>Div center</div>" + "<h1 align='left'>Heading 1 left.</h1>";

builder.InsertHtml(html);

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHtml.doc");
Shows how to create a simple table using DocumentBuilder with default formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// We call this method to start building the table.
builder.StartTable();
builder.InsertCell();
builder.Write("Row 1, Cell 1 Content.");

// Build the second cell
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.EndRow();

// Build the first cell of the second row.
builder.InsertCell();
builder.Write("Row 2, Cell 1 Content");

// Build the second cell.
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content.");
builder.EndRow();

// Signal that we have finished building the table.
builder.EndTable();

// Save the document to disk.
doc.Save(ArtifactsDir + "DocumentBuilder.CreateSimpleTable.doc");
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocumentBuilder Members | Aspose.Words Namespace


DocumentBuilder Members

DocumentBuilder overview

Public Instance Constructors

DocumentBuilder Overloaded. Initializes a new instance of the DocumentBuilder class.

Public Instance Properties

Bold | True if the font is formatted as bold.
CellFormat | Returns an object that represents current table cell formatting properties.
CurrentNode | Gets the node that is currently selected in this DocumentBuilder.
CurrentParagraph | Gets the paragraph that is currently selected in this DocumentBuilder.
CurrentSection | Gets the section that is currently selected in this DocumentBuilder.
CurrentStory | Gets the story that is currently selected in this DocumentBuilder.
Document | Gets or sets the Document object that this object is attached to.
Font | Returns an object that represents current font formatting properties.
IsAtEndOfParagraph | Returns true if the cursor is at the end of the current paragraph.
IsAtStartOfParagraph | Returns true if the cursor is at the beginning of the current paragraph (no text before the cursor).
Italic | True if the font is formatted as italic.
ListFormat | Returns an object that represents current list formatting properties.
PageSetup | Returns an object that represents current page setup and section properties.
ParagraphFormat | Returns an object that represents current paragraph formatting properties.
RowFormat | Returns an object that represents current table row formatting properties.
Underline | Gets/sets underline type for the current font.

Public Instance Methods

DeleteRow | Deletes a row from a table.
EndBookmark | Marks the current position in the document as a bookmark end.
EndEditableRange | Overloaded. Marks the current position in the document as an editable range end.
EndRow | Ends a table row in the document.
EndTable | Ends a table in the document.
InsertBreak | Inserts a break of the specified type into the document.
InsertCell | Inserts a table cell into the document.
InsertChart | Overloaded. Inserts an chart object into the document and scales it to the specified size.
InsertCheckBox | Overloaded. Inserts a checkbox form field at the current position.
InsertComboBox | Inserts a combobox form field at the current position.
InsertDocument | Overloaded. Inserts a document at the cursor position.
InsertField | Overloaded. Inserts a Word field into a document.
InsertFootnote | Overloaded. Inserts a footnote or endnote into the document.
InsertHorizontalRule | Inserts a horizontal rule shape into the document.
InsertHtml | Overloaded. Inserts an HTML string into the document.
InsertHyperlink | Inserts a hyperlink into the document.
InsertImage | Overloaded. Inserts an image into the document.
InsertNode | Inserts a text level node inside the current paragraph before the cursor.
InsertOleObject | Overloaded. Inserts an embedded OLE object from a stream into the document.
InsertOnlineVideo | Overloaded. Inserts an online video object into the document and scales it to the specified size.
InsertParagraph | Inserts a paragraph break into the document.
InsertShape | Overloaded. Inserts inline shape with specified type and size.
InsertSignatureLine | Overloaded. Inserts a signature line at the current position.
InsertStyleSeparator | Inserts style separator into the document.
InsertTableOfContents | Inserts a TOC (table of contents) field into the document.
InsertTextInput | Inserts a text form field at the current position.
MoveTo | Moves the cursor to an inline node or to the end of a paragraph.
MoveToBookmark | Overloaded. Moves the cursor to a bookmark.
MoveToCell | Moves the cursor to a table cell in the current section.
MoveToDocumentEnd | Moves the cursor to the end of the document.
MoveToDocumentStart | Moves the cursor to the beginning of the document.
MoveToField | Moves the cursor to a field in the document.
MoveToHeaderFooter | Moves the cursor to the beginning of a header or footer in the current section.
MoveToMergeField | Overloaded. Moves the cursor to the specified merge field.
MoveToParagraph | Moves the cursor to a paragraph in the current section.
MoveToSection | Moves the cursor to the beginning of the body in a specified section.
PopFont | Retrieves character formatting previously saved on the stack.
PushFont | Saves current character formatting onto the stack.
StartBookmark | Marks the current position in the document as a bookmark start.
StartEditableRange | Marks the current position in the document as an editable range start.
StartTable | Starts a table in the document.
Write | Inserts a string into the document at the current insert position.
Writeln | Overloaded. Inserts a string and a paragraph break into the document.

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder Constructor

Initializes a new instance of this class.

Overload List

Initializes a new instance of this class.

public DocumentBuilder();

Initializes a new instance of this class.

public DocumentBuilder(Document);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder Constructor ()

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New()
[C#]
public DocumentBuilder();

Remarks

Creates a new DocumentBuilder object and attaches it to a new Document object.

Example

Inserts formatted text using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Specify font formatting before adding text.
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

builder.Write("Sample text.");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder Constructor Overload List


DocumentBuilder Constructor (Document)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As Document _
)
[C#]
public DocumentBuilder(
Document doc
);

Parameters

doc
The Document object to attach to.

Remarks

Creates a new DocumentBuilder object, attaches to the specified Document object. The cursor is positioned at the beginning of the document.

Example

Creates headers and footers in a document using DocumentBuilder.

[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");
Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.
[C#]

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 2");
builder.Writeln("Heading 3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");

// Call the method below to update the TOC.
doc.UpdateFields();

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder Constructor Overload List


DocumentBuilder Properties

The properties of the DocumentBuilder class are listed below. For a complete list of DocumentBuilder class members, see the DocumentBuilder Members topic.

Public Instance Properties

Bold | True if the font is formatted as bold.
CellFormat | Returns an object that represents current table cell formatting properties.
CurrentNode | Gets the node that is currently selected in this DocumentBuilder.
CurrentParagraph | Gets the paragraph that is currently selected in this DocumentBuilder.
CurrentSection | Gets the section that is currently selected in this DocumentBuilder.
CurrentStory | Gets the story that is currently selected in this DocumentBuilder.
Document | Gets or sets the Document object that this object is attached to.
Font | Returns an object that represents current font formatting properties.
IsAtEndOfParagraph | Returns true if the cursor is at the end of the current paragraph.
IsAtStartOfParagraph | Returns true if the cursor is at the beginning of the current paragraph (no text before the cursor).
Italic | True if the font is formatted as italic.
ListFormat | Returns an object that represents current list formatting properties.
PageSetup | Returns an object that represents current page setup and section properties.
ParagraphFormat | Returns an object that represents current paragraph formatting properties.
RowFormat | Returns an object that represents current table row formatting properties.
Underline | Gets/sets underline type for the current font.

See Also

DocumentBuilder Class | Aspose.Words Namespace


Bold Property

Aspose.Words

DocumentBuilder.Bold Property

True if the font is formatted as bold.

[Visual Basic]
Public Property Bold As Boolean
[C#]
public bool Bold {get; set;}

Example

Fills document merge fields with some data.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.FillingDocument.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToMergeField("TeamLeaderName");
builder.Bold = true;
builder.Writeln("Roman Korchagin");

builder.MoveToMergeField("SoftwareDeveloper1Name");
builder.Italic = true;
builder.Writeln("Dmitry Vorobyev");

builder.MoveToMergeField("SoftwareDeveloper2Name");
builder.Italic = true;
builder.Writeln("Vladimir Averkin");

doc.Save(ArtifactsDir + "DocumentBuilder.FillingDocument.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


CellFormat Property

Aspose.Words

DocumentBuilder.CellFormat Property

Returns an object that represents current table cell formatting properties.

[Visual Basic]
Public ReadOnly Property CellFormat As CellFormat
[C#]
public CellFormat CellFormat {get;}

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

DocumentBuilder Class | Aspose.Words Namespace


CurrentNode Property

Aspose.Words

DocumentBuilder.CurrentNode Property

Gets the node that is currently selected in this DocumentBuilder.

[Visual Basic]
Public ReadOnly Property CurrentNode As Node
[C#]
public Node CurrentNode {get;}

Remarks

CurrentNode is a cursor of DocumentBuilder and points to a Node that is a direct child of a Paragraph. Any insert operations you perform using DocumentBuilder will insert before the CurrentNode.

When the current paragraph is empty or the cursor is positioned just before the end of the paragraph, CurrentNode returns null.

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | CurrentParagraph


CurrentParagraph Property

Aspose.Words

DocumentBuilder.CurrentParagraph Property

Gets the paragraph that is currently selected in this DocumentBuilder.

[Visual Basic]
Public ReadOnly Property CurrentParagraph As Paragraph
[C#]
public Paragraph CurrentParagraph {get;}

Remarks

CurrentNode

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


CurrentSection Property

Aspose.Words

DocumentBuilder.CurrentSection Property

Gets the section that is currently selected in this DocumentBuilder.

[Visual Basic]
Public ReadOnly Property CurrentSection As Section
[C#]
public Section CurrentSection {get;}

Example

Shows how to insert a floating image and specify its position and size.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace


CurrentStory Property

Aspose.Words

DocumentBuilder.CurrentStory Property

Gets the story that is currently selected in this DocumentBuilder.

[Visual Basic]
Public ReadOnly Property CurrentStory As Story
[C#]
public Story CurrentStory {get;}

Example

Shows how to work with a document builder's current story.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The body of the current section is the same object as the current story
Assert.AreEqual(builder.CurrentStory, doc.FirstSection.Body);
Assert.AreEqual(builder.CurrentStory, builder.CurrentParagraph.ParentNode);

Assert.AreEqual(StoryType.MainText, builder.CurrentStory.StoryType);

builder.CurrentStory.AppendParagraph("Text added to current Story.");

// A story can contain tables too
Table table = builder.StartTable();

builder.InsertCell();
builder.Write("This is row 1 cell 1");
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

builder.InsertCell();
builder.Writeln("This is row 2 cell 1");
builder.InsertCell();
builder.Writeln("This is row 2 cell 2");

builder.EndRow();
builder.EndTable();

// The table we just made is automatically placed in the story
Assert.IsTrue(builder.CurrentStory.Tables.Contains(table));

doc.Save(ArtifactsDir + "DocumentBuilder.CurrentStory.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace


Document Property

Aspose.Words

DocumentBuilder.Document Property

Gets or sets the Document object that this object is attached to.

[Visual Basic]
Public Property Document As Document
[C#]
public Document Document {get; set;}

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


Font Property

Aspose.Words

DocumentBuilder.Font Property

Returns an object that represents current font formatting properties.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Remarks

Use Font to access and modify font formatting properties.

Specify font formatting before inserting text.

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


IsAtEndOfParagraph Property

Aspose.Words

DocumentBuilder.IsAtEndOfParagraph Property

Returns true if the cursor is at the end of the current paragraph.

[Visual Basic]
Public ReadOnly Property IsAtEndOfParagraph As Boolean
[C#]
public bool IsAtEndOfParagraph {get;}

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


IsAtStartOfParagraph Property

Aspose.Words

DocumentBuilder.IsAtStartOfParagraph Property

Returns true if the cursor is at the beginning of the current paragraph (no text before the cursor).

[Visual Basic]
Public ReadOnly Property IsAtStartOfParagraph As Boolean
[C#]
public bool IsAtStartOfParagraph {get;}

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


Italic Property

Aspose.Words

DocumentBuilder.Italic Property

True if the font is formatted as italic.

[Visual Basic]
Public Property Italic As Boolean
[C#]
public bool Italic {get; set;}

Example

Fills document merge fields with some data.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.FillingDocument.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToMergeField("TeamLeaderName");
builder.Bold = true;
builder.Writeln("Roman Korchagin");

builder.MoveToMergeField("SoftwareDeveloper1Name");
builder.Italic = true;
builder.Writeln("Dmitry Vorobyev");

builder.MoveToMergeField("SoftwareDeveloper2Name");
builder.Italic = true;
builder.Writeln("Vladimir Averkin");

doc.Save(ArtifactsDir + "DocumentBuilder.FillingDocument.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


ListFormat Property

Aspose.Words

DocumentBuilder.ListFormat Property

Returns an object that represents current list formatting properties.

[Visual Basic]
Public ReadOnly Property ListFormat As ListFormat
[C#]
public ListFormat ListFormat {get;}

Example

Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln("Aspose.Words allows:");
builder.Writeln();

// Start a numbered list with default formatting.
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Opening documents from different formats:");

// Go to second list level, add more text.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");

// Outdent to the first list level.
builder.ListFormat.ListOutdent();
builder.Writeln("Processing documents");
builder.Writeln("Saving documents in different formats:");

// Indent the list level again.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");
builder.Writeln("MHTML");
builder.Writeln("Plain text");

// Outdent the list level again.
builder.ListFormat.ListOutdent();
builder.Writeln("Doing many other things!");

// End the numbered list.
builder.ListFormat.RemoveNumbers();
builder.Writeln();

builder.Writeln("Aspose.Words main advantages are:");
builder.Writeln();

// Start a bulleted list with default formatting.
builder.ListFormat.ApplyBulletDefault();
builder.Writeln("Great performance");
builder.Writeln("High reliability");
builder.Writeln("Quality code and working");
builder.Writeln("Wide variety of features");
builder.Writeln("Easy to understand API");

// End the bulleted list.
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.ApplyDefaultBulletsAndNumbers.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


PageSetup Property

Aspose.Words

DocumentBuilder.PageSetup Property

Returns an object that represents current page setup and section properties.

[Visual Basic]
Public ReadOnly Property PageSetup As PageSetup
[C#]
public PageSetup PageSetup {get;}

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


ParagraphFormat Property

Aspose.Words

DocumentBuilder.ParagraphFormat Property

Returns an object that represents current paragraph formatting properties.

[Visual Basic]
Public ReadOnly Property ParagraphFormat As ParagraphFormat
[C#]
public ParagraphFormat ParagraphFormat {get;}

Example

Shows how to create a formatted table using DocumentBuilder

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


RowFormat Property

Aspose.Words

DocumentBuilder.RowFormat Property

Returns an object that represents current table row formatting properties.

[Visual Basic]
Public ReadOnly Property RowFormat As RowFormat
[C#]
public RowFormat RowFormat {get;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

DocumentBuilder Class | Aspose.Words Namespace


Underline Property

Aspose.Words

DocumentBuilder.Underline Property

Gets/sets underline type for the current font.

[Visual Basic]
Public Property Underline As Underline
[C#]
public Underline Underline {get; set;}

Example

Shows how to set and edit a document builder's underline.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set a new style for our underline
builder.Underline = Underline.Dash;

// Same object as DocumentBuilder.Font.Underline
Assert.AreEqual(builder.Underline, builder.Font.Underline);
Assert.AreEqual(Underline.Dash, builder.Font.Underline);

// These properties will be applied to the underline as well
builder.Font.Color = Color.Blue;
builder.Font.Size = 32;

builder.Writeln("Underlined text.");

doc.Save(ArtifactsDir + "DocumentBuilder.Underline.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder Methods

The methods of the DocumentBuilder class are listed below. For a complete list of DocumentBuilder class members, see the DocumentBuilder Members topic.

Public Instance Methods

DeleteRow | Deletes a row from a table.
EndBookmark | Marks the current position in the document as a bookmark end.
EndEditableRange | Overloaded. Marks the current position in the document as an editable range end.
EndRow | Ends a table row in the document.
EndTable | Ends a table in the document.
InsertBreak | Inserts a break of the specified type into the document.
InsertCell | Inserts a table cell into the document.
InsertChart | Overloaded. Inserts an chart object into the document and scales it to the specified size.
InsertCheckBox | Overloaded. Inserts a checkbox form field at the current position.
InsertComboBox | Inserts a combobox form field at the current position.
InsertDocument | Overloaded. Inserts a document at the cursor position.
InsertField | Overloaded. Inserts a Word field into a document.
InsertFootnote | Overloaded. Inserts a footnote or endnote into the document.
InsertHorizontalRule | Inserts a horizontal rule shape into the document.
InsertHtml | Overloaded. Inserts an HTML string into the document.
InsertHyperlink | Inserts a hyperlink into the document.
InsertImage | Overloaded. Inserts an image into the document.
InsertNode | Inserts a text level node inside the current paragraph before the cursor.
InsertOleObject | Overloaded. Inserts an embedded OLE object from a stream into the document.
InsertOnlineVideo | Overloaded. Inserts an online video object into the document and scales it to the specified size.
InsertParagraph | Inserts a paragraph break into the document.
InsertShape | Overloaded. Inserts inline shape with specified type and size.
InsertSignatureLine | Overloaded. Inserts a signature line at the current position.
InsertStyleSeparator | Inserts style separator into the document.
InsertTableOfContents | Inserts a TOC (table of contents) field into the document.
InsertTextInput | Inserts a text form field at the current position.
MoveTo | Moves the cursor to an inline node or to the end of a paragraph.
MoveToBookmark | Overloaded. Moves the cursor to a bookmark.
MoveToCell | Moves the cursor to a table cell in the current section.
MoveToDocumentEnd | Moves the cursor to the end of the document.
MoveToDocumentStart | Moves the cursor to the beginning of the document.
MoveToField | Moves the cursor to a field in the document.
MoveToHeaderFooter | Moves the cursor to the beginning of a header or footer in the current section.
MoveToMergeField | Overloaded. Moves the cursor to the specified merge field.
MoveToParagraph | Moves the cursor to a paragraph in the current section.
MoveToSection | Moves the cursor to the beginning of the body in a specified section.
PopFont | Retrieves character formatting previously saved on the stack.
PushFont | Saves current character formatting onto the stack.
StartBookmark | Marks the current position in the document as a bookmark start.
StartEditableRange | Marks the current position in the document as an editable range start.
StartTable | Starts a table in the document.
Write | Inserts a string into the document at the current insert position.
Writeln | Overloaded. Inserts a string and a paragraph break into the document.

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.DeleteRow Method

Deletes a row from a table.

[Visual Basic]
Public Function DeleteRow( _
ByVal tableIndex As Integer, _
ByVal rowIndex As Integer _
) As Row
[C#]
public Row DeleteRow(
int tableIndex,
int rowIndex
);

Parameters

tableIndex
The index of the table.
rowIndex
The index of the row in the table.

Return Value

The row node that was just removed.

Remarks

If the cursor is inside the row that is being deleted, the cursor is moved out to the next row or to the next paragraph after the table.

If you delete a row from a table that contains only one row, the whole table is deleted.

For the index parameters, when index is greater than or equal to 0, it specifies an index from the beginning with 0 being the first element. When index is less than 0, it specified an index from the end with -1 being the last element.

Example

Shows how to delete a row from a table.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.DocWithTable.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Delete the first row of the first table in the document.
builder.DeleteRow(0, 0);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.EndBookmark Method

Marks the current position in the document as a bookmark end.

[Visual Basic]
Public Function EndBookmark( _
ByVal bookmarkName As String _
) As BookmarkEnd
[C#]
public BookmarkEnd EndBookmark(
string bookmarkName
);

Parameters

bookmarkName
Name of the bookmark.

Return Value

The bookmark end node that was just created.

Remarks

Bookmarks in a document can overlap and span any range. To create a valid bookmark you need to call both StartBookmark and EndBookmark with the same bookmarkName parameter.

Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

Example

Adds some text into the document and encloses the text in a bookmark using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.StartBookmark("MyBookmark");
builder.Writeln("Text inside a bookmark.");
builder.EndBookmark("MyBookmark");
Inserts a hyperlink referencing local bookmark.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartBookmark("Bookmark1");
builder.Write("Bookmarked text.");
builder.EndBookmark("Bookmark1");

builder.Writeln("Some other text");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;

// Insert hyperlink.
// Switch \o is used to provide hyperlink tip text.
builder.InsertHyperlink("Hyperlink Text", @"Bookmark1"" \o ""Hyperlink Tip", true);

// Clear hyperlink formatting.
builder.Font.ClearFormatting();

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlinkToLocalBookmark.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


EndEditableRange Method

Aspose.Words

DocumentBuilder.EndEditableRange Method

Marks the current position in the document as an editable range end.

Overload List

Marks the current position in the document as an editable range end.

public EditableRangeEnd EndEditableRange();

Marks the current position in the document as an editable range end.

public EditableRangeEnd EndEditableRange(EditableRangeStart);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.EndEditableRange Method ()

Marks the current position in the document as an editable range end.

[Visual Basic]
Overloads Public Function EndEditableRange() As EditableRangeEnd
[C#]
public EditableRangeEnd EndEditableRange();

Return Value

The editable range end node that was just created.

Remarks

Editable range in a document can overlap and span any range. To create a valid editable range you need to call both StartEditableRange and EndEditableRange or EndEditableRange methods.

Badly formed editable range will be ignored when the document is saved.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.EndEditableRange Overload List


DocumentBuilder.EndEditableRange Method (EditableRangeStart)

Marks the current position in the document as an editable range end.

[Visual Basic]
Overloads Public Function EndEditableRange( _
ByVal start As EditableRangeStart _
) As EditableRangeEnd
[C#]
public EditableRangeEnd EndEditableRange(
EditableRangeStart start
);

Parameters

start
This editable range start.

Return Value

The editable range end node that was just created.

Remarks

Use this overload during creating nested editable ranges.

Editable range in a document can overlap and span any range. To create a valid editable range you need to call both StartEditableRange and EndEditableRange or EndEditableRange methods.

Badly formed editable range will be ignored when the document is saved.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.EndEditableRange Overload List


DocumentBuilder.EndRow Method

Ends a table row in the document.

[Visual Basic]
Public Function EndRow() As Row
[C#]
public Row EndRow();

Return Value

The row node that was just finished.

Remarks

Call EndRow to end a table row. If you call InsertCell immediately after that, then the table continues on a new row.

Use the RowFormat property to specify row formatting.

Example

Creates a table with two columns with cells merged vertically in the first column.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in one cell");
builder.EndRow();

builder.InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in another cell");
builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.EndTable Method

Ends a table in the document.

[Visual Basic]
Public Function EndTable() As Table
[C#]
public Table EndTable();

Return Value

The table node that was just finished.

Remarks

This method should be called only once after EndRow was called. When called, EndTable moves the cursor out of the current cell to point just after the table.

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertBreak Method

Inserts a break of the specified type into the document.

[Visual Basic]
Public Sub InsertBreak( _
ByVal breakType As BreakType _
)
[C#]
public void InsertBreak(
BreakType breakType
);

Parameters

breakType
Specifies the type of the break to insert.

Remarks

Use this method to insert paragraph, page, column, section or line break into the document.

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");
Creates headers and footers in a document using DocumentBuilder.
[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");
Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.
[C#]

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 2");
builder.Writeln("Heading 3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");

// Call the method below to update the TOC.
doc.UpdateFields();

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertCell Method

Inserts a table cell into the document.

[Visual Basic]
Public Function InsertCell() As Cell
[C#]
public Cell InsertCell();

Return Value

The cell node that was just inserted.

Remarks

To start a table, just call InsertCell. After this, any content you add using other methods of the DocumentBuilder class will be added to the current cell.

To start a new cell in the same row, call InsertCell again.

To end a table row call EndRow.

Use the CellFormat property to specify cell formatting.

Example

Creates a table with two columns with cells merged vertically in the first column.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in one cell");
builder.EndRow();

builder.InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in another cell");
builder.EndRow();
builder.EndTable();
Shows how to create a simple table using DocumentBuilder with default formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// We call this method to start building the table.
builder.StartTable();
builder.InsertCell();
builder.Write("Row 1, Cell 1 Content.");

// Build the second cell
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.EndRow();

// Build the first cell of the second row.
builder.InsertCell();
builder.Write("Row 2, Cell 1 Content");

// Build the second cell.
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content.");
builder.EndRow();

// Signal that we have finished building the table.
builder.EndTable();

// Save the document to disk.
doc.Save(ArtifactsDir + "DocumentBuilder.CreateSimpleTable.doc");
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertChart Method

Aspose.Words

DocumentBuilder.InsertChart Method

Inserts an chart object into the document and scales it to the specified size.

Overload List

Inserts an chart object into the document and scales it to the specified size.

public Shape InsertChart(ChartType,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an chart object into the document and scales it to the specified size.

public Shape InsertChart(ChartType,double,double);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertChart Method (ChartType, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an chart object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertChart( _
ByVal chartType As ChartType, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertChart(
ChartType chartType,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

chartType
The chart type to insert into the document.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows how to insert a chart into a document and specify position and size.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertChart(ChartType.Pie, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
    100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "Document.InsertedChartRelativePosition.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertChart Overload List


DocumentBuilder.InsertChart Method (ChartType, Double, Double)

Inserts an chart object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertChart( _
ByVal chartType As ChartType, _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertChart(
ChartType chartType,
double width,
double height
);

Parameters

chartType
The chart type to insert into the document.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows how to insert a chart into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertChart(ChartType.Pie, ConvertUtil.PixelToPoint(300), ConvertUtil.PixelToPoint(300));

doc.Save(ArtifactsDir + "Document.InsertedChartDouble.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertChart Overload List


InsertCheckBox Method

Aspose.Words

DocumentBuilder.InsertCheckBox Method

Inserts a checkbox form field at the current position.

Overload List

Inserts a checkbox form field at the current position.

public FormField InsertCheckBox(string,bool,bool,int);

Inserts a checkbox form field at the current position.

public FormField InsertCheckBox(string,bool,int);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertCheckBox Method (String, Boolean, Boolean, Int32)

Inserts a checkbox form field at the current position.

[Visual Basic]
Overloads Public Function InsertCheckBox( _
ByVal name As String, _
ByVal defaultValue As Boolean, _
ByVal checkedValue As Boolean, _
ByVal size As Integer _
) As FormField
[C#]
public FormField InsertCheckBox(
string name,
bool defaultValue,
bool checkedValue,
int size
);

Parameters

name
The name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.
defaultValue
Default value of the checkbox form field.
checkedValue
Current checked status of the checkbox form field.
size
Specifies the size of the checkbox in points. Specify 0 for MS Word to calculate the size of the checkbox automatically.

Return Value

The form field node that was just inserted.

Remarks

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Example

Shows how to insert checkboxes to the document

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCheckBox(String.Empty, false, false, 0);
builder.InsertCheckBox("CheckBox_Default", true, true, 50);
builder.InsertCheckBox("CheckBox_OnlyCheckedValue", true, 100);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertCheckBox Overload List


DocumentBuilder.InsertCheckBox Method (String, Boolean, Int32)

Inserts a checkbox form field at the current position.

[Visual Basic]
Overloads Public Function InsertCheckBox( _
ByVal name As String, _
ByVal checkedValue As Boolean, _
ByVal size As Integer _
) As FormField
[C#]
public FormField InsertCheckBox(
string name,
bool checkedValue,
int size
);

Parameters

name
The name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.
checkedValue
Checked status of the checkbox form field.
size
Specifies the size of the checkbox in points. Specify 0 for MS Word to calculate the size of the checkbox automatically.

Return Value

The form field node that was just inserted.

Remarks

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Example

Shows how to insert checkboxes to the document

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCheckBox(String.Empty, false, false, 0);
builder.InsertCheckBox("CheckBox_Default", true, true, 50);
builder.InsertCheckBox("CheckBox_OnlyCheckedValue", true, 100);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertCheckBox Overload List


DocumentBuilder.InsertComboBox Method

Inserts a combobox form field at the current position.

[Visual Basic]
Public Function InsertComboBox( _
ByVal name As String, _
ByVal items As String(), _
ByVal selectedIndex As Integer _
) As FormField
[C#]
public FormField InsertComboBox(
string name,
string[] items,
int selectedIndex
);

Parameters

name
The name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.
items
The items of the ComboBox. Maximum is 25 items.
selectedIndex
The index of the selected item in the ComboBox.

Return Value

The form field node that was just inserted.

Remarks

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Example

Shows how to insert a combobox form field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

String[] items = { "One", "Two", "Three" };
builder.InsertComboBox("DropDown", items, 0);
Builds a sample form to fill.
[C#]

DocumentBuilder builder = new DocumentBuilder();

// Insert a text form field for input a name.
builder.InsertTextInput("", TextFormFieldType.Regular, "", "Enter your name here", 30);

// Insert two blank lines.
builder.Writeln("");
builder.Writeln("");

string[] items =
{
    "-- Select your favorite footwear --", "Sneakers", "Oxfords", "Flip-flops", "Other",
    "I prefer to be barefoot"
};

// Insert a combo box to select a footwear type.
builder.InsertComboBox("", items, 0);

// Insert 2 blank lines.
builder.Writeln("");
builder.Writeln("");

builder.Document.Save(ArtifactsDir + "DocumentBuilder.CreateForm.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertDocument Method

Aspose.Words

DocumentBuilder.InsertDocument Method

Inserts a document at the cursor position.

Overload List

Inserts a document at the cursor position.

public Node InsertDocument(Document,ImportFormatMode);

Inserts a document at the cursor position.

public Node InsertDocument(Document,ImportFormatMode,ImportFormatOptions);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertDocument Method (Document, ImportFormatMode)

Inserts a document at the cursor position.

[Visual Basic]
Overloads Public Function InsertDocument( _
ByVal srcDoc As Document, _
ByVal importFormatMode As ImportFormatMode _
) As Node
[C#]
public Node InsertDocument(
Document srcDoc,
ImportFormatMode importFormatMode
);

Parameters

srcDoc
Source document for inserting.
importFormatMode
Specifies how to merge style formatting that clashes.

Return Value

First node of the inserted content.

Remarks

This method mimics the MS Word behavior, as if CTRL+'A' (select all content) was pressed, then CTRL+'C' (copy selected into the buffer) inside one document and then CTRL+'V' (insert content from the buffer) inside another document.

Example

Shows how to insert a document content into another document keep formatting of inserted document.

[C#]

Document doc = new Document(MyDir + "Document.docx");

DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);

Document docToInsert = new Document(MyDir + "DocumentBuilder.KeepSourceFormatting.docx");

builder.InsertDocument(docToInsert, ImportFormatMode.KeepSourceFormatting);
builder.Document.Save(ArtifactsDir + "DocumentBuilder.InsertDocument.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertDocument Overload List


DocumentBuilder.InsertDocument Method (Document, ImportFormatMode, ImportFormatOptions)

Inserts a document at the cursor position.

[Visual Basic]
Overloads Public Function InsertDocument( _
ByVal srcDoc As Document, _
ByVal importFormatMode As ImportFormatMode, _
ByVal importFormatOptions As ImportFormatOptions _
) As Node
[C#]
public Node InsertDocument(
Document srcDoc,
ImportFormatMode importFormatMode,
ImportFormatOptions importFormatOptions
);

Parameters

srcDoc
Source document for inserting.
importFormatMode
Specifies how to merge style formatting that clashes.
importFormatOptions
Allows to specify options that affect formatting of a result document.

Return Value

First node of the inserted content.

Remarks

This method mimics the MS Word behavior, as if CTRL+'A' (select all content) was pressed, then CTRL+'C' (copy selected into the buffer) inside one document and then CTRL+'V' (insert content from the buffer) inside another document.

Example

Shows how to resolve styles behavior while inserting documents.

[C#]

Document destDoc = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.DestinationDocument.docx");
Document sourceDoc1 = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.SourceDocument01.docx");
Document sourceDoc2 = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.SourceDocument02.docx");

DocumentBuilder builder = new DocumentBuilder(destDoc);

builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);
builder.MoveToDocumentEnd();

ImportFormatOptions importFormatOptions = new ImportFormatOptions();
importFormatOptions.SmartStyleBehavior = true;

// When SmartStyleBehavior is enabled,
// a source style will be expanded into a direct attributes inside a destination document,
// if KeepSourceFormatting importing mode is used.
builder.InsertDocument(sourceDoc1, ImportFormatMode.KeepSourceFormatting, importFormatOptions);

builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);

// When SmartStyleBehavior is disabled,
// a source style will be expanded only if it is numbered.
// Existing destination attributes will not be overridden, including lists.
builder.InsertDocument(sourceDoc2, ImportFormatMode.UseDestinationStyles);

destDoc.Save(ArtifactsDir + @"DocumentBuilder.SmartStyleBehavior.ResultDocument.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertDocument Overload List


InsertField Method

Aspose.Words

DocumentBuilder.InsertField Method

Inserts a Word field into a document.

Overload List

Inserts a Word field into a document and optionally updates the field result.

public Field InsertField(FieldType,bool);

Inserts a Word field into a document and updates the field result.

public Field InsertField(string);

Inserts a Word field into a document without updating the field result.

public Field InsertField(string,string);

See Also

DocumentBuilder Class | Aspose.Words Namespace | Field


DocumentBuilder.InsertField Method (FieldType, Boolean)

Inserts a Word field into a document and optionally updates the field result.

[Visual Basic]
Overloads Public Function InsertField( _
ByVal fieldType As FieldType, _
ByVal updateField As Boolean _
) As Field
[C#]
public Field InsertField(
FieldType fieldType,
bool updateField
);

Parameters

fieldType
The type of the field to append.
updateField
Specifies whether to update the field immediately.

Return Value

A Field object that represents the inserted field.

Remarks

This method inserts a field into a document. Aspose.Words can update fields of most types, but not all. For more details see the InsertField overload.

Example

Shows how to insert a field into a document using FieldType

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This field was inserted/updated at ");
builder.InsertField(FieldType.FieldTime, true);

doc.Save(ArtifactsDir + "Document.InsertedField.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertField Overload List | Field


DocumentBuilder.InsertField Method (String)

Inserts a Word field into a document and updates the field result.

[Visual Basic]
Overloads Public Function InsertField( _
ByVal fieldCode As String _
) As Field
[C#]
public Field InsertField(
string fieldCode
);

Parameters

fieldCode
The field code to insert (without curly braces).

Return Value

A Field object that represents the inserted field.

Remarks

This method inserts a field into a document and updates the field result immediately. Aspose.Words can update fields of most types, but not all. For more details see the InsertField overload.

Example

Shows how to insert merge fields and move between them.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField(@"MERGEFIELD MyMergeField1 \* MERGEFORMAT");
builder.InsertField(@"MERGEFIELD MyMergeField2 \* MERGEFORMAT");

Assert.AreEqual(2, doc.Range.Fields.Count);

// The second merge field starts immediately after the end of the first
// We'll move the builder's cursor to the end of the first so we can split them by text
builder.MoveToMergeField("MyMergeField1", true, false);

builder.Write(" Text between our two merge fields. ");

doc.Save(ArtifactsDir + "DocumentBuilder.MergeFields.docx");
Inserts a field into a document using DocumentBuilder and FieldCode.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertField Overload List | Field


DocumentBuilder.InsertField Method (String, String)

Inserts a Word field into a document without updating the field result.

[Visual Basic]
Overloads Public Function InsertField( _
ByVal fieldCode As String, _
ByVal fieldValue As String _
) As Field
[C#]
public Field InsertField(
string fieldCode,
string fieldValue
);

Parameters

fieldCode
The field code to insert (without curly braces).
fieldValue
The field value to insert. Pass null for fields that do not have a value.

Return Value

A Field object that represents the inserted field.

Remarks

Fields in Microsoft Word documents consist of a field code and a field result. The field code is like a formula and the field result is like the value that the formula produces. The field code may also contain field switches that are like additional instructions to perform a specific action.

You can switch between displaying field codes and results in your document in Microsoft Word using the keyboard shortcut Alt+F9. Field codes appear between curly braces ( { } ).

To create a field, you need to specify a field type, field code and a "placeholder" field value. If you are not sure about a particular field code syntax, create the field in Microsoft Word first and switch to see its field code.

Aspose.Words can calculate field results for most of the field types, but this method does not update the field result automatically. Because the field result is not calculated automatically, you are expected to pass some string value (or even an empty string) that will be inserted into the field result. This value will remain in the field result as a placeholder until the field is updated. To update the field result you can call Update on the field object returned to you or UpdateFields to update fields in the whole document.

Example

Shows how to control page numbering per section.

[C#]

// This document has two sections, but no page numbers yet.
Document doc = new Document(MyDir + "PageSetup.PageNumbering.doc");

// Use document builder to create a header with a page number field for the first section.
// The page number will look like "Page V".
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToSection(0);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Page ");
builder.InsertField("PAGE", "");

// Set first section page numbering.
Section section = doc.Sections[0];
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageStartingNumber = 5;
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman;

// Create a header for the section.
// The page number will look like " - 10 - ".
builder.MoveToSection(1);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write(" - ");
builder.InsertField("PAGE", "");
builder.Write(" - ");

// Set second section page numbering.
section = doc.Sections[1];
section.PageSetup.PageStartingNumber = 10;
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageNumberStyle = NumberStyle.Arabic;

doc.Save(ArtifactsDir + "PageSetup.PageNumbering.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertField Overload List | Field


InsertFootnote Method

Aspose.Words

DocumentBuilder.InsertFootnote Method

Inserts a footnote or endnote into the document.

Overload List

Inserts a footnote or endnote into the document.

public Footnote InsertFootnote(FootnoteType,string);

Inserts a footnote or endnote into the document.

public Footnote InsertFootnote(FootnoteType,string,string);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertFootnote Method (FootnoteType, String)

Inserts a footnote or endnote into the document.

[Visual Basic]
Overloads Public Function InsertFootnote( _
ByVal footnoteType As FootnoteType, _
ByVal footnoteText As String _
) As Footnote
[C#]
public Footnote InsertFootnote(
FootnoteType footnoteType,
string footnoteText
);

Parameters

footnoteType
Specifies whether to insert a footnote or an endnote.
footnoteText
Specifies the text of the footnote.

Return Value

Returns a footnote object that was just created.

Example

Shows how to add a footnote to a paragraph in the document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

for (int i = 0; i <= 100; i++)
{
    builder.Write("Some text " + i);

    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i);
    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i, "242");
}

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertFootnote Overload List


DocumentBuilder.InsertFootnote Method (FootnoteType, String, String)

Inserts a footnote or endnote into the document.

[Visual Basic]
Overloads Public Function InsertFootnote( _
ByVal footnoteType As FootnoteType, _
ByVal footnoteText As String, _
ByVal referenceMark As String _
) As Footnote
[C#]
public Footnote InsertFootnote(
FootnoteType footnoteType,
string footnoteText,
string referenceMark
);

Parameters

footnoteType
Specifies whether to insert a footnote or an endnote.
footnoteText
Specifies the text of the footnote.
referenceMark
Specifies the custom reference mark of the footnote.

Return Value

Returns a footnote object that was just created.

Example

Shows how to add a footnote to a paragraph in the document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

for (int i = 0; i <= 100; i++)
{
    builder.Write("Some text " + i);

    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i);
    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i, "242");
}

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertFootnote Overload List


DocumentBuilder.InsertHorizontalRule Method

Inserts a horizontal rule shape into the document.

[Visual Basic]
Public Sub InsertHorizontalRule()
[C#]
public void InsertHorizontalRule();

Example

Shows how to insert horizontal rule shape in a document.

[C#]

// Use a document builder to insert a horizontal rule
DocumentBuilder builder = new DocumentBuilder();
builder.InsertHorizontalRule();

// Get the rule from the document's shape collection and verify it
Shape horizontalRule = (Shape)builder.Document.GetChild(NodeType.Shape, 0, true);
Assert.True(horizontalRule.IsHorizontalRule);

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertHtml Method

Aspose.Words

DocumentBuilder.InsertHtml Method

Inserts an HTML string into the document.

Overload List

Inserts an HTML string into the document.

public void InsertHtml(string);

Inserts an HTML string into the document.

public void InsertHtml(string,bool);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertHtml Method (String)

Inserts an HTML string into the document.

[Visual Basic]
Overloads Public Sub InsertHtml( _
ByVal html As String _
)
[C#]
public void InsertHtml(
string html
);

Parameters

html
An HTML string to insert into the document.

Remarks

You can use InsertHtml to insert an HTML fragment or whole HTML document.

Example

Inserts MathMl into a document using.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

const String mathMl =
    "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mrow><msub><mi>a</mi><mrow><mn>1</mn></mrow></msub><mo>+</mo><msub><mi>b</mi><mrow><mn>1</mn></mrow></msub></mrow></math>";

builder.InsertHtml(mathMl);
Inserts HTML into a document. The formatting specified in the HTML is applied.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

string html = "<P align='right'>Paragraph right</P>" + "<b>Implicit paragraph left</b>" +
              "<div align='center'>Div center</div>" + "<h1 align='left'>Heading 1 left.</h1>";

builder.InsertHtml(html);

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHtml.doc");
Replaces text specified with regular expression with HTML.
[C#]

// Open the document.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);

    doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);

    // Save the modified document.
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
    {
        mOptions = options;
    }

    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document) args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }

    private readonly FindReplaceOptions mOptions;
}
Shows how to mail merge HTML data into a document.
[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertHtml Overload List


DocumentBuilder.InsertHtml Method (String, Boolean)

Inserts an HTML string into the document.

[Visual Basic]
Overloads Public Sub InsertHtml( _
ByVal html As String, _
ByVal useBuilderFormatting As Boolean _
)
[C#]
public void InsertHtml(
string html,
bool useBuilderFormatting
);

Parameters

html
An HTML string to insert into the document.
useBuilderFormatting
A value indicating whether formatting specified in DocumentBuilder is used as base formatting for text imported from HTML.

Remarks

You can use InsertHtml to insert an HTML fragment or whole HTML document.

When useBuilderFormatting is false, DocumentBuilder formating is ignored and formatting of inserted text is based on default HTML formatting. As a result, the text looks as it is rendered in browsers.

When useBuilderFormatting is true, formatting of inserted text is based on DocumentBuilder formatting, and the text looks as if it were inserted with Write.

Example

Inserts HTML into a document using. The current document formatting at the insertion position is applied to the inserted text.

[C#]

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertHtml(
    "<P align='right'>Paragraph right</P>" + "<b>Implicit paragraph left</b>" +
    "<div align='center'>Div center</div>" + "<h1 align='left'>Heading 1 left.</h1>", true);

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHtml.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertHtml Overload List


DocumentBuilder.InsertHyperlink Method

Inserts a hyperlink into the document.

[Visual Basic]
Public Function InsertHyperlink( _
ByVal displayText As String, _
ByVal urlOrBookmark As String, _
ByVal isBookmark As Boolean _
) As Field
[C#]
public Field InsertHyperlink(
string displayText,
string urlOrBookmark,
bool isBookmark
);

Parameters

displayText
Text of the link to be displayed in the document.
urlOrBookmark
Link destination. Can be a url or a name of a bookmark inside the document. This method always adds apostrophes at the beginning and end of the url.
isBookmark
True if the previous parameter is a name of a bookmark inside the document; false is the previous parameter is a URL.

Return Value

A Field object that represents the inserted field.

Remarks

Note that you need to specify font formatting for the hyperlink display text explicitly using the Font property.

This methods internally calls InsertField to insert an MS Word HYPERLINK field into the document.

Example

Inserts a hyperlink into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Please make sure to visit ");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
// Insert the link.
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false);

// Revert to default formatting.
builder.Font.ClearFormatting();

builder.Write(" for more information.");

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlink.doc");
Inserts a hyperlink referencing local bookmark.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartBookmark("Bookmark1");
builder.Write("Bookmarked text.");
builder.EndBookmark("Bookmark1");

builder.Writeln("Some other text");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;

// Insert hyperlink.
// Switch \o is used to provide hyperlink tip text.
builder.InsertHyperlink("Hyperlink Text", @"Bookmark1"" \o ""Hyperlink Tip", true);

// Clear hyperlink formatting.
builder.Font.ClearFormatting();

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlinkToLocalBookmark.doc");
Shows how to use temporarily save and restore character formatting when building a document with DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set up font formatting and write text that goes before the hyperlink.
builder.Font.Name = "Arial";
builder.Font.Size = 24;
builder.Font.Bold = true;
builder.Write("To go to an important location, click ");

// Save the font formatting so we use different formatting for hyperlink and restore old formatting later.
builder.PushFont();

// Set new font formatting for the hyperlink and insert the hyperlink.
// The "Hyperlink" style is a Microsoft Word built-in style so we don't have to worry to
// create it, it will be created automatically if it does not yet exist in the document.
builder.Font.StyleIdentifier = StyleIdentifier.Hyperlink;
builder.InsertHyperlink("here", "http://www.google.com", false);

// Restore the formatting that was before the hyperlink.
builder.PopFont();

builder.Writeln(". We hope you enjoyed the example.");

doc.Save(ArtifactsDir + "DocumentBuilder.PushPopFont.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertImage Method

Aspose.Words

DocumentBuilder.InsertImage Method

Inserts an image into the document.

Overload List

Inserts an image from a byte array into the document. The image is inserted inline and at 100% scale.

public Shape InsertImage(byte[]);

Inserts an image from a byte array at the specified position and size.

public Shape InsertImage(byte[],RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an inline image from a byte array into the document and scales it to the specified size.

public Shape InsertImage(byte[],double,double);

Inserts an image from a .NET Image object into the document. The image is inserted inline and at 100% scale.

public Shape InsertImage(Image);

Inserts an image from a .NET Image object at the specified position and size.

public Shape InsertImage(Image,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an inline image from a .NET Image object into the document and scales it to the specified size.

public Shape InsertImage(Image,double,double);

Inserts an image from a stream into the document. The image is inserted inline and at 100% scale.

public Shape InsertImage(Stream);

Inserts an image from a stream at the specified position and size.

public Shape InsertImage(Stream,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an inline image from a stream into the document and scales it to the specified size.

public Shape InsertImage(Stream,double,double);

Inserts an image from a file or URL into the document. The image is inserted inline and at 100% scale.

public Shape InsertImage(string);

Inserts an image from a file or URL at the specified position and size.

public Shape InsertImage(string,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an inline image from a file or URL into the document and scales it to the specified size.

public Shape InsertImage(string,double,double);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertImage Method (Byte[])

Inserts an image from a byte array into the document. The image is inserted inline and at 100% scale.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal imageBytes As Byte() _
) As Shape
[C#]
public Shape InsertImage(
byte[] imageBytes
);

Parameters

imageBytes
The byte array that contains the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from a byte array.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image image = Image.FromFile(ImageDir + "Aspose.Words.gif");

using (MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ImageFormat.Png);
    byte[] imageByteArray = ms.ToArray();

    builder.Writeln("\nInserted image from byte array: ");
    builder.InsertImage(imageByteArray);

    builder.Writeln("\nInserted image from byte array with a custom size: ");
    builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from byte array using relative positions: ");
    builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromByteArray.docx");
Shows different solutions of how to import an image into a document from a byte array (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    using (SKImage image = SKImage.FromBitmap(bitmap))
    {
        using (SKData data = image.Encode()) // Encode the image (defaults to PNG)
        {
            byte[] imageByteArray = data.ToArray();

            builder.Writeln("\nInserted image from byte array: ");
            builder.InsertImage(imageByteArray);

            builder.Writeln("\nInserted image from byte array with a custom size: ");
            builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

            builder.Writeln("\nInserted image from byte array using relative positions: ");
            builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
                100, 200, 100, WrapType.Square);
        }
    }
}

doc.Save(ArtifactsDir + "InsertImageFromByteArray.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Byte[], RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an image from a byte array at the specified position and size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal imageBytes As Byte(), _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertImage(
byte[] imageBytes,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

imageBytes
The byte array that contains the image.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from a byte array.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image image = Image.FromFile(ImageDir + "Aspose.Words.gif");

using (MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ImageFormat.Png);
    byte[] imageByteArray = ms.ToArray();

    builder.Writeln("\nInserted image from byte array: ");
    builder.InsertImage(imageByteArray);

    builder.Writeln("\nInserted image from byte array with a custom size: ");
    builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from byte array using relative positions: ");
    builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromByteArray.docx");
Shows different solutions of how to import an image into a document from a byte array (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    using (SKImage image = SKImage.FromBitmap(bitmap))
    {
        using (SKData data = image.Encode()) // Encode the image (defaults to PNG)
        {
            byte[] imageByteArray = data.ToArray();

            builder.Writeln("\nInserted image from byte array: ");
            builder.InsertImage(imageByteArray);

            builder.Writeln("\nInserted image from byte array with a custom size: ");
            builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

            builder.Writeln("\nInserted image from byte array using relative positions: ");
            builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
                100, 200, 100, WrapType.Square);
        }
    }
}

doc.Save(ArtifactsDir + "InsertImageFromByteArray.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Byte[], Double, Double)

Inserts an inline image from a byte array into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal imageBytes As Byte(), _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertImage(
byte[] imageBytes,
double width,
double height
);

Parameters

imageBytes
The byte array that contains the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from a byte array.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image image = Image.FromFile(ImageDir + "Aspose.Words.gif");

using (MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ImageFormat.Png);
    byte[] imageByteArray = ms.ToArray();

    builder.Writeln("\nInserted image from byte array: ");
    builder.InsertImage(imageByteArray);

    builder.Writeln("\nInserted image from byte array with a custom size: ");
    builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from byte array using relative positions: ");
    builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromByteArray.docx");
Shows different solutions of how to import an image into a document from a byte array (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    using (SKImage image = SKImage.FromBitmap(bitmap))
    {
        using (SKData data = image.Encode()) // Encode the image (defaults to PNG)
        {
            byte[] imageByteArray = data.ToArray();

            builder.Writeln("\nInserted image from byte array: ");
            builder.InsertImage(imageByteArray);

            builder.Writeln("\nInserted image from byte array with a custom size: ");
            builder.InsertImage(imageByteArray, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

            builder.Writeln("\nInserted image from byte array using relative positions: ");
            builder.InsertImage(imageByteArray, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
                100, 200, 100, WrapType.Square);
        }
    }
}

doc.Save(ArtifactsDir + "InsertImageFromByteArray.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Image)

Inserts an image from a .NET Image object into the document. The image is inserted inline and at 100% scale.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal image As Image _
) As Shape
[C#]
public Shape InsertImage(
Image image
);

Parameters

image
The image to insert into the document.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from Image class.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image image = Image.FromFile(ImageDir + "Aspose.Words.gif");

builder.Writeln("\nInserted image from Image class: ");
builder.InsertImage(image);

builder.Writeln("\nInserted image from Image class with a custom size: ");
builder.InsertImage(image, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

builder.Writeln("\nInserted image from Image class using relative positions: ");
builder.InsertImage(image, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
    100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "InsertImageFromImageClass.docx");
Shows different solutions of how to import an image into a document from Image class (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    builder.Writeln("\nInserted image from Image class: ");
    builder.InsertImage(bitmap);

    builder.Writeln("\nInserted image from Image class with a custom size: ");
    builder.InsertImage(bitmap, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from Image class using relative positions: ");
    builder.InsertImage(bitmap, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromImageClass.NetStandard2.docx");
Inserts a watermark image into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");
Shows how to insert a .NET Image object into a document. The image is inserted inline and at 100% scale.
[C#]

// This creates a builder and also an empty document inside the builder.
            DocumentBuilder builder = new DocumentBuilder();
#if NETSTANDARD2_0 || __MOBILE__
            // Insert a raster image.
            // SKBitmap doesn't allow to insert a metafiles.
            using (SKBitmap rasterImage = SKBitmap.Decode(MyDir + "Images/Aspose.Words.gif"))
            {
                builder.Write("Raster image: ");
                builder.InsertImage(rasterImage);
                builder.Writeln();
            }
#else
            // Insert a raster image.
            Image rasterImage = Image.FromFile(MyDir + "Images/Aspose.Words.gif");
            try
            {
                builder.Write("Raster image: ");
                builder.InsertImage(rasterImage);
                builder.Writeln();
            }
            finally
            {
                rasterImage.Dispose();
            }

            // Aspose.Words allows to insert a metafile too.
            Image metafile = Image.FromFile(MyDir + "Images/Hammer.wmf");
            try
            {
                builder.Write("Metafile: ");
                builder.InsertImage(metafile);
                builder.Writeln();
            }
            finally
            {
                metafile.Dispose();
            }
#endif
            builder.Document.Save(ArtifactsDir + "Image.CreateFromImage.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Image, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an image from a .NET Image object at the specified position and size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal image As Image, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertImage(
Image image,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

image
The image to insert into the document.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from Image class.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image image = Image.FromFile(ImageDir + "Aspose.Words.gif");

builder.Writeln("\nInserted image from Image class: ");
builder.InsertImage(image);

builder.Writeln("\nInserted image from Image class with a custom size: ");
builder.InsertImage(image, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

builder.Writeln("\nInserted image from Image class using relative positions: ");
builder.InsertImage(image, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
    100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "InsertImageFromImageClass.docx");
Shows different solutions of how to import an image into a document from Image class (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    builder.Writeln("\nInserted image from Image class: ");
    builder.InsertImage(bitmap);

    builder.Writeln("\nInserted image from Image class with a custom size: ");
    builder.InsertImage(bitmap, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from Image class using relative positions: ");
    builder.InsertImage(bitmap, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromImageClass.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Image, Double, Double)

Inserts an inline image from a .NET Image object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal image As Image, _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertImage(
Image image,
double width,
double height
);

Parameters

image
The image to insert into the document.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from Image class.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image image = Image.FromFile(ImageDir + "Aspose.Words.gif");

builder.Writeln("\nInserted image from Image class: ");
builder.InsertImage(image);

builder.Writeln("\nInserted image from Image class with a custom size: ");
builder.InsertImage(image, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

builder.Writeln("\nInserted image from Image class using relative positions: ");
builder.InsertImage(image, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
    100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "InsertImageFromImageClass.docx");
Shows different solutions of how to import an image into a document from Image class (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap bitmap = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    builder.Writeln("\nInserted image from Image class: ");
    builder.InsertImage(bitmap);

    builder.Writeln("\nInserted image from Image class with a custom size: ");
    builder.InsertImage(bitmap, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from Image class using relative positions: ");
    builder.InsertImage(bitmap, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromImageClass.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Stream)

Inserts an image from a stream into the document. The image is inserted inline and at 100% scale.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal stream As Stream _
) As Shape
[C#]
public Shape InsertImage(
Stream stream
);

Parameters

stream
The stream that contains the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows how to insert an image from a stream. The image is inserted inline and at 100% scale.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

Stream stream = File.OpenRead(MyDir + "Images/Aspose.Words.gif");
try
{
    builder.Write("Image from stream: ");
    builder.InsertImage(stream);
}
finally
{
    stream.Close();
}

builder.Document.Save(ArtifactsDir + "Image.CreateFromStream.doc");
Shows different solutions of how to import an image into a document from a stream.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (Stream stream = File.OpenRead(ImageDir + "Aspose.Words.gif"))
{
    builder.Writeln("Inserted image from stream: ");
    builder.InsertImage(stream);

    builder.Writeln("\nInserted image from stream with a custom size: ");
    builder.InsertImage(stream, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from stream using relative positions: ");
    builder.InsertImage(stream, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromStream.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Stream, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an image from a stream at the specified position and size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal stream As Stream, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertImage(
Stream stream,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

stream
The stream that contains the image.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from a stream.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (Stream stream = File.OpenRead(ImageDir + "Aspose.Words.gif"))
{
    builder.Writeln("Inserted image from stream: ");
    builder.InsertImage(stream);

    builder.Writeln("\nInserted image from stream with a custom size: ");
    builder.InsertImage(stream, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from stream using relative positions: ");
    builder.InsertImage(stream, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromStream.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (Stream, Double, Double)

Inserts an inline image from a stream into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal stream As Stream, _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertImage(
Stream stream,
double width,
double height
);

Parameters

stream
The stream that contains the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from a stream.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (Stream stream = File.OpenRead(ImageDir + "Aspose.Words.gif"))
{
    builder.Writeln("Inserted image from stream: ");
    builder.InsertImage(stream);

    builder.Writeln("\nInserted image from stream with a custom size: ");
    builder.InsertImage(stream, ConvertUtil.PixelToPoint(250), ConvertUtil.PixelToPoint(144));

    builder.Writeln("\nInserted image from stream using relative positions: ");
    builder.InsertImage(stream, RelativeHorizontalPosition.Margin, 100, RelativeVerticalPosition.Margin,
        100, 200, 100, WrapType.Square);
}

doc.Save(ArtifactsDir + "InsertImageFromStream.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (String)

Inserts an image from a file or URL into the document. The image is inserted inline and at 100% scale.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal fileName As String _
) As Shape
[C#]
public Shape InsertImage(
string fileName
);

Parameters

fileName
The file with the image. Can be any valid local or remote URI.

Return Value

The image node that was just inserted.

Remarks

This overload will automatically download the image before inserting into the document if you specify a remote URI.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows how to insert an image into a document from a web address.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertImage(AsposeLogoUrl);

doc.Save(ArtifactsDir + "DocumentBuilder.InsertImageFromUrl.doc");
Shows how to inserts an image from a URL. The image is inserted inline and at 100% scale.
[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

builder.Write("Image from local file: ");
builder.InsertImage(MyDir + "Images/Aspose.Words.gif");
builder.Writeln();

builder.Write("Image from an Internet url, automatically downloaded for you: ");
builder.InsertImage(AsposeLogoUrl);
builder.Writeln();

builder.Document.Save(ArtifactsDir + "Image.CreateFromUrl.doc");
Shows different solutions of how to import an image into a document from a string.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("\nInserted image from string: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif");

builder.Writeln("\nInserted image from string with a custom size: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif", ConvertUtil.PixelToPoint(250),
    ConvertUtil.PixelToPoint(144));

builder.Writeln("\nInserted image from string using relative positions: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif", RelativeHorizontalPosition.Margin, 100,
    RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "InsertImageFromString.docx");
Shows how to insert a floating image in the middle of a page.
[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (String, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an image from a file or URL at the specified position and size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal fileName As String, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertImage(
string fileName,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

fileName
The file that contains the image.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows how to insert a floating image from a file or URL.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertImage(ImageDir + "Watermark.png", RelativeHorizontalPosition.Margin, 100,
    RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square);
Shows how to insert a floating image from a file or URL and retain the original image size in the document.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Pass a negative value to the width and height values to specify using the size of the source image.
builder.InsertImage(ImageDir + "LogoSmall.png", RelativeHorizontalPosition.Margin, 200,
    RelativeVerticalPosition.Margin, 100, -1, -1, WrapType.Square);
Shows different solutions of how to import an image into a document from a string.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("\nInserted image from string: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif");

builder.Writeln("\nInserted image from string with a custom size: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif", ConvertUtil.PixelToPoint(250),
    ConvertUtil.PixelToPoint(144));

builder.Writeln("\nInserted image from string using relative positions: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif", RelativeHorizontalPosition.Margin, 100,
    RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "InsertImageFromString.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertImage Method (String, Double, Double)

Inserts an inline image from a file or URL into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertImage( _
ByVal fileName As String, _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertImage(
string fileName,
double width,
double height
);

Parameters

fileName
The file that contains the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows different solutions of how to import an image into a document from a string.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("\nInserted image from string: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif");

builder.Writeln("\nInserted image from string with a custom size: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif", ConvertUtil.PixelToPoint(250),
    ConvertUtil.PixelToPoint(144));

builder.Writeln("\nInserted image from string using relative positions: ");
builder.InsertImage(ImageDir + "Aspose.Words.gif", RelativeHorizontalPosition.Margin, 100,
    RelativeVerticalPosition.Margin, 100, 200, 100, WrapType.Square);

doc.Save(ArtifactsDir + "InsertImageFromString.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertImage Overload List


DocumentBuilder.InsertNode Method

Inserts a text level node inside the current paragraph before the cursor.

[Visual Basic]
Public Sub InsertNode( _
ByVal node As Node _
)
[C#]
public void InsertNode(
Node node
);

Example

Shows how to insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "Images/Hammer.wmf";

builder.Write("Image linked, not stored in the document: ");

Shape linkedOnly = new Shape(builder.Document, ShapeType.Image);
linkedOnly.WrapType = WrapType.Inline;
linkedOnly.ImageData.SourceFullName = imageFileName;

builder.InsertNode(linkedOnly);
builder.Writeln();

builder.Write("Image linked and stored in the document: ");

Shape linkedAndStored = new Shape(builder.Document, ShapeType.Image);
linkedAndStored.WrapType = WrapType.Inline;
linkedAndStored.ImageData.SourceFullName = imageFileName;
linkedAndStored.ImageData.SetImage(imageFileName);

builder.InsertNode(linkedAndStored);
builder.Writeln();

builder.Write("Image stored in the document, but not linked: ");

Shape stored = new Shape(builder.Document, ShapeType.Image);
stored.WrapType = WrapType.Inline;
stored.ImageData.SetImage(imageFileName);

builder.InsertNode(stored);
builder.Writeln();

builder.Document.Save(ArtifactsDir + "Image.CreateLinkedImage.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertOleObject Method

Aspose.Words

DocumentBuilder.InsertOleObject Method

Inserts an embedded OLE object from a stream into the document.

Overload List

Inserts an embedded OLE object from a stream into the document.

public Shape InsertOleObject(Stream,string,bool,Image);

Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using file extension.

public Shape InsertOleObject(string,bool,bool,Image);

Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using given progID parameter.

public Shape InsertOleObject(string,string,bool,bool,Image);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertOleObject Method (Stream, String, Boolean, Image)

Inserts an embedded OLE object from a stream into the document.

[Visual Basic]
Overloads Public Function InsertOleObject( _
ByVal stream As Stream, _
ByVal progId As String, _
ByVal asIcon As Boolean, _
ByVal presentation As Image _
) As Shape
[C#]
public Shape InsertOleObject(
Stream stream,
string progId,
bool asIcon,
Image presentation
);

Parameters

stream
Stream containing application data.
progId
Programmatic Identifier of OLE object.
asIcon
Specifies either Iconic or Normal mode of OLE object being inserted.
presentation
Image presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.

Return Value

Shape node containing Ole object and inserted at the current Builder position.

Example

Shows how to use document builder to embed Ole objects in a document.

[C#]

Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Let's take a spreadsheet from our system and insert it into the document
            using (Stream spreadsheetStream = File.Open(MyDir + "MySpreadsheet.xlsx", FileMode.Open))
            {
                // The spreadsheet can be activated by double clicking the panel that you'll see in the document immediately under the text we will add
                // We did not set the area to double click as an icon nor did we change its appearance so it looks like a simple panel
                builder.Writeln("Spreadsheet Ole object:");
                builder.InsertOleObject(spreadsheetStream, "MyOleObject.xlsx", false, null);

                // A powerpoint presentation is another type of object we can embed in our document
                // This time we'll also exercise some control over how it looks
                using (Stream powerpointStream = File.Open(MyDir + "MyPresentation.pptx", FileMode.Open))
                {
                    // If we insert the Ole object as an icon, we are still provided with a default icon
                    // If that is not suitable, we can make the icon to look like any image
                    using (WebClient webClient = new WebClient())
                    {
                        byte[] imgBytes = webClient.DownloadData(AsposeLogoUrl);

#if NETSTANDARD2_0 || __MOBILE__
                        SkiaSharp.SKBitmap bitmap = SkiaSharp.SKBitmap.Decode(imgBytes);

                        builder.InsertParagraph();
                        builder.Writeln("Powerpoint Ole object:");
                        builder.InsertOleObject(powerpointStream, "MyOleObject.pptx", true, bitmap);
#else
                        using (MemoryStream stream = new MemoryStream(imgBytes))
                        {
                            using (Image image = Image.FromStream(stream))
                            {
                                // If we double click the image, the powerpoint presentation will open
                                builder.InsertParagraph();
                                builder.Writeln("Powerpoint Ole object:");
                                builder.InsertOleObject(powerpointStream, "MyOleObject.pptx", true, image);
                            }
                        }
#endif
                    }
                }
            }

            doc.Save(ArtifactsDir + "DocumentBuilder.InsertOleObject.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOleObject Overload List


DocumentBuilder.InsertOleObject Method (String, Boolean, Boolean, Image)

Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using file extension.

[Visual Basic]
Overloads Public Function InsertOleObject( _
ByVal fileName As String, _
ByVal isLinked As Boolean, _
ByVal asIcon As Boolean, _
ByVal presentation As Image _
) As Shape
[C#]
public Shape InsertOleObject(
string fileName,
bool isLinked,
bool asIcon,
Image presentation
);

Parameters

fileName
Full path to the file.
isLinked
If true then linked OLE object is inserted otherwise embedded OLE object is inserted.
asIcon
Specifies either Iconic or Normal mode of OLE object being inserted.
presentation
Image presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.

Return Value

Shape node containing Ole object and inserted at the current Builder position.

Example

Shows how to insert an OLE object into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image representingImage = Image.FromFile(ImageDir + "Aspose.Words.gif");

// OleObject
builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", false, false, representingImage);
//OleObject with ProgId
builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", "Excel.Sheet", false, false, representingImage);

doc.Save(ArtifactsDir + "Document.InsertedOleObject.docx");
Shows how to insert an OLE object into a document (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap representingImage = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    // OleObject
    builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", false, false, representingImage);
    //OleObject with ProgId
    builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", "Excel.Sheet", false, false,
        representingImage);
}

doc.Save(ArtifactsDir + "Document.InsertedOleObject.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOleObject Overload List


DocumentBuilder.InsertOleObject Method (String, String, Boolean, Boolean, Image)

Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using given progID parameter.

[Visual Basic]
Overloads Public Function InsertOleObject( _
ByVal fileName As String, _
ByVal progId As String, _
ByVal isLinked As Boolean, _
ByVal asIcon As Boolean, _
ByVal presentation As Image _
) As Shape
[C#]
public Shape InsertOleObject(
string fileName,
string progId,
bool isLinked,
bool asIcon,
Image presentation
);

Parameters

fileName
Full path to the file.
progId
ProgId of OLE object.
isLinked
If true then linked OLE object is inserted otherwise embedded OLE object is inserted.
asIcon
Specifies either Iconic or Normal mode of OLE object being inserted.
presentation
Image presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.

Return Value

Shape node containing Ole object and inserted at the current Builder position.

Example

Shows how to insert an OLE object into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Image representingImage = Image.FromFile(ImageDir + "Aspose.Words.gif");

// OleObject
builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", false, false, representingImage);
//OleObject with ProgId
builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", "Excel.Sheet", false, false, representingImage);

doc.Save(ArtifactsDir + "Document.InsertedOleObject.docx");
Shows how to insert an OLE object into a document (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (SKBitmap representingImage = SKBitmap.Decode(ImageDir + "Aspose.Words.gif"))
{
    // OleObject
    builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", false, false, representingImage);
    //OleObject with ProgId
    builder.InsertOleObject(MyDir + "Document.Spreadsheet.xlsx", "Excel.Sheet", false, false,
        representingImage);
}

doc.Save(ArtifactsDir + "Document.InsertedOleObject.NetStandard2.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOleObject Overload List


InsertOnlineVideo Method

Aspose.Words

DocumentBuilder.InsertOnlineVideo Method

Inserts an online video object into the document and scales it to the specified size.

Overload List

Inserts an online video object into the document and scales it to the specified size.

public Shape InsertOnlineVideo(string,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an online video object into the document and scales it to the specified size.

public Shape InsertOnlineVideo(string,double,double);

Inserts an online video object into the document and scales it to the specified size.

public Shape InsertOnlineVideo(string,string,byte[],RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts an online video object into the document and scales it to the specified size.

public Shape InsertOnlineVideo(string,string,byte[],double,double);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertOnlineVideo Method (String, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an online video object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertOnlineVideo( _
ByVal videoUrl As String, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertOnlineVideo(
string videoUrl,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

videoUrl
The URL to the video.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Insertion of online video from the following resources is supported:

  • https://www.youtube.com/
  • https://vimeo.com/

If your online video is not displaying correctly, use InsertOnlineVideo, which accepts custom embedded html code.

The code for embedding video can vary between providers, consult your corresponding provider of choice for details.

Example

Show how to insert online video into a document using html code

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Visible url
string vimeoVideoUrl = @"https://vimeo.com/52477838";

// Embed Html code
string vimeoEmbedCode =
    "<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";

// This video will have an automatically generated thumbnail, and we are setting the size according to its 16:9 aspect ratio
builder.Writeln("Video with an automatically generated thumbnail at the top left corner of the page:");
builder.InsertOnlineVideo(vimeoVideoUrl, RelativeHorizontalPosition.LeftMargin, 0,
    RelativeVerticalPosition.TopMargin, 0, 320, 180, WrapType.Square);
builder.InsertBreak(BreakType.PageBreak);

// We can get an image to use as a custom thumbnail
using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (MemoryStream stream = new MemoryStream(imageBytes))
    {
        using (Image image = Image.FromStream(stream))
        {
            // This puts the video where we are with our document builder, with a custom thumbnail and size depending on the size of the image
            builder.Writeln("Custom thumbnail at document builder's cursor:");
            builder.InsertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, image.Width, image.Height);
            builder.InsertBreak(BreakType.PageBreak);

            // We can put the video at the bottom right edge of the page too, but we'll have to take the page margins into account
            double left = builder.PageSetup.RightMargin - image.Width;
            double top = builder.PageSetup.BottomMargin - image.Height;

            // Here we use a custom thumbnail and relative positioning to put it and the bottom right of tha page
            builder.Writeln("Bottom right of page with custom thumbnail:");

            builder.InsertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes,
                RelativeHorizontalPosition.RightMargin, left, RelativeVerticalPosition.BottomMargin, top,
                image.Width, image.Height, WrapType.Square);
        }
    }
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertOnlineVideo.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOnlineVideo Overload List


DocumentBuilder.InsertOnlineVideo Method (String, Double, Double)

Inserts an online video object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertOnlineVideo( _
ByVal videoUrl As String, _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertOnlineVideo(
string videoUrl,
double width,
double height
);

Parameters

videoUrl
The URL to the video.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Insertion of online video from the following resources is supported:

  • https://www.youtube.com/
  • https://vimeo.com/

If your online video is not displaying correctly, use InsertOnlineVideo, which accepts custom embedded html code.

The code for embedding video can vary between providers, consult your corresponding provider of choice for details.

Example

Show how to insert online video into a document using video url

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Pass direct url from youtu.be.
String url = "https://youtu.be/t_1LYZ102RA";

double width = 360;
double height = 270;

builder.InsertOnlineVideo(url, width, height);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOnlineVideo Overload List


DocumentBuilder.InsertOnlineVideo Method (String, String, Byte[], RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts an online video object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertOnlineVideo( _
ByVal videoUrl As String, _
ByVal videoEmbedCode As String, _
ByVal thumbnailImageBytes As Byte(), _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertOnlineVideo(
string videoUrl,
string videoEmbedCode,
byte[] thumbnailImageBytes,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

videoUrl
The URL to the video.
videoEmbedCode
The embed code for the video.
thumbnailImageBytes
The thumbnail image bytes.
horzPos
Specifies where the distance to the image is measured from.
left
Distance in points from the origin to the left side of the image.
vertPos
Specifies where the distance to the image measured from.
top
Distance in points from the origin to the top side of the image.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.
wrapType
Specifies how to wrap text around the image.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Show how to insert online video into a document using html code

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Visible url
string vimeoVideoUrl = @"https://vimeo.com/52477838";

// Embed Html code
string vimeoEmbedCode =
    "<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";

// This video will have an automatically generated thumbnail, and we are setting the size according to its 16:9 aspect ratio
builder.Writeln("Video with an automatically generated thumbnail at the top left corner of the page:");
builder.InsertOnlineVideo(vimeoVideoUrl, RelativeHorizontalPosition.LeftMargin, 0,
    RelativeVerticalPosition.TopMargin, 0, 320, 180, WrapType.Square);
builder.InsertBreak(BreakType.PageBreak);

// We can get an image to use as a custom thumbnail
using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (MemoryStream stream = new MemoryStream(imageBytes))
    {
        using (Image image = Image.FromStream(stream))
        {
            // This puts the video where we are with our document builder, with a custom thumbnail and size depending on the size of the image
            builder.Writeln("Custom thumbnail at document builder's cursor:");
            builder.InsertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, image.Width, image.Height);
            builder.InsertBreak(BreakType.PageBreak);

            // We can put the video at the bottom right edge of the page too, but we'll have to take the page margins into account
            double left = builder.PageSetup.RightMargin - image.Width;
            double top = builder.PageSetup.BottomMargin - image.Height;

            // Here we use a custom thumbnail and relative positioning to put it and the bottom right of tha page
            builder.Writeln("Bottom right of page with custom thumbnail:");

            builder.InsertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes,
                RelativeHorizontalPosition.RightMargin, left, RelativeVerticalPosition.BottomMargin, top,
                image.Width, image.Height, WrapType.Square);
        }
    }
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertOnlineVideo.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOnlineVideo Overload List


DocumentBuilder.InsertOnlineVideo Method (String, String, Byte[], Double, Double)

Inserts an online video object into the document and scales it to the specified size.

[Visual Basic]
Overloads Public Function InsertOnlineVideo( _
ByVal videoUrl As String, _
ByVal videoEmbedCode As String, _
ByVal thumbnailImageBytes As Byte(), _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertOnlineVideo(
string videoUrl,
string videoEmbedCode,
byte[] thumbnailImageBytes,
double width,
double height
);

Parameters

videoUrl
The URL to the video.
videoEmbedCode
The embed code for the video.
thumbnailImageBytes
The thumbnail image bytes.
width
The width of the image in points. Can be a negative or zero value to request 100% scale.
height
The height of the image in points. Can be a negative or zero value to request 100% scale.

Return Value

The image node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Show how to insert online video into a document using html code

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Visible url
string vimeoVideoUrl = @"https://vimeo.com/52477838";

// Embed Html code
string vimeoEmbedCode =
    "<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";

// This video will have an automatically generated thumbnail, and we are setting the size according to its 16:9 aspect ratio
builder.Writeln("Video with an automatically generated thumbnail at the top left corner of the page:");
builder.InsertOnlineVideo(vimeoVideoUrl, RelativeHorizontalPosition.LeftMargin, 0,
    RelativeVerticalPosition.TopMargin, 0, 320, 180, WrapType.Square);
builder.InsertBreak(BreakType.PageBreak);

// We can get an image to use as a custom thumbnail
using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (MemoryStream stream = new MemoryStream(imageBytes))
    {
        using (Image image = Image.FromStream(stream))
        {
            // This puts the video where we are with our document builder, with a custom thumbnail and size depending on the size of the image
            builder.Writeln("Custom thumbnail at document builder's cursor:");
            builder.InsertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, image.Width, image.Height);
            builder.InsertBreak(BreakType.PageBreak);

            // We can put the video at the bottom right edge of the page too, but we'll have to take the page margins into account
            double left = builder.PageSetup.RightMargin - image.Width;
            double top = builder.PageSetup.BottomMargin - image.Height;

            // Here we use a custom thumbnail and relative positioning to put it and the bottom right of tha page
            builder.Writeln("Bottom right of page with custom thumbnail:");

            builder.InsertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes,
                RelativeHorizontalPosition.RightMargin, left, RelativeVerticalPosition.BottomMargin, top,
                image.Width, image.Height, WrapType.Square);
        }
    }
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertOnlineVideo.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOnlineVideo Overload List


DocumentBuilder.InsertParagraph Method

Inserts a paragraph break into the document.

[Visual Basic]
Public Function InsertParagraph() As Paragraph
[C#]
public Paragraph InsertParagraph();

Return Value

The paragraph node that was just inserted. It is the same node as CurrentParagraph.

Remarks

Current paragraph formatting specified by the ParagraphFormat property is used.

Breaks the current paragraph in two. After inserting the paragraph, the cursor is placed at the beginning of the new paragraph.

Example

Shows how to insert a paragraph into the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertShape Method

Aspose.Words

DocumentBuilder.InsertShape Method

Inserts free-floating shape with specified position, size and text wrap type.

Overload List

Inserts free-floating shape with specified position, size and text wrap type.

public Shape InsertShape(ShapeType,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,double,double,WrapType);

Inserts inline shape with specified type and size.

public Shape InsertShape(ShapeType,double,double);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertShape Method (ShapeType, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)

Inserts free-floating shape with specified position, size and text wrap type.

[Visual Basic]
Overloads Public Function InsertShape( _
ByVal shapeType As ShapeType, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal width As Double, _
ByVal height As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertShape(
ShapeType shapeType,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
double width,
double height,
WrapType wrapType
);

Parameters

shapeType
The shape type to insert into the document
horzPos
Specifies where the horizontal distance to the shape is measured from.
left
Distance in points from the origin to the left side of the shape.
vertPos
Specifies where the vertical distance to the shape is measured from.
top
Distance in points from the origin to the top side of the shape.
width
The width of the shape in points.
height
The width of the shape in points.
wrapType
Specifies how to wrap text around the shape.

Return Value

The shape node that was inserted.

Example

Shows how to insert DML shape into the document

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Two ways of shape insertion
Shape freeFloatingShape = builder.InsertShape(ShapeType.TextBox, RelativeHorizontalPosition.Page, 100, RelativeVerticalPosition.Page, 100, 50, 50, WrapType.None);
freeFloatingShape.Rotation = 30.0;
Shape inlineShape = builder.InsertShape(ShapeType.TextBox, 50, 50);
inlineShape.Rotation = 30.0;

OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(SaveFormat.Docx);
// "Strict" or "Transitional" compliance allows to save shape as DML
saveOptions.Compliance = OoxmlCompliance.Iso29500_2008_Transitional;
doc.Save(ArtifactsDir + "RotatedShape.docx", saveOptions);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertShape Overload List


DocumentBuilder.InsertShape Method (ShapeType, Double, Double)

Inserts inline shape with specified type and size.

[Visual Basic]
Overloads Public Function InsertShape( _
ByVal shapeType As ShapeType, _
ByVal width As Double, _
ByVal height As Double _
) As Shape
[C#]
public Shape InsertShape(
ShapeType shapeType,
double width,
double height
);

Parameters

shapeType
The shape type to insert into the document.
width
The width of the shape in points.
height
The height of the shape in points.

Return Value

The shape node that was inserted.

Example

Shows how to insert DML shape into the document

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Two ways of shape insertion
Shape freeFloatingShape = builder.InsertShape(ShapeType.TextBox, RelativeHorizontalPosition.Page, 100, RelativeVerticalPosition.Page, 100, 50, 50, WrapType.None);
freeFloatingShape.Rotation = 30.0;
Shape inlineShape = builder.InsertShape(ShapeType.TextBox, 50, 50);
inlineShape.Rotation = 30.0;

OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(SaveFormat.Docx);
// "Strict" or "Transitional" compliance allows to save shape as DML
saveOptions.Compliance = OoxmlCompliance.Iso29500_2008_Transitional;
doc.Save(ArtifactsDir + "RotatedShape.docx", saveOptions);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertShape Overload List


InsertSignatureLine Method

Aspose.Words

DocumentBuilder.InsertSignatureLine Method

Inserts a signature line at the current position.

Overload List

Inserts a signature line at the current position.

public Shape InsertSignatureLine(SignatureLineOptions);

Inserts a signature line at the specified position.

public Shape InsertSignatureLine(SignatureLineOptions,RelativeHorizontalPosition,double,RelativeVerticalPosition,double,WrapType);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertSignatureLine Method (SignatureLineOptions)

Inserts a signature line at the current position.

[Visual Basic]
Overloads Public Function InsertSignatureLine( _
ByVal signatureLineOptions As SignatureLineOptions _
) As Shape
[C#]
public Shape InsertSignatureLine(
SignatureLineOptions signatureLineOptions
);

Parameters

signatureLineOptions
The object that stores parameters of creating signature line.

Return Value

The signature line node that was just inserted.

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertSignatureLine Overload List


DocumentBuilder.InsertSignatureLine Method (SignatureLineOptions, RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, WrapType)

Inserts a signature line at the specified position.

[Visual Basic]
Overloads Public Function InsertSignatureLine( _
ByVal signatureLineOptions As SignatureLineOptions, _
ByVal horzPos As RelativeHorizontalPosition, _
ByVal left As Double, _
ByVal vertPos As RelativeVerticalPosition, _
ByVal top As Double, _
ByVal wrapType As WrapType _
) As Shape
[C#]
public Shape InsertSignatureLine(
SignatureLineOptions signatureLineOptions,
RelativeHorizontalPosition horzPos,
double left,
RelativeVerticalPosition vertPos,
double top,
WrapType wrapType
);

Parameters

signatureLineOptions
The object that stores parameters of creating signature line.
horzPos
Specifies where the distance to the signature line is measured from.
left
Distance in points from the origin to the left side of the signature line.
vertPos
Specifies where the distance to the signature line measured from.
top
Distance in points from the origin to the top side of the signature line.
wrapType
Specifies how to wrap text around the signature line.

Return Value

The signature line node that was just inserted.

Remarks

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Example

Shows how to insert signature line at the specified position.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions options = new SignatureLineOptions
{
    Signer = "John Doe",
    SignerTitle = "Manager",
    Email = "johndoe@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, 2.0,
    RelativeVerticalPosition.Page, 3.0, WrapType.Inline);

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertSignatureLine Overload List


DocumentBuilder.InsertStyleSeparator Method

Inserts style separator into the document.

[Visual Basic]
Public Sub InsertStyleSeparator()
[C#]
public void InsertStyleSeparator();

Remarks

This method allows to apply different paragraph styles to two different parts of a text line.

Example

Shows how to separate styles from two different paragraphs used in one logical printed paragraph.

[C#]

DocumentBuilder builder = new DocumentBuilder(new Document());

Style paraStyle = builder.Document.Styles.Add(StyleType.Paragraph, "MyParaStyle");
paraStyle.Font.Bold = false;
paraStyle.Font.Size = 8;
paraStyle.Font.Name = "Arial";

// Append text with "Heading 1" style.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Write("Heading 1");
builder.InsertStyleSeparator();

// Append text with another style.
builder.ParagraphFormat.StyleName = paraStyle.Name;
builder.Write("This is text with some other formatting ");
Shows how to use and separate multiple styles in a paragraph
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in the default style. ");

builder.InsertStyleSeparator();

// Create a custom style
Style myStyle = builder.Document.Styles.Add(StyleType.Paragraph, "MyStyle");
myStyle.Font.Size = 14;
myStyle.Font.Name = "Courier New";
myStyle.Font.Color = Color.Blue;

// Append text with custom style
builder.ParagraphFormat.StyleName = myStyle.Name;
builder.Write("This is text in the same paragraph but with my custom style.");

doc.Save(ArtifactsDir + "DocumentBuilder.StyleSeparator.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertTableOfContents Method

Inserts a TOC (table of contents) field into the document.

[Visual Basic]
Public Function InsertTableOfContents( _
ByVal switches As String _
) As Field
[C#]
public Field InsertTableOfContents(
string switches
);

Parameters

switches
The TOC field switches.

Remarks

This method inserts a TOC (table of contents) field into the document at the current position.

A table of contents in a Word document can be built in a number of ways and formatted using a variety of options. The way the table is built and displayed by Microsoft Word is controlled by the field switches.

The easiest way to specify the switches is to insert and configure a table of contents into a Word document using the Insert->Reference->Index and Tables menu, then switch display of field codes on to see the switches. You can press Alt+F9 in Microsoft Word to toggle display of field codes on or off.

For example, after creating a table of contents, the following field is inserted into the document: { TOC \o "1-3" \h \z \u }. You can copy \o "1-3" \h \z \u and use it as the switches parameter.

Note that InsertTableOfContents will only insert a TOC field, but will not actually build the table of contents. The table of contents is built by Microsoft Word when the field is updated.

If you insert a table of contents using this method and then open the file in Microsoft Word, you will not see the table of contents because the TOC field has not yet been updated.

In Microsoft Word, fields are not automatically updated when a document is opened, but you can update fields in a document at any time by pressing F9.

Example

Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.

[C#]

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 2");
builder.Writeln("Heading 3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");

// Call the method below to update the TOC.
doc.UpdateFields();

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertTextInput Method

Inserts a text form field at the current position.

[Visual Basic]
Public Function InsertTextInput( _
ByVal name As String, _
ByVal type As TextFormFieldType, _
ByVal format As String, _
ByVal fieldValue As String, _
ByVal maxLength As Integer _
) As FormField
[C#]
public FormField InsertTextInput(
string name,
TextFormFieldType type,
string format,
string fieldValue,
int maxLength
);

Parameters

name
The name of the form field. Can be an empty string.
type
Specifies the type of the text form field.
format
Format string used to format the value of the form field.
fieldValue
Text that will be shown in the field.
maxLength
Maximum length the user can enter into the form field. Set to zero for unlimited length.

Return Value

The form field node that was just inserted.

Remarks

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Example

Shows how to insert a text input form field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Hello", 0);
Shows how to insert form fields, set options and gather them back in for use
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a text input field. The unique name of this field is "TextInput1", the other parameters define
// what type of FormField it is, the format of the text, the field result and the maximum text length (0 = no limit)
builder.InsertTextInput("TextInput1", TextFormFieldType.Regular, "", "", 0);
Builds a sample form to fill.
[C#]

DocumentBuilder builder = new DocumentBuilder();

// Insert a text form field for input a name.
builder.InsertTextInput("", TextFormFieldType.Regular, "", "Enter your name here", 30);

// Insert two blank lines.
builder.Writeln("");
builder.Writeln("");

string[] items =
{
    "-- Select your favorite footwear --", "Sneakers", "Oxfords", "Flip-flops", "Other",
    "I prefer to be barefoot"
};

// Insert a combo box to select a footwear type.
builder.InsertComboBox("", items, 0);

// Insert 2 blank lines.
builder.Writeln("");
builder.Writeln("");

builder.Document.Save(ArtifactsDir + "DocumentBuilder.CreateForm.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveTo Method

Moves the cursor to an inline node or to the end of a paragraph.

[Visual Basic]
Public Sub MoveTo( _
ByVal node As Node _
)
[C#]
public void MoveTo(
Node node
);

Parameters

node
The node must be a paragraph or a direct child of a paragraph.

Remarks

When node is an inline-level node, the cursor is moved to this node and further content will be inserted before that node.

When node is a Paragraph, the cursor is moved to the end of the paragraph and further content will be inserted just before the paragraph break.

When node is a block-level node but not a Paragraph, the cursor is moved to the end of the first paragraph into block-level node and further content will be inserted just before the paragraph break.

Example

Shows how to move a cursor position to a specified node.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveTo(doc.FirstSection.Body.LastParagraph);
Shows how to move between nodes and manipulate current ones.
[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


MoveToBookmark Method

Aspose.Words

DocumentBuilder.MoveToBookmark Method

Moves the cursor to a bookmark.

Overload List

Moves the cursor to a bookmark.

public bool MoveToBookmark(string);

Moves the cursor to a bookmark with greater precision.

public bool MoveToBookmark(string,bool,bool);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToBookmark Method (String)

Moves the cursor to a bookmark.

[Visual Basic]
Overloads Public Function MoveToBookmark( _
ByVal bookmarkName As String _
) As Boolean
[C#]
public bool MoveToBookmark(
string bookmarkName
);

Parameters

bookmarkName
The name of the bookmark to move the cursor to.

Return Value

True if the bookmark was found; false otherwise.

Remarks

Moves the cursor to a position just after the start of the bookmark with the specified name.

The comparison is not case-sensitive. If the bookmark was not found, false is returned and the cursor is not moved.

Inserting new text does not replace existing text of the bookmark.

Note that some bookmarks in the document are assigned to form fields. Moving to such a bookmark and inserting text there inserts the text into the form field code. Although this will not invalidate the form field, the inserted text will not be visible because it becomes part of the field code.

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.MoveToBookmark Overload List


DocumentBuilder.MoveToBookmark Method (String, Boolean, Boolean)

Moves the cursor to a bookmark with greater precision.

[Visual Basic]
Overloads Public Function MoveToBookmark( _
ByVal bookmarkName As String, _
ByVal isStart As Boolean, _
ByVal isAfter As Boolean _
) As Boolean
[C#]
public bool MoveToBookmark(
string bookmarkName,
bool isStart,
bool isAfter
);

Parameters

bookmarkName
The name of the bookmark to move the cursor to.
isStart
When true, moves the cursor to the beginning of the bookmark. When false, moves the cursor to the end of the bookmark.
isAfter
When true, moves the cursor to be after the bookmark start or end position. When false, moves the cursor to be before the bookmark start or end position.

Return Value

True if the bookmark was found; false otherwise.

Remarks

Moves the cursor to a position before or after the bookmark start or end.

If desired position is not at inline level, moves to the next paragraph.

The comparison is not case-sensitive. If the bookmark was not found, false is returned and the cursor is not moved.

Example

Shows how to move a cursor position to just after the bookmark end.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToBookmark("CoolBookmark", false, true);
builder.Writeln("This is a very cool bookmark.");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.MoveToBookmark Overload List


DocumentBuilder.MoveToCell Method

Moves the cursor to a table cell in the current section.

[Visual Basic]
Public Sub MoveToCell( _
ByVal tableIndex As Integer, _
ByVal rowIndex As Integer, _
ByVal columnIndex As Integer, _
ByVal characterIndex As Integer _
)
[C#]
public void MoveToCell(
int tableIndex,
int rowIndex,
int columnIndex,
int characterIndex
);

Parameters

tableIndex
The index of the table to move to.
rowIndex
The index of the row in the table.
columnIndex
The index of the column in the table.
characterIndex
The index of the character inside the cell. Currently can only specify 0 to move to the beginning of the cell or -1 to move to the end of the cell.

Remarks

The navigation is performed inside the current story of the current section.

For the index parameters, when index is greater than or equal to 0, it specifies an index from the beginning with 0 being the first element. When index is less than 0, it specified an index from the end with -1 being the last element.

Example

Shows how to move a cursor position to the specified table cell.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell.
builder.MoveToCell(1, 2, 4, 0);
builder.Writeln("Hello World!");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToDocumentEnd Method

Moves the cursor to the end of the document.

[Visual Basic]
Public Sub MoveToDocumentEnd()
[C#]
public void MoveToDocumentEnd();

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToDocumentStart Method

Moves the cursor to the beginning of the document.

[Visual Basic]
Public Sub MoveToDocumentStart()
[C#]
public void MoveToDocumentStart();

Example

Shows how to move between nodes and manipulate current ones.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.WorkingWithNodes.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete");
builder.CurrentParagraph.Remove();

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = true
};

// Move to a particular paragraph's run and replace all occurrences of "bad" with "good" within this run.
builder.MoveTo(doc.LastSection.Body.Paragraphs[0].Runs[0]);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsFalse(builder.IsAtEndOfParagraph);
builder.CurrentNode.Range.Replace("bad", "good", options);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// builder.WriteLn puts an end to its current paragraph after writing the text and starts a new one
Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsTrue(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// builder.Write doesn't end the paragraph
builder.Write("Second paragraph.");

Assert.AreEqual(2, doc.FirstSection.Body.Paragraphs.Count);
Assert.IsFalse(builder.IsAtStartOfParagraph);
Assert.IsTrue(builder.IsAtEndOfParagraph);

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(ArtifactsDir + "DocumentBuilder.WorkingWithNodes.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToField Method

Moves the cursor to a field in the document.

[Visual Basic]
Public Sub MoveToField( _
ByVal field As Field, _
ByVal isAfter As Boolean _
)
[C#]
public void MoveToField(
Field field,
bool isAfter
);

Parameters

field
The field to move the cursor to.
isAfter
When true, moves the cursor to be after the field end. When false, moves the cursor to be before the field start.

Example

Shows how to move document builder's cursor to a specific field.

[C#]

Document doc = new Document(MyDir + "Document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

Field field = builder.InsertField("MERGEFIELD field");

builder.MoveToField(field, true);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToHeaderFooter Method

Moves the cursor to the beginning of a header or footer in the current section.

[Visual Basic]
Public Sub MoveToHeaderFooter( _
ByVal headerFooterType As HeaderFooterType _
)
[C#]
public void MoveToHeaderFooter(
HeaderFooterType headerFooterType
);

Parameters

headerFooterType
Specifies the header or footer to move to.

Remarks

After you moved the cursor into a header or footer, you can use the rest of DocumentBuilder methods to modify the contents of the header or footer.

If you want to create headers and footers different for the first page, you need to set DifferentFirstPageHeaderFooter.

If you want to create headers and footers different for even and odd pages, you need to set OddAndEvenPagesHeaderFooter.

Use MoveToSection to move out of the header into the main text.

Example

Inserts a watermark image into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Creates headers and footers in a document using DocumentBuilder.
[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


MoveToMergeField Method

Aspose.Words

DocumentBuilder.MoveToMergeField Method

Moves the cursor to the specified merge field.

Overload List

Moves the cursor to a position just beyond the specified merge field and removes the merge field.

public bool MoveToMergeField(string);

Moves the merge field to the specified merge field.

public bool MoveToMergeField(string,bool,bool);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToMergeField Method (String)

Moves the cursor to a position just beyond the specified merge field and removes the merge field.

[Visual Basic]
Overloads Public Function MoveToMergeField( _
ByVal fieldName As String _
) As Boolean
[C#]
public bool MoveToMergeField(
string fieldName
);

Parameters

fieldName
The case-insensitive name of the mail merge field.

Return Value

True if the merge field was found and the cursor was moved; false otherwise.

Remarks

Note that this method deletes the merge field from the document after moving the cursor.

Example

Fills document merge fields with some data.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.FillingDocument.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToMergeField("TeamLeaderName");
builder.Bold = true;
builder.Writeln("Roman Korchagin");

builder.MoveToMergeField("SoftwareDeveloper1Name");
builder.Italic = true;
builder.Writeln("Dmitry Vorobyev");

builder.MoveToMergeField("SoftwareDeveloper2Name");
builder.Italic = true;
builder.Writeln("Vladimir Averkin");

doc.Save(ArtifactsDir + "DocumentBuilder.FillingDocument.doc");
Shows how to insert checkbox form fields into a document during mail merge.
[C#]

// File 'MailMerge.InsertCheckBox.doc' is a template
    // containing the table with the following fields in it:
    // <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
    Document doc = new Document(MyDir + "MailMerge.InsertCheckBox.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertCheckBox();

    // Execute mail merge with regions.
    DataTable dataTable = GetStudentCourseDataTable();
    doc.MailMerge.ExecuteWithRegions(dataTable);

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertCheckBox.doc");
}

private class HandleMergeFieldInsertCheckBox : IFieldMergingCallback
{
    /// <summary>
    /// This is called for each merge field in the document
    /// when Document.MailMerge.ExecuteWithRegions is called.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        if (args.DocumentFieldName.Equals("CourseName"))
        {
            // The name of the table that we are merging can be found here
            Assert.AreEqual("StudentCourse", args.TableName);

            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.FieldName);
            builder.InsertCheckBox(args.DocumentFieldName + mCheckBoxCount, false, 0);

            // Get the actual value of the field
            string fieldValue = args.FieldValue.ToString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.AreEqual(Char.GetNumericValue(fieldValue[7]), args.RecordIndex);

            builder.Write(fieldValue);
            mCheckBoxCount++;
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// Counter for CheckBox name generation
    /// </summary>
    private int mCheckBoxCount;
}

/// <summary>
/// Create DataTable and fill it with data.
/// In real life this DataTable should be filled from a database.
/// </summary>
private static DataTable GetStudentCourseDataTable()
{
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.Columns.Add("CourseName");
    for (int i = 0; i < 10; i++)
    {
        DataRow datarow = dataTable.NewRow();
        dataTable.Rows.Add(datarow);
        datarow[0] = "Course " + i;
    }

    return dataTable;
}

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.MoveToMergeField Overload List


DocumentBuilder.MoveToMergeField Method (String, Boolean, Boolean)

Moves the merge field to the specified merge field.

[Visual Basic]
Overloads Public Function MoveToMergeField( _
ByVal fieldName As String, _
ByVal isAfter As Boolean, _
ByVal isDeleteField As Boolean _
) As Boolean
[C#]
public bool MoveToMergeField(
string fieldName,
bool isAfter,
bool isDeleteField
);

Parameters

fieldName
The case-insensitive name of the mail merge field.
isAfter
When true, moves the cursor to be after the field end. When false, moves the cursor to be before the field start.
isDeleteField
When true, deletes the merge field.

Return Value

True if the merge field was found and the cursor was moved; false otherwise.

Example

Shows how to insert merge fields and move between them.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField(@"MERGEFIELD MyMergeField1 \* MERGEFORMAT");
builder.InsertField(@"MERGEFIELD MyMergeField2 \* MERGEFORMAT");

Assert.AreEqual(2, doc.Range.Fields.Count);

// The second merge field starts immediately after the end of the first
// We'll move the builder's cursor to the end of the first so we can split them by text
builder.MoveToMergeField("MyMergeField1", true, false);

builder.Write(" Text between our two merge fields. ");

doc.Save(ArtifactsDir + "DocumentBuilder.MergeFields.docx");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.MoveToMergeField Overload List


DocumentBuilder.MoveToParagraph Method

Moves the cursor to a paragraph in the current section.

[Visual Basic]
Public Sub MoveToParagraph( _
ByVal paragraphIndex As Integer, _
ByVal characterIndex As Integer _
)
[C#]
public void MoveToParagraph(
int paragraphIndex,
int characterIndex
);

Parameters

paragraphIndex
The index of the paragraph to move to.
characterIndex
The index of the character inside the paragraph. Currently can only specify 0 to move to the beginning of the paragraph or -1 to move to the end of the paragraph.

Remarks

The navigation is performed inside the current story of the current section. That is, if you moved the cursor to the primary header of the first section, then paragraphIndex specified the index of the paragraph inside that header of that section.

When paragraphIndex is greater than or equal to 0, it specifies an index from the beginning of the section with 0 being the first paragraph. When paragraphIndex is less than 0, it specified an index from the end of the section with -1 being the last paragraph.

Example

Shows how to move a cursor position to the specified paragraph.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Parameters are 0-index. Moves to third paragraph.
builder.MoveToParagraph(2, 0);
builder.Writeln("This is the 3rd paragraph.");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.MoveToSection Method

Moves the cursor to the beginning of the body in a specified section.

[Visual Basic]
Public Sub MoveToSection( _
ByVal sectionIndex As Integer _
)
[C#]
public void MoveToSection(
int sectionIndex
);

Parameters

sectionIndex
The index of the section to move to.

Remarks

When sectionIndex is greater than or equal to 0, it specifies an index from the beginning of the document with 0 being the first section. When sectionIndex is less than 0, it specified an index from the end of the document with -1 being the last section.

The cursor is moved to the first paragraph in the Body of the specified section.

Example

Creates headers and footers in a document using DocumentBuilder.

[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.PopFont Method

Retrieves character formatting previously saved on the stack.

[Visual Basic]
Public Sub PopFont()
[C#]
public void PopFont();

Remarks

Example

Shows how to use temporarily save and restore character formatting when building a document with DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set up font formatting and write text that goes before the hyperlink.
builder.Font.Name = "Arial";
builder.Font.Size = 24;
builder.Font.Bold = true;
builder.Write("To go to an important location, click ");

// Save the font formatting so we use different formatting for hyperlink and restore old formatting later.
builder.PushFont();

// Set new font formatting for the hyperlink and insert the hyperlink.
// The "Hyperlink" style is a Microsoft Word built-in style so we don't have to worry to
// create it, it will be created automatically if it does not yet exist in the document.
builder.Font.StyleIdentifier = StyleIdentifier.Hyperlink;
builder.InsertHyperlink("here", "http://www.google.com", false);

// Restore the formatting that was before the hyperlink.
builder.PopFont();

builder.Writeln(". We hope you enjoyed the example.");

doc.Save(ArtifactsDir + "DocumentBuilder.PushPopFont.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | Font | PushFont


DocumentBuilder.PushFont Method

Saves current character formatting onto the stack.

[Visual Basic]
Public Sub PushFont()
[C#]
public void PushFont();

Remarks

Example

Shows how to use temporarily save and restore character formatting when building a document with DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set up font formatting and write text that goes before the hyperlink.
builder.Font.Name = "Arial";
builder.Font.Size = 24;
builder.Font.Bold = true;
builder.Write("To go to an important location, click ");

// Save the font formatting so we use different formatting for hyperlink and restore old formatting later.
builder.PushFont();

// Set new font formatting for the hyperlink and insert the hyperlink.
// The "Hyperlink" style is a Microsoft Word built-in style so we don't have to worry to
// create it, it will be created automatically if it does not yet exist in the document.
builder.Font.StyleIdentifier = StyleIdentifier.Hyperlink;
builder.InsertHyperlink("here", "http://www.google.com", false);

// Restore the formatting that was before the hyperlink.
builder.PopFont();

builder.Writeln(". We hope you enjoyed the example.");

doc.Save(ArtifactsDir + "DocumentBuilder.PushPopFont.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | Font | PopFont


DocumentBuilder.StartBookmark Method

Marks the current position in the document as a bookmark start.

[Visual Basic]
Public Function StartBookmark( _
ByVal bookmarkName As String _
) As BookmarkStart
[C#]
public BookmarkStart StartBookmark(
string bookmarkName
);

Parameters

bookmarkName
Name of the bookmark.

Return Value

The bookmark start node that was just created.

Remarks

Bookmarks in a document can overlap and span any range. To create a valid bookmark you need to call both StartBookmark and EndBookmark with the same bookmarkName parameter.

Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

Example

Adds some text into the document and encloses the text in a bookmark using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.StartBookmark("MyBookmark");
builder.Writeln("Text inside a bookmark.");
builder.EndBookmark("MyBookmark");
Inserts a hyperlink referencing local bookmark.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartBookmark("Bookmark1");
builder.Write("Bookmarked text.");
builder.EndBookmark("Bookmark1");

builder.Writeln("Some other text");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;

// Insert hyperlink.
// Switch \o is used to provide hyperlink tip text.
builder.InsertHyperlink("Hyperlink Text", @"Bookmark1"" \o ""Hyperlink Tip", true);

// Clear hyperlink formatting.
builder.Font.ClearFormatting();

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlinkToLocalBookmark.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.StartEditableRange Method

Marks the current position in the document as an editable range start.

[Visual Basic]
Public Function StartEditableRange() As EditableRangeStart
[C#]
public EditableRangeStart StartEditableRange();

Return Value

The editable range start node that was just created.

Remarks

Editable range in a document can overlap and span any range. To create a valid editable range you need to call both StartEditableRange and EndEditableRange or EndEditableRange methods.

Badly formed editable range will be ignored when the document is saved.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.StartTable Method

Starts a table in the document.

[Visual Basic]
Public Function StartTable() As Table
[C#]
public Table StartTable();

Return Value

The table node that was just created.

Remarks

The next method to call is InsertCell.

This method starts a nested table when called inside a cell.

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.Write Method

Inserts a string into the document at the current insert position.

[Visual Basic]
Public Sub Write( _
ByVal text As String _
)
[C#]
public void Write(
string text
);

Parameters

text
The string to insert into the document.

Remarks

Current font formatting specified by the Font property is used.

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
Shows how to create a simple table using DocumentBuilder with default formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// We call this method to start building the table.
builder.StartTable();
builder.InsertCell();
builder.Write("Row 1, Cell 1 Content.");

// Build the second cell
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.EndRow();

// Build the first cell of the second row.
builder.InsertCell();
builder.Write("Row 2, Cell 1 Content");

// Build the second cell.
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content.");
builder.EndRow();

// Signal that we have finished building the table.
builder.EndTable();

// Save the document to disk.
doc.Save(ArtifactsDir + "DocumentBuilder.CreateSimpleTable.doc");
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace


Writeln Method

Aspose.Words

DocumentBuilder.Writeln Method

Inserts a paragraph break into the document.

Overload List

Inserts a paragraph break into the document.

public void Writeln();

Inserts a string and a paragraph break into the document.

public void Writeln(string);

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.Writeln Method ()

Inserts a paragraph break into the document.

[Visual Basic]
Overloads Public Sub Writeln()
[C#]
public void Writeln();

Remarks

Calls InsertParagraph.

Example

Creates headers and footers in a document using DocumentBuilder.

[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.Writeln Overload List


DocumentBuilder.Writeln Method (String)

Inserts a string and a paragraph break into the document.

[Visual Basic]
Overloads Public Sub Writeln( _
ByVal text As String _
)
[C#]
public void Writeln(
string text
);

Parameters

text
The string to insert into the document.

Remarks

Current font and paragraph formatting specified by the Font and ParagraphFormat properties are used.

Example

Shows how to build a formatted table that contains 2 rows and 2 columns.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.Writeln Overload List


DocumentVisitor Class

Base class for custom document visitors.

For a list of all members of this type, see DocumentVisitor Members.

System.Object
Aspose.Words.DocumentVisitor

[Visual Basic]
MustInherit Public Class DocumentVisitor
[C#]
public abstract class DocumentVisitor

Remarks

With DocumentVisitor you can define and execute custom operations that require enumeration over the document tree.

For example, Aspose.Words uses DocumentVisitor internally for saving Document in various formats and for other operations like finding fields or bookmarks over a fragment of a document.

To use DocumentVisitor:

  1. Create a class derived from DocumentVisitor.
  2. Override and provide implementations for some or all of the VisitXXX methods to perform some custom operations.
  3. Call Node.Accept on the Node that you want to start the enumeration from.

DocumentVisitor provides default implementations for all of the VisitXXX methods to make it easier to create new document visitors as only the methods required for the particular visitor need to be overridden. It is not necessary to override all of the visitor methods.

For more information see the Visitor design pattern.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocumentVisitor Members | Aspose.Words Namespace


DocumentVisitor Members

DocumentVisitor overview

Public Instance Methods

VisitAbsolutePositionTab | Called when a AbsolutePositionTab node is encountered in the document.
VisitBodyEnd | Called when enumeration of the main text story in a section has ended.
VisitBodyStart | Called when enumeration of the main text story in a section has started.
VisitBookmarkEnd | Called when an end of a bookmark is encountered in the document.
VisitBookmarkStart | Called when a start of a bookmark is encountered in the document.
VisitBuildingBlockEnd | Called when enumeration of a building block has ended.
VisitBuildingBlockStart | Called when enumeration of a building block has started.
VisitCellEnd | Called when enumeration of a table cell has ended.
VisitCellStart | Called when enumeration of a table cell has started.
VisitCommentEnd | Called when enumeration of a comment text has ended.
VisitCommentRangeEnd | Called when the end of a commented range of text is encountered.
VisitCommentRangeStart | Called when the start of a commented range of text is encountered.
VisitCommentStart | Called when enumeration of a comment text has started.
VisitDocumentEnd | Called when enumeration of the document has finished.
VisitDocumentStart | Called when enumeration of the document has started.
VisitEditableRangeEnd | Called when an end of an editable range is encountered in the document.
VisitEditableRangeStart | Called when a start of an editable range is encountered in the document.
VisitFieldEnd | Called when a field ends in the document.
VisitFieldSeparator | Called when a field separator is encountered in the document.
VisitFieldStart | Called when a field starts in the document.
VisitFootnoteEnd | Called when enumeration of a footnote or endnote text has ended.
VisitFootnoteStart | Called when enumeration of a footnote or endnote text has started.
VisitFormField | Called when a form field is encountered in the document.
VisitGlossaryDocumentEnd | Called when enumeration of a glossary document has ended.
VisitGlossaryDocumentStart | Called when enumeration of a glossary document has started.
VisitGroupShapeEnd | Called when enumeration of a group shape has ended.
VisitGroupShapeStart | Called when enumeration of a group shape has started.
VisitHeaderFooterEnd | Called when enumeration of a header or footer in a section has ended.
VisitHeaderFooterStart | Called when enumeration of a header or footer in a section has started.
VisitOfficeMathEnd | Called when enumeration of a Office Math object has ended.
VisitOfficeMathStart | Called when enumeration of a Office Math object has started.
VisitParagraphEnd | Called when enumeration of a paragraph has ended.
VisitParagraphStart | Called when enumeration of a paragraph has started.
VisitRowEnd | Called when enumeration of a table row has ended.
VisitRowStart | Called when enumeration of a table row has started.
VisitRun | Called when a run of text in the is encountered.
VisitSectionEnd | Called when enumeration of a section has ended.
VisitSectionStart | Called when enumeration of a section has started.
VisitShapeEnd | Called when enumeration of a shape has ended.
VisitShapeStart | Called when enumeration of a shape has started.
VisitSmartTagEnd | Called when enumeration of a smart tag has ended.
VisitSmartTagStart | Called when enumeration of a smart tag has started.
VisitSpecialChar | Called when a SpecialChar node is encountered in the document.
VisitStructuredDocumentTagEnd | Called when enumeration of a structured document tag has ended.
VisitStructuredDocumentTagStart | Called when enumeration of a structured document tag has started.
VisitSubDocument | Called when a subDocument is encountered.
VisitTableEnd | Called when enumeration of a table has ended.
VisitTableStart | Called when enumeration of a table has started.

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor Methods

The methods of the DocumentVisitor class are listed below. For a complete list of DocumentVisitor class members, see the DocumentVisitor Members topic.

Public Instance Methods

VisitAbsolutePositionTab | Called when a AbsolutePositionTab node is encountered in the document.
VisitBodyEnd | Called when enumeration of the main text story in a section has ended.
VisitBodyStart | Called when enumeration of the main text story in a section has started.
VisitBookmarkEnd | Called when an end of a bookmark is encountered in the document.
VisitBookmarkStart | Called when a start of a bookmark is encountered in the document.
VisitBuildingBlockEnd | Called when enumeration of a building block has ended.
VisitBuildingBlockStart | Called when enumeration of a building block has started.
VisitCellEnd | Called when enumeration of a table cell has ended.
VisitCellStart | Called when enumeration of a table cell has started.
VisitCommentEnd | Called when enumeration of a comment text has ended.
VisitCommentRangeEnd | Called when the end of a commented range of text is encountered.
VisitCommentRangeStart | Called when the start of a commented range of text is encountered.
VisitCommentStart | Called when enumeration of a comment text has started.
VisitDocumentEnd | Called when enumeration of the document has finished.
VisitDocumentStart | Called when enumeration of the document has started.
VisitEditableRangeEnd | Called when an end of an editable range is encountered in the document.
VisitEditableRangeStart | Called when a start of an editable range is encountered in the document.
VisitFieldEnd | Called when a field ends in the document.
VisitFieldSeparator | Called when a field separator is encountered in the document.
VisitFieldStart | Called when a field starts in the document.
VisitFootnoteEnd | Called when enumeration of a footnote or endnote text has ended.
VisitFootnoteStart | Called when enumeration of a footnote or endnote text has started.
VisitFormField | Called when a form field is encountered in the document.
VisitGlossaryDocumentEnd | Called when enumeration of a glossary document has ended.
VisitGlossaryDocumentStart | Called when enumeration of a glossary document has started.
VisitGroupShapeEnd | Called when enumeration of a group shape has ended.
VisitGroupShapeStart | Called when enumeration of a group shape has started.
VisitHeaderFooterEnd | Called when enumeration of a header or footer in a section has ended.
VisitHeaderFooterStart | Called when enumeration of a header or footer in a section has started.
VisitOfficeMathEnd | Called when enumeration of a Office Math object has ended.
VisitOfficeMathStart | Called when enumeration of a Office Math object has started.
VisitParagraphEnd | Called when enumeration of a paragraph has ended.
VisitParagraphStart | Called when enumeration of a paragraph has started.
VisitRowEnd | Called when enumeration of a table row has ended.
VisitRowStart | Called when enumeration of a table row has started.
VisitRun | Called when a run of text in the is encountered.
VisitSectionEnd | Called when enumeration of a section has ended.
VisitSectionStart | Called when enumeration of a section has started.
VisitShapeEnd | Called when enumeration of a shape has ended.
VisitShapeStart | Called when enumeration of a shape has started.
VisitSmartTagEnd | Called when enumeration of a smart tag has ended.
VisitSmartTagStart | Called when enumeration of a smart tag has started.
VisitSpecialChar | Called when a SpecialChar node is encountered in the document.
VisitStructuredDocumentTagEnd | Called when enumeration of a structured document tag has ended.
VisitStructuredDocumentTagStart | Called when enumeration of a structured document tag has started.
VisitSubDocument | Called when a subDocument is encountered.
VisitTableEnd | Called when enumeration of a table has ended.
VisitTableStart | Called when enumeration of a table has started.

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitAbsolutePositionTab Method

Called when a AbsolutePositionTab node is encountered in the document.

[Visual Basic]
Overridable Public Function VisitAbsolutePositionTab( _
ByVal tab As AbsolutePositionTab _
) As VisitorAction
[C#]
public virtual VisitorAction VisitAbsolutePositionTab(
AbsolutePositionTab tab
);

Parameters

tab
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how to use AbsolutePositionTab.

[C#]

public void DocumentToTxt()
{
    // This document contains two sentences separated by an absolute position tab.
    Document doc = new Document(MyDir + "AbsolutePositionTab.docx");

    // An AbsolutePositionTab is a child node of a paragraph.
    // AbsolutePositionTabs get picked up when looking for nodes of the SpecialChar type.
    Paragraph para = doc.FirstSection.Body.FirstParagraph;
    AbsolutePositionTab absPositionTab = (AbsolutePositionTab)para.GetChild(NodeType.SpecialChar, 0, true);

    // This implementation of the DocumentVisitor pattern converts the document to plain text.
    MyDocToTxtWriter myDocToTxtWriter = new MyDocToTxtWriter();

    // We can run the DocumentVisitor over the whole first paragraph.
    para.Accept(myDocToTxtWriter);

    // A tab character is placed where the AbsolutePositionTab was found.
    Assert.AreEqual("Before AbsolutePositionTab\tAfter AbsolutePositionTab", myDocToTxtWriter.GetText());

    // An AbsolutePositionTab can accept a DocumentVisitor by itself too.
    myDocToTxtWriter = new MyDocToTxtWriter();
    absPositionTab.Accept(myDocToTxtWriter);

    Assert.AreEqual("\t", myDocToTxtWriter.GetText());
}

/// <summary>
/// Visitor implementation that simply collects the Runs and AbsolutePositionTabs of a document as plain text.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        // We'll treat the AbsolutePositionTab as a regular tab in this case.
        mBuilder.Append("\t");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honors the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        mBuilder.Append(text);
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitBodyEnd Method

Called when enumeration of the main text story in a section has ended.

[Visual Basic]
Overridable Public Function VisitBodyEnd( _
ByVal body As Body _
) As VisitorAction
[C#]
public virtual VisitorAction VisitBodyEnd(
Body body
);

Parameters

body
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitBodyStart Method

Called when enumeration of the main text story in a section has started.

[Visual Basic]
Overridable Public Function VisitBodyStart( _
ByVal body As Body _
) As VisitorAction
[C#]
public virtual VisitorAction VisitBodyStart(
Body body
);

Parameters

body
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitBookmarkEnd Method

Called when an end of a bookmark is encountered in the document.

[Visual Basic]
Overridable Public Function VisitBookmarkEnd( _
ByVal bookmarkEnd As BookmarkEnd _
) As VisitorAction
[C#]
public virtual VisitorAction VisitBookmarkEnd(
BookmarkEnd bookmarkEnd
);

Parameters

bookmarkEnd
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitBookmarkStart Method

Called when a start of a bookmark is encountered in the document.

[Visual Basic]
Overridable Public Function VisitBookmarkStart( _
ByVal bookmarkStart As BookmarkStart _
) As VisitorAction
[C#]
public virtual VisitorAction VisitBookmarkStart(
BookmarkStart bookmarkStart
);

Parameters

bookmarkStart
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how add bookmarks and update their contents.

[C#]

public void CreateUpdateAndPrintBookmarks()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add some bookmarks to the document
    for (int i = 1; i < 4; i++)
    {
        string bookmarkName = "Bookmark " + i;

        builder.StartBookmark(bookmarkName);
        builder.Write("Text content of " + bookmarkName);
        builder.EndBookmark(bookmarkName);
    }

    BookmarkCollection bookmarks = doc.Range.Bookmarks;

    // Look at initial values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

    // Update some values
    bookmarks[0].Name = "Updated name of " + bookmarks[0].Name;
    bookmarks[1].Text = "Updated text content of " + bookmarks[1].Name;
    bookmarks[2].Remove();

    bookmarks = doc.Range.Bookmarks;

    // Look at updated values of our bookmarks
    PrintAllBookmarkInfo(bookmarks);

}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark from within a document.
/// </summary>
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
    // Create a DocumentVisitor
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
    using (IEnumerator<Bookmark> enumerator = bookmarks.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Bookmark currentBookmark = enumerator.Current;

            // Accept our DocumentVisitor it to print information about our bookmarks
            if (currentBookmark != null)
            {
                currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
                currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);

                // Prints a blank line
                Console.WriteLine(currentBookmark.BookmarkStart.GetText());
            }
        }
    }
}

/// <summary>
/// Visitor that prints bookmark information to the console.
/// </summary>
public class BookmarkInfoPrinter : DocumentVisitor
{
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        Console.WriteLine("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.Name,
            bookmarkStart.Bookmark.Text);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        Console.WriteLine("BookmarkEnd name: \"{0}\"", bookmarkEnd.Name);
        return VisitorAction.Continue;
    }
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitBuildingBlockEnd Method

Called when enumeration of a building block has ended.

[Visual Basic]
Overridable Public Function VisitBuildingBlockEnd( _
ByVal block As BuildingBlock _
) As VisitorAction
[C#]
public virtual VisitorAction VisitBuildingBlockEnd(
BuildingBlock block
);

Parameters

block
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

Note: A building block node and its children are not visited when you execute a Visitor over a Document. If you want to execute a Visitor over a building block, you need to execute the visitor over GlossaryDocument or call Accept.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitBuildingBlockStart Method

Called when enumeration of a building block has started.

[Visual Basic]
Overridable Public Function VisitBuildingBlockStart( _
ByVal block As BuildingBlock _
) As VisitorAction
[C#]
public virtual VisitorAction VisitBuildingBlockStart(
BuildingBlock block
);

Parameters

block
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

Note: A building block node and its children are not visited when you execute a Visitor over a Document. If you want to execute a Visitor over a building block, you need to execute the visitor over GlossaryDocument or call Accept.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCellEnd Method

Called when enumeration of a table cell has ended.

[Visual Basic]
Overridable Public Function VisitCellEnd( _
ByVal cell As Cell _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCellEnd(
Cell cell
);

Parameters

cell
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all tables that it encounters.

[C#]

public void TableToText()
{
    // Open the document that has tables we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    TableInfoPrinter visitor = new TableInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of all tables encountered in the document.
/// </summary>
public class TableInfoPrinter : DocumentVisitor
{
    public TableInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideTable = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they consist of text from cells
        // So we are only interested in runs that are children of table nodes
        if (mVisitorIsInsideTable) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Table is encountered in the document.
    /// </summary>
    public override VisitorAction VisitTableStart(Table table)
    {
        int rows = 0;
        int columns = 0;

        if (table.Rows.Count > 0)
        {
            rows = table.Rows.Count;
            columns = table.FirstRow.Count;
        }

        IndentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
        mDocTraversalDepth++;
        mVisitorIsInsideTable = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Table node is ended.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Table end]");
        mVisitorIsInsideTable = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Row node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRowStart(Row row)
    {
        IndentAndAppendLine("[Row start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Row node is ended.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Row end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Cell node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCellStart(Cell cell)
    {
        Row row = cell.ParentRow;
        Table table = row.ParentTable;

        IndentAndAppendLine("[Cell start] Row " + (table.IndexOf(row) + 1) + ", Col " +
                            (row.IndexOf(cell) + 1) + "");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Cell end]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideTable;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCellStart Method

Called when enumeration of a table cell has started.

[Visual Basic]
Overridable Public Function VisitCellStart( _
ByVal cell As Cell _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCellStart(
Cell cell
);

Parameters

cell
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all tables that it encounters.

[C#]

public void TableToText()
{
    // Open the document that has tables we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    TableInfoPrinter visitor = new TableInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of all tables encountered in the document.
/// </summary>
public class TableInfoPrinter : DocumentVisitor
{
    public TableInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideTable = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they consist of text from cells
        // So we are only interested in runs that are children of table nodes
        if (mVisitorIsInsideTable) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Table is encountered in the document.
    /// </summary>
    public override VisitorAction VisitTableStart(Table table)
    {
        int rows = 0;
        int columns = 0;

        if (table.Rows.Count > 0)
        {
            rows = table.Rows.Count;
            columns = table.FirstRow.Count;
        }

        IndentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
        mDocTraversalDepth++;
        mVisitorIsInsideTable = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Table node is ended.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Table end]");
        mVisitorIsInsideTable = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Row node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRowStart(Row row)
    {
        IndentAndAppendLine("[Row start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Row node is ended.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Row end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Cell node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCellStart(Cell cell)
    {
        Row row = cell.ParentRow;
        Table table = row.ParentTable;

        IndentAndAppendLine("[Cell start] Row " + (table.IndexOf(row) + 1) + ", Col " +
                            (row.IndexOf(cell) + 1) + "");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Cell end]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideTable;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCommentEnd Method

Called when enumeration of a comment text has ended.

[Visual Basic]
Overridable Public Function VisitCommentEnd( _
ByVal comment As Comment _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCommentEnd(
Comment comment
);

Parameters

comment
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all comment nodes that it encounters.

[C#]

public void CommentsToText()
{
    // Open the document that has comments/comment ranges we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter visitor = new CommentInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(String.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCommentRangeEnd Method

Called when the end of a commented range of text is encountered.

[Visual Basic]
Overridable Public Function VisitCommentRangeEnd( _
ByVal commentRangeEnd As CommentRangeEnd _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCommentRangeEnd(
CommentRangeEnd commentRangeEnd
);

Parameters

commentRangeEnd
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all comment nodes that it encounters.

[C#]

public void CommentsToText()
{
    // Open the document that has comments/comment ranges we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter visitor = new CommentInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(String.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCommentRangeStart Method

Called when the start of a commented range of text is encountered.

[Visual Basic]
Overridable Public Function VisitCommentRangeStart( _
ByVal commentRangeStart As CommentRangeStart _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCommentRangeStart(
CommentRangeStart commentRangeStart
);

Parameters

commentRangeStart
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all comment nodes that it encounters.

[C#]

public void CommentsToText()
{
    // Open the document that has comments/comment ranges we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter visitor = new CommentInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(String.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCommentStart Method

Called when enumeration of a comment text has started.

[Visual Basic]
Overridable Public Function VisitCommentStart( _
ByVal comment As Comment _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCommentStart(
Comment comment
);

Parameters

comment
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all comment nodes that it encounters.

[C#]

public void CommentsToText()
{
    // Open the document that has comments/comment ranges we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    CommentInfoPrinter visitor = new CommentInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of comments and comment ranges encountered in the document.
/// </summary>
public class CommentInfoPrinter : DocumentVisitor
{
    public CommentInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideComment = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideComment) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeStart(CommentRangeStart commentRangeStart)
    {
        IndentAndAppendLine("[Comment range start] ID: " + commentRangeStart.Id);
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a CommentRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentRangeEnd(CommentRangeEnd commentRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment range end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        IndentAndAppendLine(String.Format("[Comment start] For comment range ID {0}, By {1} on {2}", comment.Id,
            comment.Author, comment.DateTime));
        mDocTraversalDepth++;
        mVisitorIsInsideComment = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Comment node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCommentEnd(Comment comment)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Comment end]");
        mVisitorIsInsideComment = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideComment;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitDocumentEnd Method

Called when enumeration of the document has finished.

[Visual Basic]
Overridable Public Function VisitDocumentEnd( _
ByVal doc As Document _
) As VisitorAction
[C#]
public virtual VisitorAction VisitDocumentEnd(
Document doc
);

Parameters

doc
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitDocumentStart Method

Called when enumeration of the document has started.

[Visual Basic]
Overridable Public Function VisitDocumentStart( _
ByVal doc As Document _
) As VisitorAction
[C#]
public virtual VisitorAction VisitDocumentStart(
Document doc
);

Parameters

doc
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitEditableRangeEnd Method

Called when an end of an editable range is encountered in the document.

[Visual Basic]
Overridable Public Function VisitEditableRangeEnd( _
ByVal editableRangeEnd As EditableRangeEnd _
) As VisitorAction
[C#]
public virtual VisitorAction VisitEditableRangeEnd(
EditableRangeEnd editableRangeEnd
);

Parameters

editableRangeEnd
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all editable ranges that it encounters.

[C#]

public void EditableRangeToText()
{
    // Open the document that has editable ranges we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    EditableRangeInfoPrinter visitor = new EditableRangeInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    Paragraph p = new Paragraph(doc);
    p.AppendChild(new Run(doc, "Paragraph with editable range text."));

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about editable ranges encountered in the document.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideEditableRange = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they are inside shapes, as they would be in the case of text boxes
        if (mVisitorIsInsideEditableRange) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRange node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        IndentAndAppendLine("[EditableRange start] ID: " + editableRangeStart.Id + " Owner: " +
                            editableRangeStart.EditableRange.SingleUser);
        mDocTraversalDepth++;
        mVisitorIsInsideEditableRange = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a EditableRange node is ended.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[EditableRange end]");
        mVisitorIsInsideEditableRange = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideEditableRange;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitEditableRangeStart Method

Called when a start of an editable range is encountered in the document.

[Visual Basic]
Overridable Public Function VisitEditableRangeStart( _
ByVal editableRangeStart As EditableRangeStart _
) As VisitorAction
[C#]
public virtual VisitorAction VisitEditableRangeStart(
EditableRangeStart editableRangeStart
);

Parameters

editableRangeStart
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all editable ranges that it encounters.

[C#]

public void EditableRangeToText()
{
    // Open the document that has editable ranges we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    EditableRangeInfoPrinter visitor = new EditableRangeInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    Paragraph p = new Paragraph(doc);
    p.AppendChild(new Run(doc, "Paragraph with editable range text."));

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about editable ranges encountered in the document.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideEditableRange = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they are inside shapes, as they would be in the case of text boxes
        if (mVisitorIsInsideEditableRange) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRange node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        IndentAndAppendLine("[EditableRange start] ID: " + editableRangeStart.Id + " Owner: " +
                            editableRangeStart.EditableRange.SingleUser);
        mDocTraversalDepth++;
        mVisitorIsInsideEditableRange = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a EditableRange node is ended.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[EditableRange end]");
        mVisitorIsInsideEditableRange = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideEditableRange;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitFieldEnd Method

Called when a field ends in the document.

[Visual Basic]
Overridable Public Function VisitFieldEnd( _
ByVal fieldEnd As FieldEnd _
) As VisitorAction
[C#]
public virtual VisitorAction VisitFieldEnd(
FieldEnd fieldEnd
);

Parameters

fieldEnd
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

For more info see VisitFieldStart

Example

Traverse a document with a visitor that prints all fields that it encounters.

[C#]

public void FieldToText()
{
    // Open the document that has fields that we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    FieldInfoPrinter visitor = new FieldInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about fields encountered in the document.
/// </summary>
public class FieldInfoPrinter : DocumentVisitor
{
    public FieldInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideField = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideField) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        IndentAndAppendLine("[Field start] FieldType: " + fieldStart.FieldType);
        mDocTraversalDepth++;
        mVisitorIsInsideField = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Field end]");
        mVisitorIsInsideField = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        IndentAndAppendLine("[FieldSeparator]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideField;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitFieldSeparator Method

Called when a field separator is encountered in the document.

[Visual Basic]
Overridable Public Function VisitFieldSeparator( _
ByVal fieldSeparator As FieldSeparator _
) As VisitorAction
[C#]
public virtual VisitorAction VisitFieldSeparator(
FieldSeparator fieldSeparator
);

Parameters

fieldSeparator
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

The field separator separates field code from field value in the document. Note that some fields have only field code and do not have field separator and field value.

For more info see VisitFieldStart

Example

Traverse a document with a visitor that prints all fields that it encounters.

[C#]

public void FieldToText()
{
    // Open the document that has fields that we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    FieldInfoPrinter visitor = new FieldInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about fields encountered in the document.
/// </summary>
public class FieldInfoPrinter : DocumentVisitor
{
    public FieldInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideField = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideField) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        IndentAndAppendLine("[Field start] FieldType: " + fieldStart.FieldType);
        mDocTraversalDepth++;
        mVisitorIsInsideField = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Field end]");
        mVisitorIsInsideField = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        IndentAndAppendLine("[FieldSeparator]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideField;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitFieldStart Method

Called when a field starts in the document.

[Visual Basic]
Overridable Public Function VisitFieldStart( _
ByVal fieldStart As FieldStart _
) As VisitorAction
[C#]
public virtual VisitorAction VisitFieldStart(
FieldStart fieldStart
);

Parameters

fieldStart
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

A field in a Word Word document consists of a field code and field value.

For example, a field that displays a page number can be represented as follows:

[FieldStart]PAGE[FieldSeparator]98[FieldEnd]

The field separator separates field code from field value in the document. Note that some fields have only field code and do not have field separator and field value.

Fields can be nested.

Example

Traverse a document with a visitor that prints all fields that it encounters.

[C#]

public void FieldToText()
{
    // Open the document that has fields that we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    FieldInfoPrinter visitor = new FieldInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about fields encountered in the document.
/// </summary>
public class FieldInfoPrinter : DocumentVisitor
{
    public FieldInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideField = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideField) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        IndentAndAppendLine("[Field start] FieldType: " + fieldStart.FieldType);
        mDocTraversalDepth++;
        mVisitorIsInsideField = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Field end]");
        mVisitorIsInsideField = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        IndentAndAppendLine("[FieldSeparator]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideField;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitFootnoteEnd Method

Called when enumeration of a footnote or endnote text has ended.

[Visual Basic]
Overridable Public Function VisitFootnoteEnd( _
ByVal footnote As Footnote _
) As VisitorAction
[C#]
public virtual VisitorAction VisitFootnoteEnd(
Footnote footnote
);

Parameters

footnote
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all footnotes that it encounters.

[C#]

public void FootnoteToText()
{
    // Open the document that has footnotes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    FootnoteInfoPrinter visitor = new FootnoteInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about footnotes encountered in the document.
/// </summary>
public class FootnoteInfoPrinter : DocumentVisitor
{
    public FootnoteInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideFootnote = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Footnote node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        IndentAndAppendLine("[Footnote start] Type: " + footnote.FootnoteType);
        mDocTraversalDepth++;
        mVisitorIsInsideFootnote = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Footnote node is ended.
    /// </summary>
    public override VisitorAction VisitFootnoteEnd(Footnote footnote)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Footnote end]");
        mVisitorIsInsideFootnote = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideFootnote) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideFootnote;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitFootnoteStart Method

Called when enumeration of a footnote or endnote text has started.

[Visual Basic]
Overridable Public Function VisitFootnoteStart( _
ByVal footnote As Footnote _
) As VisitorAction
[C#]
public virtual VisitorAction VisitFootnoteStart(
Footnote footnote
);

Parameters

footnote
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all footnotes that it encounters.

[C#]

public void FootnoteToText()
{
    // Open the document that has footnotes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    FootnoteInfoPrinter visitor = new FootnoteInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about footnotes encountered in the document.
/// </summary>
public class FootnoteInfoPrinter : DocumentVisitor
{
    public FootnoteInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideFootnote = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Footnote node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        IndentAndAppendLine("[Footnote start] Type: " + footnote.FootnoteType);
        mDocTraversalDepth++;
        mVisitorIsInsideFootnote = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Footnote node is ended.
    /// </summary>
    public override VisitorAction VisitFootnoteEnd(Footnote footnote)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Footnote end]");
        mVisitorIsInsideFootnote = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideFootnote) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideFootnote;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitFormField Method

Called when a form field is encountered in the document.

[Visual Basic]
Overridable Public Function VisitFormField( _
ByVal formField As FormField _
) As VisitorAction
[C#]
public virtual VisitorAction VisitFormField(
FormField formField
);

Parameters

formField
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitGlossaryDocumentEnd Method

Called when enumeration of a glossary document has ended.

[Visual Basic]
Overridable Public Function VisitGlossaryDocumentEnd( _
ByVal glossary As GlossaryDocument _
) As VisitorAction
[C#]
public virtual VisitorAction VisitGlossaryDocumentEnd(
GlossaryDocument glossary
);

Parameters

glossary
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

Note: A glossary document node and its children are not visited when you execute a Visitor over a Document. If you want to execute a Visitor over a glossary document, you need to call Accept.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitGlossaryDocumentStart Method

Called when enumeration of a glossary document has started.

[Visual Basic]
Overridable Public Function VisitGlossaryDocumentStart( _
ByVal glossary As GlossaryDocument _
) As VisitorAction
[C#]
public virtual VisitorAction VisitGlossaryDocumentStart(
GlossaryDocument glossary
);

Parameters

glossary
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

Note: A glossary document node and its children are not visited when you execute a Visitor over a Document. If you want to execute a Visitor over a glossary document, you need to call Accept.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitGroupShapeEnd Method

Called when enumeration of a group shape has ended.

[Visual Basic]
Overridable Public Function VisitGroupShapeEnd( _
ByVal groupShape As GroupShape _
) As VisitorAction
[C#]
public virtual VisitorAction VisitGroupShapeEnd(
GroupShape groupShape
);

Parameters

groupShape
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitGroupShapeStart Method

Called when enumeration of a group shape has started.

[Visual Basic]
Overridable Public Function VisitGroupShapeStart( _
ByVal groupShape As GroupShape _
) As VisitorAction
[C#]
public virtual VisitorAction VisitGroupShapeStart(
GroupShape groupShape
);

Parameters

groupShape
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitHeaderFooterEnd Method

Called when enumeration of a header or footer in a section has ended.

[Visual Basic]
Overridable Public Function VisitHeaderFooterEnd( _
ByVal headerFooter As HeaderFooter _
) As VisitorAction
[C#]
public virtual VisitorAction VisitHeaderFooterEnd(
HeaderFooter headerFooter
);

Parameters

headerFooter
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all header/footer nodes that it encounters.

[C#]

public void HeaderFooterToText()
{
    // Open the document that has headers and/or footers we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    HeaderFooterInfoPrinter visitor = new HeaderFooterInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());

    // An alternative way of visiting a document's header/footers section-by-section is by accessing the collection
    // We can also turn it into an array
    HeaderFooter[] headerFooters = doc.FirstSection.HeadersFooters.ToArray();
    Assert.AreEqual(6, headerFooters.Length);
}

/// <summary>
/// This Visitor implementation prints information about HeaderFooter nodes encountered in the document.
/// </summary>
public class HeaderFooterInfoPrinter : DocumentVisitor
{
    public HeaderFooterInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideHeaderFooter = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideHeaderFooter) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        IndentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.HeaderFooterType);
        mDocTraversalDepth++;
        mVisitorIsInsideHeaderFooter = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a HeaderFooter node is ended.
    /// </summary>
    public override VisitorAction VisitHeaderFooterEnd(HeaderFooter headerFooter)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[HeaderFooter end]");
        mVisitorIsInsideHeaderFooter = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideHeaderFooter;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitHeaderFooterStart Method

Called when enumeration of a header or footer in a section has started.

[Visual Basic]
Overridable Public Function VisitHeaderFooterStart( _
ByVal headerFooter As HeaderFooter _
) As VisitorAction
[C#]
public virtual VisitorAction VisitHeaderFooterStart(
HeaderFooter headerFooter
);

Parameters

headerFooter
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all header/footer nodes that it encounters.

[C#]

public void HeaderFooterToText()
{
    // Open the document that has headers and/or footers we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    HeaderFooterInfoPrinter visitor = new HeaderFooterInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());

    // An alternative way of visiting a document's header/footers section-by-section is by accessing the collection
    // We can also turn it into an array
    HeaderFooter[] headerFooters = doc.FirstSection.HeadersFooters.ToArray();
    Assert.AreEqual(6, headerFooters.Length);
}

/// <summary>
/// This Visitor implementation prints information about HeaderFooter nodes encountered in the document.
/// </summary>
public class HeaderFooterInfoPrinter : DocumentVisitor
{
    public HeaderFooterInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideHeaderFooter = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideHeaderFooter) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        IndentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.HeaderFooterType);
        mDocTraversalDepth++;
        mVisitorIsInsideHeaderFooter = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a HeaderFooter node is ended.
    /// </summary>
    public override VisitorAction VisitHeaderFooterEnd(HeaderFooter headerFooter)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[HeaderFooter end]");
        mVisitorIsInsideHeaderFooter = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideHeaderFooter;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitOfficeMathEnd Method

Called when enumeration of a Office Math object has ended.

[Visual Basic]
Overridable Public Function VisitOfficeMathEnd( _
ByVal officeMath As OfficeMath _
) As VisitorAction
[C#]
public virtual VisitorAction VisitOfficeMathEnd(
OfficeMath officeMath
);

Parameters

officeMath
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all OfficeMath nodes that it encounters.

[C#]

public void OfficeMathToText()
{
    // Open the document that has office math objects we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    OfficeMathInfoPrinter visitor = new OfficeMathInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about office math objects encountered in the document.
/// </summary>
public class OfficeMathInfoPrinter : DocumentVisitor
{
    public OfficeMathInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideOfficeMath = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideOfficeMath) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an OfficeMath node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitOfficeMathStart(OfficeMath officeMath)
    {
        IndentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.MathObjectType);
        mDocTraversalDepth++;
        mVisitorIsInsideOfficeMath = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a OfficeMath node is ended.
    /// </summary>
    public override VisitorAction VisitOfficeMathEnd(OfficeMath officeMath)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[OfficeMath end]");
        mVisitorIsInsideOfficeMath = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideOfficeMath;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitOfficeMathStart Method

Called when enumeration of a Office Math object has started.

[Visual Basic]
Overridable Public Function VisitOfficeMathStart( _
ByVal officeMath As OfficeMath _
) As VisitorAction
[C#]
public virtual VisitorAction VisitOfficeMathStart(
OfficeMath officeMath
);

Parameters

officeMath
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all OfficeMath nodes that it encounters.

[C#]

public void OfficeMathToText()
{
    // Open the document that has office math objects we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    OfficeMathInfoPrinter visitor = new OfficeMathInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about office math objects encountered in the document.
/// </summary>
public class OfficeMathInfoPrinter : DocumentVisitor
{
    public OfficeMathInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideOfficeMath = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideOfficeMath) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an OfficeMath node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitOfficeMathStart(OfficeMath officeMath)
    {
        IndentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.MathObjectType);
        mDocTraversalDepth++;
        mVisitorIsInsideOfficeMath = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a OfficeMath node is ended.
    /// </summary>
    public override VisitorAction VisitOfficeMathEnd(OfficeMath officeMath)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[OfficeMath end]");
        mVisitorIsInsideOfficeMath = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideOfficeMath;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitParagraphEnd Method

Called when enumeration of a paragraph has ended.

[Visual Basic]
Overridable Public Function VisitParagraphEnd( _
ByVal paragraph As Paragraph _
) As VisitorAction
[C#]
public virtual VisitorAction VisitParagraphEnd(
Paragraph paragraph
);

Parameters

paragraph
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitParagraphStart Method

Called when enumeration of a paragraph has started.

[Visual Basic]
Overridable Public Function VisitParagraphStart( _
ByVal paragraph As Paragraph _
) As VisitorAction
[C#]
public virtual VisitorAction VisitParagraphStart(
Paragraph paragraph
);

Parameters

paragraph
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitRowEnd Method

Called when enumeration of a table row has ended.

[Visual Basic]
Overridable Public Function VisitRowEnd( _
ByVal row As Row _
) As VisitorAction
[C#]
public virtual VisitorAction VisitRowEnd(
Row row
);

Parameters

row
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all tables that it encounters.

[C#]

public void TableToText()
{
    // Open the document that has tables we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    TableInfoPrinter visitor = new TableInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of all tables encountered in the document.
/// </summary>
public class TableInfoPrinter : DocumentVisitor
{
    public TableInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideTable = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they consist of text from cells
        // So we are only interested in runs that are children of table nodes
        if (mVisitorIsInsideTable) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Table is encountered in the document.
    /// </summary>
    public override VisitorAction VisitTableStart(Table table)
    {
        int rows = 0;
        int columns = 0;

        if (table.Rows.Count > 0)
        {
            rows = table.Rows.Count;
            columns = table.FirstRow.Count;
        }

        IndentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
        mDocTraversalDepth++;
        mVisitorIsInsideTable = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Table node is ended.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Table end]");
        mVisitorIsInsideTable = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Row node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRowStart(Row row)
    {
        IndentAndAppendLine("[Row start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Row node is ended.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Row end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Cell node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCellStart(Cell cell)
    {
        Row row = cell.ParentRow;
        Table table = row.ParentTable;

        IndentAndAppendLine("[Cell start] Row " + (table.IndexOf(row) + 1) + ", Col " +
                            (row.IndexOf(cell) + 1) + "");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Cell end]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideTable;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitRowStart Method

Called when enumeration of a table row has started.

[Visual Basic]
Overridable Public Function VisitRowStart( _
ByVal row As Row _
) As VisitorAction
[C#]
public virtual VisitorAction VisitRowStart(
Row row
);

Parameters

row
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all tables that it encounters.

[C#]

public void TableToText()
{
    // Open the document that has tables we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    TableInfoPrinter visitor = new TableInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of all tables encountered in the document.
/// </summary>
public class TableInfoPrinter : DocumentVisitor
{
    public TableInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideTable = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they consist of text from cells
        // So we are only interested in runs that are children of table nodes
        if (mVisitorIsInsideTable) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Table is encountered in the document.
    /// </summary>
    public override VisitorAction VisitTableStart(Table table)
    {
        int rows = 0;
        int columns = 0;

        if (table.Rows.Count > 0)
        {
            rows = table.Rows.Count;
            columns = table.FirstRow.Count;
        }

        IndentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
        mDocTraversalDepth++;
        mVisitorIsInsideTable = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Table node is ended.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Table end]");
        mVisitorIsInsideTable = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Row node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRowStart(Row row)
    {
        IndentAndAppendLine("[Row start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Row node is ended.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Row end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Cell node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCellStart(Cell cell)
    {
        Row row = cell.ParentRow;
        Table table = row.ParentTable;

        IndentAndAppendLine("[Cell start] Row " + (table.IndexOf(row) + 1) + ", Col " +
                            (row.IndexOf(cell) + 1) + "");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Cell end]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideTable;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitRun Method

Called when a run of text in the is encountered.

[Visual Basic]
Overridable Public Function VisitRun( _
ByVal run As Run _
) As VisitorAction
[C#]
public virtual VisitorAction VisitRun(
Run run
);

Parameters

run
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitSectionEnd Method

Called when enumeration of a section has ended.

[Visual Basic]
Overridable Public Function VisitSectionEnd( _
ByVal section As Section _
) As VisitorAction
[C#]
public virtual VisitorAction VisitSectionEnd(
Section section
);

Parameters

section
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitSectionStart Method

Called when enumeration of a section has started.

[Visual Basic]
Overridable Public Function VisitSectionStart( _
ByVal section As Section _
) As VisitorAction
[C#]
public virtual VisitorAction VisitSectionStart(
Section section
);

Parameters

section
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitShapeEnd Method

Called when enumeration of a shape has ended.

[Visual Basic]
Overridable Public Function VisitShapeEnd( _
ByVal shape As Shape _
) As VisitorAction
[C#]
public virtual VisitorAction VisitShapeEnd(
Shape shape
);

Parameters

shape
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitShapeStart Method

Called when enumeration of a shape has started.

[Visual Basic]
Overridable Public Function VisitShapeStart( _
ByVal shape As Shape _
) As VisitorAction
[C#]
public virtual VisitorAction VisitShapeStart(
Shape shape
);

Parameters

shape
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitSmartTagEnd Method

Called when enumeration of a smart tag has ended.

[Visual Basic]
Overridable Public Function VisitSmartTagEnd( _
ByVal smartTag As SmartTag _
) As VisitorAction
[C#]
public virtual VisitorAction VisitSmartTagEnd(
SmartTag smartTag
);

Parameters

smartTag
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all smart tag nodes that it encounters.

[C#]

public void SmartTagToText()
{
    // Open the document that has smart tags we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.SmartTag.docx");

    // Create an object that inherits from the DocumentVisitor class
    SmartTagInfoPrinter visitor = new SmartTagInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about smart tags encountered in the document.
/// </summary>
public class SmartTagInfoPrinter : DocumentVisitor
{
    public SmartTagInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideSmartTag = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideSmartTag) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        IndentAndAppendLine("[SmartTag start] Name: " + smartTag.Element);
        mDocTraversalDepth++;
        mVisitorIsInsideSmartTag = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[SmartTag end]");
        mVisitorIsInsideSmartTag = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideSmartTag;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitSmartTagStart Method

Called when enumeration of a smart tag has started.

[Visual Basic]
Overridable Public Function VisitSmartTagStart( _
ByVal smartTag As SmartTag _
) As VisitorAction
[C#]
public virtual VisitorAction VisitSmartTagStart(
SmartTag smartTag
);

Parameters

smartTag
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all smart tag nodes that it encounters.

[C#]

public void SmartTagToText()
{
    // Open the document that has smart tags we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.SmartTag.docx");

    // Create an object that inherits from the DocumentVisitor class
    SmartTagInfoPrinter visitor = new SmartTagInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about smart tags encountered in the document.
/// </summary>
public class SmartTagInfoPrinter : DocumentVisitor
{
    public SmartTagInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideSmartTag = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideSmartTag) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        IndentAndAppendLine("[SmartTag start] Name: " + smartTag.Element);
        mDocTraversalDepth++;
        mVisitorIsInsideSmartTag = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[SmartTag end]");
        mVisitorIsInsideSmartTag = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideSmartTag;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitSpecialChar Method

Called when a SpecialChar node is encountered in the document.

[Visual Basic]
Overridable Public Function VisitSpecialChar( _
ByVal specialChar As SpecialChar _
) As VisitorAction
[C#]
public virtual VisitorAction VisitSpecialChar(
SpecialChar specialChar
);

Parameters

specialChar
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Remarks

This method is not be called for generic control characters (see ControlChar) that can be present in the document.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitStructuredDocumentTagEnd Method

Called when enumeration of a structured document tag has ended.

[Visual Basic]
Overridable Public Function VisitStructuredDocumentTagEnd( _
ByVal sdt As StructuredDocumentTag _
) As VisitorAction
[C#]
public virtual VisitorAction VisitStructuredDocumentTagEnd(
StructuredDocumentTag sdt
);

Parameters

sdt
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structured document tag nodes that it encounters.

[C#]

public void StructuredDocumentTagToText()
{
    // Open the document that has structured document tags we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    StructuredDocumentTagInfoPrinter visitor = new StructuredDocumentTagInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about structured document tags encountered in the document.
/// </summary>
public class StructuredDocumentTagInfoPrinter : DocumentVisitor
{
    public StructuredDocumentTagInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideStructuredDocumentTag = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideStructuredDocumentTag) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a StructuredDocumentTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitStructuredDocumentTagStart(StructuredDocumentTag sdt)
    {
        IndentAndAppendLine("[StructuredDocumentTag start] Title: " + sdt.Title);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a StructuredDocumentTag node is ended.
    /// </summary>
    public override VisitorAction VisitStructuredDocumentTagEnd(StructuredDocumentTag sdt)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[StructuredDocumentTag end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private readonly bool mVisitorIsInsideStructuredDocumentTag;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitStructuredDocumentTagStart Method

Called when enumeration of a structured document tag has started.

[Visual Basic]
Overridable Public Function VisitStructuredDocumentTagStart( _
ByVal sdt As StructuredDocumentTag _
) As VisitorAction
[C#]
public virtual VisitorAction VisitStructuredDocumentTagStart(
StructuredDocumentTag sdt
);

Parameters

sdt
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structured document tag nodes that it encounters.

[C#]

public void StructuredDocumentTagToText()
{
    // Open the document that has structured document tags we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    StructuredDocumentTagInfoPrinter visitor = new StructuredDocumentTagInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about structured document tags encountered in the document.
/// </summary>
public class StructuredDocumentTagInfoPrinter : DocumentVisitor
{
    public StructuredDocumentTagInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideStructuredDocumentTag = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideStructuredDocumentTag) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a StructuredDocumentTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitStructuredDocumentTagStart(StructuredDocumentTag sdt)
    {
        IndentAndAppendLine("[StructuredDocumentTag start] Title: " + sdt.Title);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a StructuredDocumentTag node is ended.
    /// </summary>
    public override VisitorAction VisitStructuredDocumentTagEnd(StructuredDocumentTag sdt)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[StructuredDocumentTag end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private readonly bool mVisitorIsInsideStructuredDocumentTag;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitSubDocument Method

Called when a subDocument is encountered.

[Visual Basic]
Overridable Public Function VisitSubDocument( _
ByVal subDocument As SubDocument _
) As VisitorAction
[C#]
public virtual VisitorAction VisitSubDocument(
SubDocument subDocument
);

Parameters

subDocument
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all structure nodes that it encounters.

[C#]

public void DocStructureToText()
{
    // Open the document that has nodes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    DocStructurePrinter visitor = new DocStructurePrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about sections, bodies, paragraphs and runs encountered in the document.
/// </summary>
public class DocStructurePrinter : DocumentVisitor
{
    public DocStructurePrinter()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Document node is encountered.
    /// </summary>
    public override VisitorAction VisitDocumentStart(Document doc)
    {
        int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

        // A Document node is at the root of every document, so if we let a document accept a visitor, this will be the first visitor action to be carried out
        IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
        mDocTraversalDepth++;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Document is ended.
    /// </summary>
    public override VisitorAction VisitDocumentEnd(Document doc)
    {
        // If we let a document accept a visitor, this will be the last visitor action to be carried out
        mDocTraversalDepth--;
        IndentAndAppendLine("[Document end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Section node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSectionStart(Section section)
    {
        // Get the index of our section within the document
        NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
        int sectionIndex = docSections.IndexOf(section);

        IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Section node is ended.
    /// </summary>
    public override VisitorAction VisitSectionEnd(Section section)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Section end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Body node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBodyStart(Body body)
    {
        int paragraphCount = body.Paragraphs.Count;
        IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Body node is ended.
    /// </summary>
    public override VisitorAction VisitBodyEnd(Body body)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Body end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        IndentAndAppendLine("[Paragraph start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Paragraph node is ended.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Paragraph end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SubDocument node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSubDocument(SubDocument subDocument)
    {
        IndentAndAppendLine("[SubDocument]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitTableEnd Method

Called when enumeration of a table has ended.

[Visual Basic]
Overridable Public Function VisitTableEnd( _
ByVal table As Table _
) As VisitorAction
[C#]
public virtual VisitorAction VisitTableEnd(
Table table
);

Parameters

table
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all tables that it encounters.

[C#]

public void TableToText()
{
    // Open the document that has tables we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    TableInfoPrinter visitor = new TableInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of all tables encountered in the document.
/// </summary>
public class TableInfoPrinter : DocumentVisitor
{
    public TableInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideTable = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they consist of text from cells
        // So we are only interested in runs that are children of table nodes
        if (mVisitorIsInsideTable) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Table is encountered in the document.
    /// </summary>
    public override VisitorAction VisitTableStart(Table table)
    {
        int rows = 0;
        int columns = 0;

        if (table.Rows.Count > 0)
        {
            rows = table.Rows.Count;
            columns = table.FirstRow.Count;
        }

        IndentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
        mDocTraversalDepth++;
        mVisitorIsInsideTable = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Table node is ended.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Table end]");
        mVisitorIsInsideTable = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Row node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRowStart(Row row)
    {
        IndentAndAppendLine("[Row start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Row node is ended.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Row end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Cell node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCellStart(Cell cell)
    {
        Row row = cell.ParentRow;
        Table table = row.ParentTable;

        IndentAndAppendLine("[Cell start] Row " + (table.IndexOf(row) + 1) + ", Col " +
                            (row.IndexOf(cell) + 1) + "");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Cell end]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideTable;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitTableStart Method

Called when enumeration of a table has started.

[Visual Basic]
Overridable Public Function VisitTableStart( _
ByVal table As Table _
) As VisitorAction
[C#]
public virtual VisitorAction VisitTableStart(
Table table
);

Parameters

table
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

Example

Traverse a document with a visitor that prints all tables that it encounters.

[C#]

public void TableToText()
{
    // Open the document that has tables we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    TableInfoPrinter visitor = new TableInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about and contents of all tables encountered in the document.
/// </summary>
public class TableInfoPrinter : DocumentVisitor
{
    public TableInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideTable = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        // We want to print the contents of runs, but only if they consist of text from cells
        // So we are only interested in runs that are children of table nodes
        if (mVisitorIsInsideTable) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Table is encountered in the document.
    /// </summary>
    public override VisitorAction VisitTableStart(Table table)
    {
        int rows = 0;
        int columns = 0;

        if (table.Rows.Count > 0)
        {
            rows = table.Rows.Count;
            columns = table.FirstRow.Count;
        }

        IndentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
        mDocTraversalDepth++;
        mVisitorIsInsideTable = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Table node is ended.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Table end]");
        mVisitorIsInsideTable = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Row node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRowStart(Row row)
    {
        IndentAndAppendLine("[Row start]");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Row node is ended.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Row end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Cell node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCellStart(Cell cell)
    {
        Row row = cell.ParentRow;
        Table table = row.ParentTable;

        IndentAndAppendLine("[Cell start] Row " + (table.IndexOf(row) + 1) + ", Col " +
                            (row.IndexOf(cell) + 1) + "");
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Cell end]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideTable;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

DocumentVisitor Class | Aspose.Words Namespace


DropCapPosition Enumeration

Specifies the position for a drop cap text.

[Visual Basic]
Public Enum DropCapPosition
[C#]
public enum DropCapPosition

Example

Shows how to set the position of a drop cap.

[C#]

// Create a blank document
Document doc = new Document();

// Every paragraph has its own drop cap setting
Paragraph para = doc.FirstSection.Body.FirstParagraph;

// By default, it is "none", for no drop caps
Assert.AreEqual(Aspose.Words.DropCapPosition.None, para.ParagraphFormat.DropCapPosition);

// Move the first capital to outside the text margin
para.ParagraphFormat.DropCapPosition = Aspose.Words.DropCapPosition.Margin;

// This text will be affected
para.Runs.Add(new Run(doc, "Hello World!"));

doc.Save(ArtifactsDir + "Paragraph.DropCap.docx");

Members

Member Name | Description | Value
None | The paragraph does not have a drop cap. | 0
Normal | The drop cap is positioned inside the text margin on the anchor paragraph. | 1
Margin | The drop cap is positioned outside the text margin on the anchor paragraph. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


EditableRange Class

Represents a single editable range.

For a list of all members of this type, see EditableRange Members.

System.Object
Aspose.Words.EditableRange

[Visual Basic]
Public Class EditableRange
[C#]
public class EditableRange

Remarks

EditableRange is a "facade" object that encapsulates two nodes EditableRangeStart and EditableRangeEnd in a document tree and allows to work with an editable range as a single object.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

EditableRange Members | Aspose.Words Namespace


EditableRange Members

EditableRange overview

Public Instance Properties

EditableRangeEnd | Gets the node that represents the end of the editable range.
EditableRangeStart | Gets the node that represents the start of the editable range.
EditorGroup | Returns or sets an alias (or editing group) which shall be used to determine if the current user shall be allowed to edit this editable range.
Id | Gets the editable range identifier.
SingleUser | Returns or sets the single user for editable range.

Public Instance Methods

Remove Removes the editable range from the document. Does not remove content inside the editable range.

See Also

EditableRange Class | Aspose.Words Namespace


EditableRange Properties

The properties of the EditableRange class are listed below. For a complete list of EditableRange class members, see the EditableRange Members topic.

Public Instance Properties

EditableRangeEnd | Gets the node that represents the end of the editable range.
EditableRangeStart | Gets the node that represents the start of the editable range.
EditorGroup | Returns or sets an alias (or editing group) which shall be used to determine if the current user shall be allowed to edit this editable range.
Id | Gets the editable range identifier.
SingleUser | Returns or sets the single user for editable range.

See Also

EditableRange Class | Aspose.Words Namespace


EditableRangeEnd Property

Aspose.Words

EditableRange.EditableRangeEnd Property

Gets the node that represents the end of the editable range.

[Visual Basic]
Public ReadOnly Property EditableRangeEnd As EditableRangeEnd
[C#]
public EditableRangeEnd EditableRangeEnd {get;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRange Class | Aspose.Words Namespace


EditableRangeStart Property

Aspose.Words

EditableRange.EditableRangeStart Property

Gets the node that represents the start of the editable range.

[Visual Basic]
Public ReadOnly Property EditableRangeStart As EditableRangeStart
[C#]
public EditableRangeStart EditableRangeStart {get;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRange Class | Aspose.Words Namespace


EditorGroup Property

Aspose.Words

EditableRange.EditorGroup Property

Returns or sets an alias (or editing group) which shall be used to determine if the current user shall be allowed to edit this editable range.

[Visual Basic]
Public Property EditorGroup As EditorType
[C#]
public EditorType EditorGroup {get; set;}

Remarks

Single user and editor group cannot be set simultaneously for the specific editable range, if the one is set, the other will be clear.

Example

Shows how to add editing group for editable ranges

[C#]

EditableRangeStart startRange1 = builder.StartEditableRange();

builder.Writeln("EditableRange_1_1");
builder.Writeln("EditableRange_1_2");

// Sets the editor for editable range region
startRange1.EditableRange.EditorGroup = EditorType.Everyone;

See Also

EditableRange Class | Aspose.Words Namespace


Id Property

Aspose.Words

EditableRange.Id Property

Gets the editable range identifier.

[Visual Basic]
Public ReadOnly Property Id As Integer
[C#]
public int Id {get;}

Remarks

The region must be demarcated using the EditableRangeStart and EditableRangeEnd

Editable range identifiers are supposed to be unique across a document and Aspose.Words automatically maintains editable range identifiers when loading, saving and combining documents.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRange Class | Aspose.Words Namespace


SingleUser Property

Aspose.Words

EditableRange.SingleUser Property

Returns or sets the single user for editable range.

[Visual Basic]
Public Property SingleUser As String
[C#]
public string SingleUser {get; set;}

Remarks

This editor can be stored in one of the following forms:

DOMAIN\Username - for users whose access shall be authenticated using the current user's domain credentials.

user@domain.com - for users whose access shall be authenticated using the user's e-mail address as credentials.

user - for users whose access shall be authenticated using the current user's machine credentials.

Single user and editor group cannot be set simultaneously for the specific editable range, if the one is set, the other will be clear.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRange Class | Aspose.Words Namespace


EditableRange Methods

The methods of the EditableRange class are listed below. For a complete list of EditableRange class members, see the EditableRange Members topic.

Public Instance Methods

Remove Removes the editable range from the document. Does not remove content inside the editable range.

See Also

EditableRange Class | Aspose.Words Namespace


EditableRange.Remove Method

Removes the editable range from the document. Does not remove content inside the editable range.

[Visual Basic]
Public Sub Remove()
[C#]
public void Remove();

Example

Shows how to remove an editable range from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an EditableRange so we can remove it. Does not have to be well-formed.
EditableRangeStart edRange1Start = builder.StartEditableRange();
EditableRange editableRange1 = edRange1Start.EditableRange;
builder.Writeln("Paragraph inside editable range");
EditableRangeEnd edRange1End = builder.EndEditableRange();

// Remove the range that was just made.
editableRange1.Remove();

See Also

EditableRange Class | Aspose.Words Namespace


EditableRangeEnd Class

Represents an end of an editable range in a Word document.

For a list of all members of this type, see EditableRangeEnd Members.

System.Object
Aspose.Words.Node
Aspose.Words.EditableRangeEnd

[Visual Basic]
NotInheritable Public Class EditableRangeEnd
Inherits Node
[C#]
public sealed class EditableRangeEnd : Node

Remarks

A complete editable range in a Word document consists of a EditableRangeStart and a matching EditableRangeEnd with the same Id.

EditableRangeStart and EditableRangeEnd are just markers inside a document that specify where the editable range starts and ends.

Use the EditableRange class as a "facade" to work with an editable range as a single object.

Note Currently editable ranges are supported only at the inline-level, that is inside Paragraph, but editable range start and editable range end can be in different paragraphs.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

EditableRangeEnd Members | Aspose.Words Namespace


EditableRangeEnd Members

EditableRangeEnd overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
EditableRangeStart | Corresponding EditableRangeStart, received by ID.
Id | Specifies the identifier of the editable range.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns EditableRangeEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

EditableRangeEnd Class | Aspose.Words Namespace


EditableRangeEnd Properties

The properties of the EditableRangeEnd class are listed below. For a complete list of EditableRangeEnd class members, see the EditableRangeEnd Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
EditableRangeStart | Corresponding EditableRangeStart, received by ID.
Id | Specifies the identifier of the editable range.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns EditableRangeEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

EditableRangeEnd Class | Aspose.Words Namespace


EditableRangeStart Property

Aspose.Words

EditableRangeEnd.EditableRangeStart Property

Corresponding EditableRangeStart, received by ID.

[Visual Basic]
Public ReadOnly Property EditableRangeStart As EditableRangeStart
[C#]
public EditableRangeStart EditableRangeStart {get;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeEnd Class | Aspose.Words Namespace


Id Property

Aspose.Words

EditableRangeEnd.Id Property

Specifies the identifier of the editable range.

[Visual Basic]
Public Property Id As Integer
[C#]
public int Id {get; set;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeEnd Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

EditableRangeEnd.NodeType Property

Returns EditableRangeEnd.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeEnd Class | Aspose.Words Namespace


EditableRangeEnd Methods

The methods of the EditableRangeEnd class are listed below. For a complete list of EditableRangeEnd class members, see the EditableRangeEnd Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

EditableRangeEnd Class | Aspose.Words Namespace


EditableRangeEnd.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitEditableRangeEnd.

For more info see the Visitor design pattern.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeEnd Class | Aspose.Words Namespace


EditableRangeStart Class

Represents a start of an editable range in a Word document.

For a list of all members of this type, see EditableRangeStart Members.

System.Object
Aspose.Words.Node
Aspose.Words.EditableRangeStart

[Visual Basic]
NotInheritable Public Class EditableRangeStart
Inherits Node
[C#]
public sealed class EditableRangeStart : Node

Remarks

A complete editable range in a Word document consists of a EditableRangeStart and a matching EditableRangeEnd with the same Id.

EditableRangeStart and EditableRangeEnd are just markers inside a document that specify where the editable range starts and ends.

Use the EditableRange class as a "facade" to work with an editable range as a single object.

Note Currently editable ranges are supported only at the inline-level, that is inside Paragraph, but editable range start and editable range end can be in different paragraphs.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

EditableRangeStart Members | Aspose.Words Namespace


EditableRangeStart Members

EditableRangeStart overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
EditableRange | Gets the facade object that encapsulates this editable range start and end.
Id | Specifies the identifier of the editable range.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns EditableRangeStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

EditableRangeStart Class | Aspose.Words Namespace


EditableRangeStart Properties

The properties of the EditableRangeStart class are listed below. For a complete list of EditableRangeStart class members, see the EditableRangeStart Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
EditableRange | Gets the facade object that encapsulates this editable range start and end.
Id | Specifies the identifier of the editable range.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns EditableRangeStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

EditableRangeStart Class | Aspose.Words Namespace


EditableRange Property

Aspose.Words

EditableRangeStart.EditableRange Property

Gets the facade object that encapsulates this editable range start and end.

[Visual Basic]
Public ReadOnly Property EditableRange As EditableRange
[C#]
public EditableRange EditableRange {get;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeStart Class | Aspose.Words Namespace


Id Property

Aspose.Words

EditableRangeStart.Id Property

Specifies the identifier of the editable range.

[Visual Basic]
Public Property Id As Integer
[C#]
public int Id {get; set;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeStart Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

EditableRangeStart.NodeType Property

Returns EditableRangeStart.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeStart Class | Aspose.Words Namespace


EditableRangeStart Methods

The methods of the EditableRangeStart class are listed below. For a complete list of EditableRangeStart class members, see the EditableRangeStart Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

EditableRangeStart Class | Aspose.Words Namespace


EditableRangeStart.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitEditableRangeStart.

For more info see the Visitor design pattern.

Example

Shows how to start and end an editable range.

[C#]

public void CreateEditableRanges()
{
    Document doc = new Document(MyDir + "Document.doc");
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Start an editable range
    EditableRangeStart edRange1Start = builder.StartEditableRange();

    // An EditableRange object is created for the EditableRangeStart that we just made
    EditableRange editableRange1 = edRange1Start.EditableRange;

    // Put something inside the editable range
    builder.Writeln("Paragraph inside first editable range");

    // An editable range is well-formed if it has a start and an end
    // Multiple editable ranges can be nested and overlapping
    EditableRangeEnd edRange1End = builder.EndEditableRange();

    // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with
    EditableRangeStart edRange2Start = builder.StartEditableRange();
    builder.Writeln("Paragraph inside second editable range");
    EditableRange editableRange2 = edRange2Start.EditableRange;
    EditableRangeEnd edRange2End = builder.EndEditableRange(edRange2Start);

    // Editable range starts and ends have their own respective node types
    Assert.AreEqual(NodeType.EditableRangeStart, edRange1Start.NodeType);
    Assert.AreEqual(NodeType.EditableRangeEnd, edRange1End.NodeType);

    // Editable range IDs are unique and set automatically
    Assert.AreEqual(0, editableRange1.Id);
    Assert.AreEqual(1, editableRange2.Id);

    // Editable range starts and ends always belong to a range
    Assert.AreEqual(edRange1Start, editableRange1.EditableRangeStart);
    Assert.AreEqual(edRange1End, editableRange1.EditableRangeEnd);

    // They also inherit the ID of the entire editable range that they belong to
    Assert.AreEqual(editableRange1.Id, edRange1Start.Id);
    Assert.AreEqual(editableRange1.Id, edRange1End.Id);
    Assert.AreEqual(editableRange2.Id, edRange2Start.EditableRange.Id);
    Assert.AreEqual(editableRange2.Id, edRange2End.EditableRangeStart.EditableRange.Id);

    // If the editable range was found in a document, it will probably have something in the single user property
    // But if we make one programmatically, the property is null by default
    Assert.AreEqual(null, editableRange1.SingleUser);

    // We have to set it ourselves if we want the ranges to belong to somebody
    editableRange1.SingleUser = "john.doe@myoffice.com";
    editableRange2.SingleUser = "jane.doe@myoffice.com";

    // Initialize a custom visitor for editable ranges that will print their contents
    EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter();

    // Both the start and end of an editable range can accept visitors, but not the editable range itself
    edRange1Start.Accept(editableRangeReader);
    edRange2End.Accept(editableRangeReader);

    // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor
    editableRangeReader.Reset();
    doc.Accept(editableRangeReader);

    Console.WriteLine(editableRangeReader.ToText());
}

/// <summary>
/// Visitor implementation that prints attributes and contents of ranges.
/// </summary>
public class EditableRangeInfoPrinter : DocumentVisitor
{
    public EditableRangeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string ToText()
    {
        return mBuilder.ToString();
    }

    public void Reset()
    {
        mBuilder.Clear();
        mInsideEditableRange = false;
    }

    /// <summary>
    /// Called when an EditableRangeStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeStart(EditableRangeStart editableRangeStart)
    {
        mBuilder.AppendLine(" -- Editable range found! -- ");
        mBuilder.AppendLine("\tID: " + editableRangeStart.Id);
        mBuilder.AppendLine("\tUser: " + editableRangeStart.EditableRange.SingleUser);
        mBuilder.AppendLine("\tContents: ");

        mInsideEditableRange = true;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an EditableRangeEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitEditableRangeEnd(EditableRangeEnd editableRangeEnd)
    {
        mBuilder.AppendLine(" -- End of editable range -- ");

        mInsideEditableRange = false;

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mInsideEditableRange) mBuilder.AppendLine("\t\"" + run.Text + "\"");

        // Let the visitor continue visiting other nodes
        return VisitorAction.Continue;
    }

    private bool mInsideEditableRange;
    private readonly StringBuilder mBuilder;
}

See Also

EditableRangeStart Class | Aspose.Words Namespace


EditingLanguage Enumeration

Specifies the editing language.

[Visual Basic]
Public Enum EditingLanguage
[C#]
public enum EditingLanguage

Example

Shows how to set up language preferences that will be used when document is loading

[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LanguagePreferences.AddEditingLanguage(EditingLanguage.Japanese);

Document doc = new Document(MyDir + "Document.EditingLanguage.docx", loadOptions);

int localeIdFarEast = doc.Styles.DefaultFont.LocaleIdFarEast;
if (localeIdFarEast == (int)EditingLanguage.Japanese)
    Console.WriteLine("The document either has no any FarEast language set in defaults or it was set to Japanese originally.");
else
    Console.WriteLine("The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");

Members

Member Name | Description | Value
Afrikaans |  | 1078
Albanian |  | 1052
Alsatian |  | 1156
Amharic |  | 1118
ArabicAlgeria |  | 5121
ArabicBahrain |  | 15361
ArabicEgypt |  | 3073
ArabicIraq |  | 2049
ArabicJordan |  | 11265
ArabicKuwait |  | 13313
ArabicLebanon |  | 12289
ArabicLibya |  | 4097
ArabicMorocco |  | 6145
ArabicOman |  | 8193
ArabicQatar |  | 16385
ArabicSaudiArabia |  | 1025
ArabicSyria |  | 10241
ArabicTunisia |  | 7169
ArabicUAE |  | 14337
ArabicYemen |  | 9217
Armenian |  | 1067
Assamese |  | 1101
AzerbaijaniCyrillic |  | 2092
AzerbaijaniLatin |  | 1068
BanglaBangladesh |  | 2117
BanglaIndia |  | 1093
Bashkir |  | 1133
Basque |  | 1069
Belarusian |  | 1059
BosnianCyrillic |  | 8218
BosnianLatin |  | 5146
Breton |  | 1150
Bulgarian |  | 1026
Burmese |  | 1109
Catalan |  | 1027
CentralKurdishIraq |  | 1170
Cherokee |  | 1116
ChineseHongKong |  | 3076
ChineseMacao |  | 5124
ChinesePRC |  | 2052
ChineseSingapore |  | 4100
ChineseTaiwan |  | 1028
Corsican |  | 1155
CroatianBozniaAndHerzegovina |  | 4122
Croatian |  | 1050
Czech |  | 1029
Danish |  | 1030
Divehi |  | 1125
DutchBelgium |  | 2067
DutchNetherlands |  | 1043
Edo |  | 1126
EnglishAustralia |  | 3081
EnglishBelize |  | 10249
EnglishCanada |  | 4105
EnglishCaribbean |  | 9225
EnglishHongKong |  | 15369
EnglishIndia |  | 16393
EnglishIndonesia |  | 14345
EnglishIreland |  | 6153
EnglishJamaica |  | 8201
EnglishMalaysia |  | 17417
EnglishNewZealand |  | 5129
EnglishPhilippines |  | 13321
EnglishSingapore |  | 18441
EnglishSouthAfrica |  | 7177
EnglishTrinidadAndTobago |  | 11273
EnglishUK |  | 2057
EnglishUS |  | 1033
EnglishZimbabwe |  | 12297
Estonian |  | 1061
Faeroese |  | 1080
Filipino |  | 1124
Finnish |  | 1035
FrenchBelgium |  | 2060
FrenchCanada |  | 3084
FrenchFrance |  | 1036
FrenchLuxembourg |  | 5132
FrenchMonaco |  | 6156
FrenchSwitzerland |  | 4108
Frisian |  | 1122
FulahLatinSenegal |  | 2151
FulahNigeria |  | 1127
Galician |  | 1110
Georgian |  | 1079
GermanAustria |  | 3079
GermanGermany |  | 1031
GermanLiechtenstein |  | 5127
GermanLuxembourg |  | 4103
GermanSwitzerland |  | 2055
Greek |  | 1032
Greenlandic |  | 1135
Guarani |  | 1140
Gujarati |  | 1095
Hausa |  | 1128
Hawaiian |  | 1141
Hebrew |  | 1037
Hindi |  | 1081
Hungarian |  | 1038
Icelandic |  | 1039
Igbo |  | 1136
InariSamiFinland |  | 9275
Indonesian |  | 1057
InuktitutLatin |  | 31837
InuktitutSyllabics |  | 30813
Irish |  | 2108
IsiXhosa |  | 1076
IsiZulu |  | 1077
ItalianItaly |  | 1040
ItalianSwitzerland |  | 2064
Japanese |  | 1041
Kannada |  | 1099
Kanuri |  | 1137
Kashmiri |  | 2144
KashmiriArabic |  | 1120
Kazakh |  | 1087
Khmer |  | 1107
Kiche |  | 31878
Kinyarwanda |  | 1159
Kiswahili |  | 1089
Konkani |  | 1111
Korean |  | 1042
Kyrgyz |  | 1088
Lao |  | 1108
Latin |  | 1142
Latvian |  | 1062
Lithuanian |  | 1063
LowerSorbian |  | 31790
LuleSamiNorway |  | 4155
LuleSamiSweden |  | 5179
Luxembougish |  | 1134
Macedonian |  | 1071
MalayMalaysia |  | 1086
MalayBruneiDarussalam |  | 2110
Malayalam |  | 1100
Maltese |  | 1082
Manipuri |  | 1112
Maori |  | 1153
MapudungunChile |  | 1146
Marathi |  | 1102
Mohawk |  | 1148
MongolianCyrillic |  | 1104
MongolianMongolian |  | 2128
Nepali |  | 1121
NorthernSamiFinland |  | 3131
NorthernSamiNorway |  | 1083
NorthernSamiSweden |  | 2107
NorwegianBokmal |  | 1044
NorwegianNynorsk |  | 2068
Oriya |  | 1096
Oromo |  | 1138
Papiamentu |  | 1145
Pashto |  | 1123
Persian |  | 1065
Polish |  | 1045
PortugueseBrazil |  | 1046
PortuguesePortugal |  | 2070
PunjabiIndia |  | 1094
PunjabiPakistan |  | 2118
QuechuaBolivia |  | 1131
QuechuaEcuador |  | 2155
QuechuaPeru |  | 3179
Romanian |  | 1048
Romansh |  | 1047
Russian |  | 1049
Sakha |  | 1157
Sanskrit |  | 1103
ScottishGaelic |  | 1169
SerbianCyrillicBosniaAndHerzegovina |  | 7194
SerbianCyrillicSerbiaAndMontenegro |  | 3098
SerbianLatinBosniaAndHerzegovina |  | 6170
SerbianLatinSerbiaAndMontenegro |  | 2074
Sindhi |  | 2137
SindhiDevanagaric |  | 1113
Sinhalese |  | 1115
Slovak |  | 1051
Slovenian |  | 1060
Somali |  | 1143
Sorbian |  | 1070
SpanishArgentina |  | 11274
SpanishBolivia |  | 16394
SpanishChile |  | 13322
SpanishColombia |  | 9226
SpanishCostaRica |  | 5130
SpanishDominicanRepublic |  | 7178
SpanishEcuador |  | 12298
SpanishElSalvador |  | 17418
SpanishGuatemala |  | 4106
SpanishHonduras |  | 18442
SpanishMexico |  | 2058
SpanishNicaragua |  | 19466
SpanishPanama |  | 6154
SpanishParaguay |  | 15370
SpanishPeru |  | 10250
SpanishPuertoRico |  | 20490
SpanishSpainModernSort |  | 3082
SpanishSpainTraditionalSort |  | 1034
SpanishUruguay |  | 14346
SpanishVenezuela |  | 8202
Sutu |  | 1072
SwedishFinland |  | 2077
SwedishSweden |  | 1053
Syriac |  | 1114
Tajik |  | 1064
Tamazight |  | 1119
TamazightLatin |  | 2143
Tamil |  | 1097
Tatar |  | 1092
Telugu |  | 1098
Thai |  | 1054
TibetanButan |  | 2129
TibetanChina |  | 1105
TigrignaEritrea |  | 2163
TigrignaEthiopia |  | 1139
Tsonga |  | 1073
Tswana |  | 1074
Turkish |  | 1055
Turkmen |  | 1090
Ukrainian |  | 1058
Urdu |  | 1056
UzbekCyrillic |  | 2115
UzbekLatin |  | 1091
Venda |  | 1075
Vietnamese |  | 1066
Welsh |  | 1106
Yi |  | 1144
Yiddish |  | 1085
Yoruba |  | 1130

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


EditorType Enumeration

Specifies the set of possible aliases (or editing groups) which can be used as aliases to determine if the current user shall be allowed to edit a single range defined by an editable range within a document.

[Visual Basic]
Public Enum EditorType
[C#]
public enum EditorType

Example

Shows how to add editing group for editable ranges

[C#]

EditableRangeStart startRange1 = builder.StartEditableRange();

builder.Writeln("EditableRange_1_1");
builder.Writeln("EditableRange_1_2");

// Sets the editor for editable range region
startRange1.EditableRange.EditorGroup = EditorType.Everyone;

Members

Member Name | Description | Value
Unspecified | Means that editor type is not specified. | 0
Administrators | Specifies that users associated with the Administrators group shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 1
Contributors | Specifies that users associated with the Contributors group shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 2
Current | Specifies that users associated with the Current group shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 3
Editors | Specifies that users associated with the Editors group shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 4
Everyone | Specifies that all users that open the document shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 5
None | Specifies that none of the users that open the document shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 6
Owners | Specifies that users associated with the Owners group shall be allowed to edit editable ranges using this editing type when document protection is enabled. | 7
Default | Same as Unspecified. | 0

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


EndnoteOptions Class

Represents the endnote numbering options for a document or section.

For a list of all members of this type, see EndnoteOptions Members.

System.Object
Aspose.Words.EndnoteOptions

[Visual Basic]
NotInheritable Public Class EndnoteOptions
[C#]
public sealed class EndnoteOptions

Remarks

Example

Shows how to define endnote position in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

EndnoteOptions Members | Aspose.Words Namespace | EndnoteOptions | EndnoteOptions


EndnoteOptions Members

EndnoteOptions overview

Public Instance Properties

NumberStyle | Specifies the number format for automatically numbered endnotes.
Position | Specifies the endnotes position.
RestartRule | Determines when automatic numbering restarts.
StartNumber | Specifies the starting number or character for the first automatically numbered endnotes.

See Also

EndnoteOptions Class | Aspose.Words Namespace | EndnoteOptions | EndnoteOptions


EndnoteOptions Properties

The properties of the EndnoteOptions class are listed below. For a complete list of EndnoteOptions class members, see the EndnoteOptions Members topic.

Public Instance Properties

NumberStyle | Specifies the number format for automatically numbered endnotes.
Position | Specifies the endnotes position.
RestartRule | Determines when automatic numbering restarts.
StartNumber | Specifies the starting number or character for the first automatically numbered endnotes.

See Also

EndnoteOptions Class | Aspose.Words Namespace | EndnoteOptions | EndnoteOptions


NumberStyle Property

Aspose.Words

EndnoteOptions.NumberStyle Property

Specifies the number format for automatically numbered endnotes.

[Visual Basic]
NotOverridable Public Property NumberStyle As NumberStyle
[C#]
public NumberStyle NumberStyle {get; set;}

Remarks

Not all number styles are applicable for this property. For the list of applicable number styles see the Insert Footnote or Endnote dialog box in Microsoft Word. If you select a number style that is not applicable, Microsoft Word will revert to a default value.

Example

Shows how to define numbering format for endnotes in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.EndnoteOptions.NumberStyle = NumberStyle.Arabic1;

See Also

EndnoteOptions Class | Aspose.Words Namespace


Position Property

Aspose.Words

EndnoteOptions.Position Property

Specifies the endnotes position.

[Visual Basic]
Public Property Position As EndnotePosition
[C#]
public EndnotePosition Position {get; set;}

Example

Shows how to define endnote position in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;

See Also

EndnoteOptions Class | Aspose.Words Namespace


RestartRule Property

Aspose.Words

EndnoteOptions.RestartRule Property

Determines when automatic numbering restarts.

[Visual Basic]
NotOverridable Public Property RestartRule As FootnoteNumberingRule
[C#]
public FootnoteNumberingRule RestartRule {get; set;}

Remarks

Not all values are applicable to endnotes. To ascertain which values are applicable see FootnoteNumberingRule.

Example

Shows how to define when automatic numbering for endnotes restarts in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.EndnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;

See Also

EndnoteOptions Class | Aspose.Words Namespace


StartNumber Property

Aspose.Words

EndnoteOptions.StartNumber Property

Specifies the starting number or character for the first automatically numbered endnotes.

[Visual Basic]
NotOverridable Public Property StartNumber As Integer
[C#]
public int StartNumber {get; set;}

Remarks

This property has effect only when RestartRule is set to Continuous.

Example

Shows how to define the starting number or character for the first automatically numbered endnotes.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.EndnoteOptions.StartNumber = 1;

See Also

EndnoteOptions Class | Aspose.Words Namespace


EndnotePosition Enumeration

Defines the endnote position.

[Visual Basic]
Public Enum EndnotePosition
[C#]
public enum EndnotePosition

Remarks

Example

Shows how to define endnote position in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;

Members

Member Name | Description | Value
EndOfSection | Endnotes are output at the end of the section. | 0
EndOfDocument | Endnotes are output at the end of the document. | 3

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | EndnoteOptions


FileCorruptedException Class

Thrown during document load, when the document appears to be corrupted and impossible to load.

System.Object
System.Exception
Aspose.Words.FileCorruptedException

[Visual Basic]
Public Class FileCorruptedException
Inherits Exception
[C#]
public class FileCorruptedException : Exception

Example

Shows how to catch a FileCorruptedException

[C#]

try
{
    Document doc = new Document(MyDir + "Corrupted.docx");
}
catch (FileCorruptedException e)
{
    Console.WriteLine(e.Message);
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


FileFormatInfo Class

Contains data returned by FileFormatUtil document format detection methods.

For a list of all members of this type, see FileFormatInfo Members.

System.Object
Aspose.Words.FileFormatInfo

[Visual Basic]
Public Class FileFormatInfo
[C#]
public class FileFormatInfo

Remarks

You do not create instances of this class directly. Objects of this class are returned by DetectFileFormat methods.

Example

Shows how to use the FileFormatUtil class to detect the document format and other features of the document.

[C#]

FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));
Console.WriteLine("Document is encrypted: " + info.IsEncrypted);
Console.WriteLine("Document has a digital signature: " + info.HasDigitalSignature);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FileFormatInfo Members | Aspose.Words Namespace


FileFormatInfo Members

FileFormatInfo overview

Public Instance Properties

Encoding | Gets the detected encoding if applicable to the current document format. At the moment detects encoding only for HTML documents.
HasDigitalSignature | Returns true if this document contains a digital signature. This property merely informs that a digital signature is present on a document, but it does not specify whether the signature is valid or not.
IsEncrypted | Returns true if the document is encrypted and requires a password to open.
LoadFormat | Gets the detected document format.

See Also

FileFormatInfo Class | Aspose.Words Namespace


FileFormatInfo Properties

The properties of the FileFormatInfo class are listed below. For a complete list of FileFormatInfo class members, see the FileFormatInfo Members topic.

Public Instance Properties

Encoding | Gets the detected encoding if applicable to the current document format. At the moment detects encoding only for HTML documents.
HasDigitalSignature | Returns true if this document contains a digital signature. This property merely informs that a digital signature is present on a document, but it does not specify whether the signature is valid or not.
IsEncrypted | Returns true if the document is encrypted and requires a password to open.
LoadFormat | Gets the detected document format.

See Also

FileFormatInfo Class | Aspose.Words Namespace


Encoding Property

Aspose.Words

FileFormatInfo.Encoding Property

Gets the detected encoding if applicable to the current document format. At the moment detects encoding only for HTML documents.

[Visual Basic]
Public ReadOnly Property Encoding As Encoding
[C#]
public Encoding Encoding {get;}

Example

Shows how to detect encoding in an html file.

[C#]

// 'DetectFileFormat' not working on a non-html files
FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Assert.AreEqual(LoadFormat.Doc, info.LoadFormat);
Assert.IsNull(info.Encoding);

// This time the property will not be null
info = FileFormatUtil.DetectFileFormat(MyDir + "Document.LoadFormat.html");
Assert.AreEqual(LoadFormat.Html, info.LoadFormat);
Assert.IsNotNull(info.Encoding);

// It now has some more useful information
Assert.AreEqual("iso-8859-1", info.Encoding.BodyName);

See Also

FileFormatInfo Class | Aspose.Words Namespace


HasDigitalSignature Property

Aspose.Words

FileFormatInfo.HasDigitalSignature Property

Returns true if this document contains a digital signature. This property merely informs that a digital signature is present on a document, but it does not specify whether the signature is valid or not.

[Visual Basic]
Public ReadOnly Property HasDigitalSignature As Boolean
[C#]
public bool HasDigitalSignature {get;}

Remarks

This property exists to help you sort documents that are digitally signed from those that are not. If you use Aspose.Words to modify and save a document that is digitally signed, then the digital signature will be lost. This is by design because a digital signature exists to guard the authenticity of a document. Using this property you can detect digitally signed documents before processing them in the same way as normal documents and take some action to avoid losing the digital signature, for example notify the user.

Example

Shows how to use the FileFormatUtil class to detect the document format and other features of the document.

[C#]

FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));
Console.WriteLine("Document is encrypted: " + info.IsEncrypted);
Console.WriteLine("Document has a digital signature: " + info.HasDigitalSignature);
Shows how to check a document for digital signatures before loading it into a Document object.
[C#]

// The path to the document which is to be processed.
String filePath = MyDir + "Document.Signed.docx";

FileFormatInfo info = FileFormatUtil.DetectFileFormat(filePath);
if (info.HasDigitalSignature)
{
    Console.WriteLine(
        "Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.",
        Path.GetFileName(filePath));
}

See Also

FileFormatInfo Class | Aspose.Words Namespace


IsEncrypted Property

Aspose.Words

FileFormatInfo.IsEncrypted Property

Returns true if the document is encrypted and requires a password to open.

[Visual Basic]
Public ReadOnly Property IsEncrypted As Boolean
[C#]
public bool IsEncrypted {get;}

Remarks

This property exists to help you sort documents that are encrypted from those that are not. If you attempt to load an encrypted document using Aspose.Words without supplying a password an exception will be thrown. You can use this property to detect whether a document requires a password and take some action before loading a document, for example, prompt the user for a password.

Example

Shows how to use the FileFormatUtil class to detect the document format and other features of the document.

[C#]

FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));
Console.WriteLine("Document is encrypted: " + info.IsEncrypted);
Console.WriteLine("Document has a digital signature: " + info.HasDigitalSignature);

See Also

FileFormatInfo Class | Aspose.Words Namespace | LoadFormat


LoadFormat Property

Aspose.Words

FileFormatInfo.LoadFormat Property

Gets the detected document format.

[Visual Basic]
Public ReadOnly Property LoadFormat As LoadFormat
[C#]
public LoadFormat LoadFormat {get;}

Remarks

When an OOXML document is encrypted, it is not possible to ascertained whether it is an Excel, Word or PowerPoint document without decrypting it first so for an encrypted OOXML document this property will always return Docx.

Example

Shows how to use the FileFormatUtil class to detect the document format and other features of the document.

[C#]

FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));
Console.WriteLine("Document is encrypted: " + info.IsEncrypted);
Console.WriteLine("Document has a digital signature: " + info.HasDigitalSignature);
Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.
[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

FileFormatInfo Class | Aspose.Words Namespace | IsEncrypted


FileFormatUtil Class

Provides utility methods for working with file formats, such as detecting file format or converting file extensions to/from file format enums.

For a list of all members of this type, see FileFormatUtil Members.

System.Object
Aspose.Words.FileFormatUtil

[Visual Basic]
MustInherit NotInheritable Public Class FileFormatUtil
[C#]
public abstract sealed class FileFormatUtil

Example

Shows how to detect encoding in an html file.

[C#]

// 'DetectFileFormat' not working on a non-html files
FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Assert.AreEqual(LoadFormat.Doc, info.LoadFormat);
Assert.IsNull(info.Encoding);

// This time the property will not be null
info = FileFormatUtil.DetectFileFormat(MyDir + "Document.LoadFormat.html");
Assert.AreEqual(LoadFormat.Html, info.LoadFormat);
Assert.IsNotNull(info.Encoding);

// It now has some more useful information
Assert.AreEqual("iso-8859-1", info.Encoding.BodyName);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FileFormatUtil Members | Aspose.Words Namespace


FileFormatUtil Members

FileFormatUtil overview

Public Static (Shared) Methods

ContentTypeToLoadFormat | Converts IANA content type into a load format enumerated value.
ContentTypeToSaveFormat | Converts IANA content type into a save format enumerated value.
DetectFileFormat | Overloaded. Detects and returns the information about a format of a document.
ExtensionToSaveFormat | Converts a file name extension into a SaveFormat value.
ImageTypeToExtension | Converts an Aspose.Words image type enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.
LoadFormatToExtension | Converts a load format enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.
LoadFormatToSaveFormat | Converts a LoadFormat value to a SaveFormat value if possible.
SaveFormatToExtension | Converts a save format enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.
SaveFormatToLoadFormat | Converts a SaveFormat value to a LoadFormat value if possible.

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil Methods

The methods of the FileFormatUtil class are listed below. For a complete list of FileFormatUtil class members, see the FileFormatUtil Members topic.

Public Static (Shared) Methods

ContentTypeToLoadFormat | Converts IANA content type into a load format enumerated value.
ContentTypeToSaveFormat | Converts IANA content type into a save format enumerated value.
DetectFileFormat | Overloaded. Detects and returns the information about a format of a document.
ExtensionToSaveFormat | Converts a file name extension into a SaveFormat value.
ImageTypeToExtension | Converts an Aspose.Words image type enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.
LoadFormatToExtension | Converts a load format enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.
LoadFormatToSaveFormat | Converts a LoadFormat value to a SaveFormat value if possible.
SaveFormatToExtension | Converts a save format enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.
SaveFormatToLoadFormat | Converts a SaveFormat value to a LoadFormat value if possible.

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.ContentTypeToLoadFormat Method

Converts IANA content type into a load format enumerated value.

[Visual Basic]
Public Shared Function ContentTypeToLoadFormat( _
ByVal contentType As String _
) As LoadFormat
[C#]
public static LoadFormat ContentTypeToLoadFormat(
string contentType
);

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to find the corresponding Aspose load/save format from an IANA content type string.

[C#]

// Trying to search for a SaveFormat with a simple string will not work
try
{
    Assert.AreEqual(SaveFormat.Jpeg, FileFormatUtil.ContentTypeToSaveFormat("jpeg"));
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

// The convertion methods only accept official IANA type names, which are all listed here:
//      https://www.iana.org/assignments/media-types/media-types.xhtml
// Note that if a corresponding SaveFormat or LoadFormat for a type from that list does not exist in the Aspose enums,
// converting will raise an exception just like in the code above

// File types that can be saved to but not opened as documents will not have corresponding load formats
// Attempting to convert them to load formats will raise an exception
Assert.AreEqual(SaveFormat.Jpeg, FileFormatUtil.ContentTypeToSaveFormat("image/jpeg"));
Assert.AreEqual(SaveFormat.Png, FileFormatUtil.ContentTypeToSaveFormat("image/png"));
Assert.AreEqual(SaveFormat.Tiff, FileFormatUtil.ContentTypeToSaveFormat("image/tiff"));
Assert.AreEqual(SaveFormat.Gif, FileFormatUtil.ContentTypeToSaveFormat("image/gif"));
Assert.AreEqual(SaveFormat.Emf, FileFormatUtil.ContentTypeToSaveFormat("image/x-emf"));
Assert.AreEqual(SaveFormat.Xps, FileFormatUtil.ContentTypeToSaveFormat("application/vnd.ms-xpsdocument"));
Assert.AreEqual(SaveFormat.Pdf, FileFormatUtil.ContentTypeToSaveFormat("application/pdf"));
Assert.AreEqual(SaveFormat.Svg, FileFormatUtil.ContentTypeToSaveFormat("image/svg+xml"));
Assert.AreEqual(SaveFormat.Epub, FileFormatUtil.ContentTypeToSaveFormat("application/epub+zip"));

// File types that can both be loaded and saved have corresponding load and save formats
Assert.AreEqual(LoadFormat.Doc, FileFormatUtil.ContentTypeToLoadFormat("application/msword"));
Assert.AreEqual(SaveFormat.Doc, FileFormatUtil.ContentTypeToSaveFormat("application/msword"));

Assert.AreEqual(LoadFormat.Docx,
    FileFormatUtil.ContentTypeToLoadFormat(
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
Assert.AreEqual(SaveFormat.Docx,
    FileFormatUtil.ContentTypeToSaveFormat(
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));

Assert.AreEqual(LoadFormat.Text, FileFormatUtil.ContentTypeToLoadFormat("text/plain"));
Assert.AreEqual(SaveFormat.Text, FileFormatUtil.ContentTypeToSaveFormat("text/plain"));

Assert.AreEqual(LoadFormat.Rtf, FileFormatUtil.ContentTypeToLoadFormat("application/rtf"));
Assert.AreEqual(SaveFormat.Rtf, FileFormatUtil.ContentTypeToSaveFormat("application/rtf"));

Assert.AreEqual(LoadFormat.Html, FileFormatUtil.ContentTypeToLoadFormat("text/html"));
Assert.AreEqual(SaveFormat.Html, FileFormatUtil.ContentTypeToSaveFormat("text/html"));

Assert.AreEqual(LoadFormat.Mhtml, FileFormatUtil.ContentTypeToLoadFormat("multipart/related"));
Assert.AreEqual(SaveFormat.Mhtml, FileFormatUtil.ContentTypeToSaveFormat("multipart/related"));

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.ContentTypeToSaveFormat Method

Converts IANA content type into a save format enumerated value.

[Visual Basic]
Public Shared Function ContentTypeToSaveFormat( _
ByVal contentType As String _
) As SaveFormat
[C#]
public static SaveFormat ContentTypeToSaveFormat(
string contentType
);

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to find the corresponding Aspose load/save format from an IANA content type string.

[C#]

// Trying to search for a SaveFormat with a simple string will not work
try
{
    Assert.AreEqual(SaveFormat.Jpeg, FileFormatUtil.ContentTypeToSaveFormat("jpeg"));
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

// The convertion methods only accept official IANA type names, which are all listed here:
//      https://www.iana.org/assignments/media-types/media-types.xhtml
// Note that if a corresponding SaveFormat or LoadFormat for a type from that list does not exist in the Aspose enums,
// converting will raise an exception just like in the code above

// File types that can be saved to but not opened as documents will not have corresponding load formats
// Attempting to convert them to load formats will raise an exception
Assert.AreEqual(SaveFormat.Jpeg, FileFormatUtil.ContentTypeToSaveFormat("image/jpeg"));
Assert.AreEqual(SaveFormat.Png, FileFormatUtil.ContentTypeToSaveFormat("image/png"));
Assert.AreEqual(SaveFormat.Tiff, FileFormatUtil.ContentTypeToSaveFormat("image/tiff"));
Assert.AreEqual(SaveFormat.Gif, FileFormatUtil.ContentTypeToSaveFormat("image/gif"));
Assert.AreEqual(SaveFormat.Emf, FileFormatUtil.ContentTypeToSaveFormat("image/x-emf"));
Assert.AreEqual(SaveFormat.Xps, FileFormatUtil.ContentTypeToSaveFormat("application/vnd.ms-xpsdocument"));
Assert.AreEqual(SaveFormat.Pdf, FileFormatUtil.ContentTypeToSaveFormat("application/pdf"));
Assert.AreEqual(SaveFormat.Svg, FileFormatUtil.ContentTypeToSaveFormat("image/svg+xml"));
Assert.AreEqual(SaveFormat.Epub, FileFormatUtil.ContentTypeToSaveFormat("application/epub+zip"));

// File types that can both be loaded and saved have corresponding load and save formats
Assert.AreEqual(LoadFormat.Doc, FileFormatUtil.ContentTypeToLoadFormat("application/msword"));
Assert.AreEqual(SaveFormat.Doc, FileFormatUtil.ContentTypeToSaveFormat("application/msword"));

Assert.AreEqual(LoadFormat.Docx,
    FileFormatUtil.ContentTypeToLoadFormat(
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
Assert.AreEqual(SaveFormat.Docx,
    FileFormatUtil.ContentTypeToSaveFormat(
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));

Assert.AreEqual(LoadFormat.Text, FileFormatUtil.ContentTypeToLoadFormat("text/plain"));
Assert.AreEqual(SaveFormat.Text, FileFormatUtil.ContentTypeToSaveFormat("text/plain"));

Assert.AreEqual(LoadFormat.Rtf, FileFormatUtil.ContentTypeToLoadFormat("application/rtf"));
Assert.AreEqual(SaveFormat.Rtf, FileFormatUtil.ContentTypeToSaveFormat("application/rtf"));

Assert.AreEqual(LoadFormat.Html, FileFormatUtil.ContentTypeToLoadFormat("text/html"));
Assert.AreEqual(SaveFormat.Html, FileFormatUtil.ContentTypeToSaveFormat("text/html"));

Assert.AreEqual(LoadFormat.Mhtml, FileFormatUtil.ContentTypeToLoadFormat("multipart/related"));
Assert.AreEqual(SaveFormat.Mhtml, FileFormatUtil.ContentTypeToSaveFormat("multipart/related"));

See Also

FileFormatUtil Class | Aspose.Words Namespace


DetectFileFormat Method

Aspose.Words

FileFormatUtil.DetectFileFormat Method

Detects and returns the information about a format of a document.

Overload List

Detects and returns the information about a format of a document stored in a stream.

public static FileFormatInfo DetectFileFormat(Stream);

Detects and returns the information about a format of a document stored in a disk file.

public static FileFormatInfo DetectFileFormat(string);

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.DetectFileFormat Method (Stream)

Detects and returns the information about a format of a document stored in a stream.

[Visual Basic]
Overloads Public Shared Function DetectFileFormat( _
ByVal stream As Stream _
) As FileFormatInfo
[C#]
public static FileFormatInfo DetectFileFormat(
Stream stream
);

Parameters

stream
The stream.

Return Value

A FileFormatInfo object that contains the detected information.

Remarks

The stream must be positioned at the beginning of the document.

When this method returns, the position in the stream is restored to the original position.

Even if this method detects the document format, it does not guarantee that the specified document is valid. This method only detects the document format by reading data that is sufficient for detection. To fully verify that a document is valid you need to load the document into a Document object.

This method throws FileCorruptedException when the format is recognized, but the detection cannot complete because of corruption.

Example

Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

FileFormatUtil Class | Aspose.Words Namespace | FileFormatUtil.DetectFileFormat Overload List


FileFormatUtil.DetectFileFormat Method (String)

Detects and returns the information about a format of a document stored in a disk file.

[Visual Basic]
Overloads Public Shared Function DetectFileFormat( _
ByVal fileName As String _
) As FileFormatInfo
[C#]
public static FileFormatInfo DetectFileFormat(
string fileName
);

Parameters

fileName
The file name.

Return Value

A FileFormatInfo object that contains the detected information.

Remarks

Even if this method detects the document format, it does not guarantee that the specified document is valid. This method only detects the document format by reading data that is sufficient for detection. To fully verify that a document is valid you need to load the document into a Document object.

This method throws FileCorruptedException when the format is recognized, but the detection cannot complete because of corruption.

Example

Shows how to use the FileFormatUtil class to detect the document format and other features of the document.

[C#]

FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));
Console.WriteLine("Document is encrypted: " + info.IsEncrypted);
Console.WriteLine("Document has a digital signature: " + info.HasDigitalSignature);
Shows how to check a document for digital signatures before loading it into a Document object.
[C#]

// The path to the document which is to be processed.
String filePath = MyDir + "Document.Signed.docx";

FileFormatInfo info = FileFormatUtil.DetectFileFormat(filePath);
if (info.HasDigitalSignature)
{
    Console.WriteLine(
        "Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.",
        Path.GetFileName(filePath));
}

See Also

FileFormatUtil Class | Aspose.Words Namespace | FileFormatUtil.DetectFileFormat Overload List


FileFormatUtil.ExtensionToSaveFormat Method

Converts a file name extension into a SaveFormat value.

[Visual Basic]
Public Shared Function ExtensionToSaveFormat( _
ByVal extension As String _
) As SaveFormat
[C#]
public static SaveFormat ExtensionToSaveFormat(
string extension
);

Parameters

extension
The file extension. Can be with or without a leading dot. Case-insensitive.

Remarks

If the extension cannot be recognized, returns Unknown.

Exceptions

Exception Type | Condition
ArgumentNullException | Throws if the parameter is null.

Example

Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.ImageTypeToExtension Method

Converts an Aspose.Words image type enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.

[Visual Basic]
Public Shared Function ImageTypeToExtension( _
ByVal imageType As ImageType _
) As String
[C#]
public static string ImageTypeToExtension(
ImageType imageType
);

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to extract images from a document and save them as files.

[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.LoadFormatToExtension Method

Converts a load format enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.

[Visual Basic]
Public Shared Function LoadFormatToExtension( _
ByVal loadFormat As LoadFormat _
) As String
[C#]
public static string LoadFormatToExtension(
LoadFormat loadFormat
);

Remarks

The WordML value is converted to ".wml".

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.LoadFormatToSaveFormat Method

Converts a LoadFormat value to a SaveFormat value if possible.

[Visual Basic]
Public Shared Function LoadFormatToSaveFormat( _
ByVal loadFormat As LoadFormat _
) As SaveFormat
[C#]
public static SaveFormat LoadFormatToSaveFormat(
LoadFormat loadFormat
);

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.SaveFormatToExtension Method

Converts a save format enumerated value into a file extension. The returned extension is a lower-case string with a leading dot.

[Visual Basic]
Public Shared Function SaveFormatToExtension( _
ByVal saveFormat As SaveFormat _
) As String
[C#]
public static string SaveFormatToExtension(
SaveFormat saveFormat
);

Remarks

The WordML value is converted to ".wml".

The FlatOpc value is converted to ".fopc".

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

[C#]

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format.
// These are both times where you might need extract the file format as it's not visible
FileStream
    docStream = File.OpenRead(
        MyDir + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document.
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
//
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension.
String fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension.
doc.Save(
    ArtifactsDir + "Document.WithFileExtension" + FileFormatUtil.SaveFormatToExtension(saveFormat));

See Also

FileFormatUtil Class | Aspose.Words Namespace


FileFormatUtil.SaveFormatToLoadFormat Method

Converts a SaveFormat value to a LoadFormat value if possible.

[Visual Basic]
Public Shared Function SaveFormatToLoadFormat( _
ByVal saveFormat As SaveFormat _
) As LoadFormat
[C#]
public static LoadFormat SaveFormatToLoadFormat(
SaveFormat saveFormat
);

Exceptions

Exception Type | Condition
ArgumentException | Throws when cannot convert.

Example

Shows how to use the FileFormatUtil class and to convert a SaveFormat enumeration into the corresponding LoadFormat enumeration.

[C#]

// Define the SaveFormat enumeration to convert.
SaveFormat saveFormat = SaveFormat.Html;
// Convert the SaveFormat enumeration to LoadFormat enumeration.
LoadFormat loadFormat = FileFormatUtil.SaveFormatToLoadFormat(saveFormat);
Console.WriteLine("The converted LoadFormat is: " + FileFormatUtil.LoadFormatToExtension(loadFormat));

See Also

FileFormatUtil Class | Aspose.Words Namespace


FindReplaceDirection Enumeration

Specifies direction for replace operations.

[Visual Basic]
Public Enum FindReplaceDirection
[C#]
public enum FindReplaceDirection

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}

Members

Member Name | Description | Value
Forward | Matched items are replaced from first to last. | 0
Backward | Matched items are replaced from last back to first. | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Font Class

Contains font attributes (font name, font size, color, and so on) for an object.

For a list of all members of this type, see Font Members.

System.Object
Aspose.Words.Font

[Visual Basic]
Public Class Font
[C#]
public class Font

Remarks

You do not create instances of the Font class directly. You just use Font to access the font properties of the various objects such as Run, Paragraph, Style, DocumentBuilder.

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
Shows how to add a formatted run of text to a document using the object model.
[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);
Shows how to create and use a paragraph style with list formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Font Members | Aspose.Words Namespace


Font Members

Font overview

Public Instance Properties

AllCaps | True if the font is formatted as all capital letters.
AutoColor | Returns the present calculated color of the text (black or white) to be used for 'auto color'. If the color is not 'auto' then returns Color.
Bidi | Specifies whether the contents of this run shall have right-to-left characteristics.
Bold | True if the font is formatted as bold.
BoldBi | True if the right-to-left text is formatted as bold.
Border | Returns a Border object that specifies border for the font.
Color | Gets or sets the color of the font.
ComplexScript | Specifies whether the contents of this run shall be treated as complex script text regardless of their Unicode character values when determining the formatting for this run.
DoubleStrikeThrough | True if the font is formatted as double strikethrough text.
Emboss | True if the font is formatted as embossed.
Engrave | True if the font is formatted as engraved.
Hidden | True if the font is formatted as hidden text.
HighlightColor | Gets or sets the highlight (marker) color.
Italic | True if the font is formatted as italic.
ItalicBi | True if the right-to-left text is formatted as italic.
Kerning | Gets or sets the font size at which kerning starts.
LineSpacing | Returns line spacing of this font (in points).
LocaleId | Gets or sets the locale identifier (language) of the formatted characters.
LocaleIdBi | Gets or sets the locale identifier (language) of the formatted right-to-left characters.
LocaleIdFarEast | Gets or sets the locale identifier (language) of the formatted Asian characters.
Name | Gets or sets the name of the font.
NameAscii | Returns or sets the font used for Latin text (characters with character codes from 0 (zero) through 127).
NameBi | Returns or sets the name of the font in a right-to-left language document.
NameFarEast | Returns or sets an East Asian font name.
NameOther | Returns or sets the font used for characters with character codes from 128 through 255.
NoProofing | True when the formatted characters are not to be spell checked.
Outline | True if the font is formatted as outline.
Position | Gets or sets the position of text (in points) relative to the base line. A positive number raises the text, and a negative number lowers it.
Scaling | Gets or sets character width scaling in percent.
Shading | Returns a Shading object that refers to the shading formatting for the font.
Shadow | True if the font is formatted as shadowed.
Size | Gets or sets the font size in points.
SizeBi | Gets or sets the font size in points used in a right-to-left document.
SmallCaps | True if the font is formatted as small capital letters.
Spacing | Returns or sets the spacing (in points) between characters .
StrikeThrough | True if the font is formatted as strikethrough text.
Style | Gets or sets the character style applied to this formatting.
StyleIdentifier | Gets or sets the locale independent style identifier of the character style applied to this formatting.
StyleName | Gets or sets the name of the character style applied to this formatting.
Subscript | True if the font is formatted as subscript.
Superscript | True if the font is formatted as superscript.
TextEffect | Gets or sets the font animation effect.
Underline | Gets or sets the type of underline applied to the font.
UnderlineColor | Gets or sets the color of the underline applied to the font.

Public Instance Methods

ClearFormatting | Resets to default font formatting.
HasDmlEffect | Checks if particular Dml text effect is applied.

See Also

Font Class | Aspose.Words Namespace


Font Properties

The properties of the Font class are listed below. For a complete list of Font class members, see the Font Members topic.

Public Instance Properties

AllCaps | True if the font is formatted as all capital letters.
AutoColor | Returns the present calculated color of the text (black or white) to be used for 'auto color'. If the color is not 'auto' then returns Color.
Bidi | Specifies whether the contents of this run shall have right-to-left characteristics.
Bold | True if the font is formatted as bold.
BoldBi | True if the right-to-left text is formatted as bold.
Border | Returns a Border object that specifies border for the font.
Color | Gets or sets the color of the font.
ComplexScript | Specifies whether the contents of this run shall be treated as complex script text regardless of their Unicode character values when determining the formatting for this run.
DoubleStrikeThrough | True if the font is formatted as double strikethrough text.
Emboss | True if the font is formatted as embossed.
Engrave | True if the font is formatted as engraved.
Hidden | True if the font is formatted as hidden text.
HighlightColor | Gets or sets the highlight (marker) color.
Italic | True if the font is formatted as italic.
ItalicBi | True if the right-to-left text is formatted as italic.
Kerning | Gets or sets the font size at which kerning starts.
LineSpacing | Returns line spacing of this font (in points).
LocaleId | Gets or sets the locale identifier (language) of the formatted characters.
LocaleIdBi | Gets or sets the locale identifier (language) of the formatted right-to-left characters.
LocaleIdFarEast | Gets or sets the locale identifier (language) of the formatted Asian characters.
Name | Gets or sets the name of the font.
NameAscii | Returns or sets the font used for Latin text (characters with character codes from 0 (zero) through 127).
NameBi | Returns or sets the name of the font in a right-to-left language document.
NameFarEast | Returns or sets an East Asian font name.
NameOther | Returns or sets the font used for characters with character codes from 128 through 255.
NoProofing | True when the formatted characters are not to be spell checked.
Outline | True if the font is formatted as outline.
Position | Gets or sets the position of text (in points) relative to the base line. A positive number raises the text, and a negative number lowers it.
Scaling | Gets or sets character width scaling in percent.
Shading | Returns a Shading object that refers to the shading formatting for the font.
Shadow | True if the font is formatted as shadowed.
Size | Gets or sets the font size in points.
SizeBi | Gets or sets the font size in points used in a right-to-left document.
SmallCaps | True if the font is formatted as small capital letters.
Spacing | Returns or sets the spacing (in points) between characters .
StrikeThrough | True if the font is formatted as strikethrough text.
Style | Gets or sets the character style applied to this formatting.
StyleIdentifier | Gets or sets the locale independent style identifier of the character style applied to this formatting.
StyleName | Gets or sets the name of the character style applied to this formatting.
Subscript | True if the font is formatted as subscript.
Superscript | True if the font is formatted as superscript.
TextEffect | Gets or sets the font animation effect.
Underline | Gets or sets the type of underline applied to the font.
UnderlineColor | Gets or sets the color of the underline applied to the font.

See Also

Font Class | Aspose.Words Namespace


AllCaps Property

Aspose.Words

Font.AllCaps Property

True if the font is formatted as all capital letters.

[Visual Basic]
Public Property AllCaps As Boolean
[C#]
public bool AllCaps {get; set;}

Example

Shows how to use all capitals and small capitals character formatting properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

Run run = new Run(doc, "All capitals");
run.Font.AllCaps = true;
para.AppendChild(run);

run = new Run(doc, "SMALL CAPITALS");
run.Font.SmallCaps = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


AutoColor Property

Aspose.Words

Font.AutoColor Property

Returns the present calculated color of the text (black or white) to be used for 'auto color'. If the color is not 'auto' then returns Color.

[Visual Basic]
Public ReadOnly Property AutoColor As Color
[C#]
public Color AutoColor {get;}

Remarks

When text has 'automatic color', the actual color of text is calculated automatically so that it is readable against the background color. As you change the background color, the text color will automatically switch to black or white in MS Word to maximize legibility.

Example

Shows how calculated color of the text (black or white) to be used for 'auto color'

[C#]

Run run = new Run(new Document());

// Remove direct color, so it can be calculated automatically with Font.AutoColor.
run.Font.Color = Color.Empty;

// When we set black color for background, autocolor for font must be white
run.Font.Shading.BackgroundPatternColor = Color.Black;
Assert.AreEqual(Color.White, run.Font.AutoColor);

// When we set white color for background, autocolor for font must be black
run.Font.Shading.BackgroundPatternColor = Color.White;
Assert.AreEqual(Color.Black, run.Font.AutoColor);

See Also

Font Class | Aspose.Words Namespace


Bidi Property

Aspose.Words

Font.Bidi Property

Specifies whether the contents of this run shall have right-to-left characteristics.

[Visual Basic]
Public Property Bidi As Boolean
[C#]
public bool Bidi {get; set;}

Remarks

This property, when on, shall not be used with strongly left-to-right text. Any behavior under that condition is unspecified. This property, when off, shall not be used with strong right-to-left text. Any behavior under that condition is unspecified.

When the contents of this run are displayed, all characters shall be treated as complex script characters for formatting purposes. This means that BoldBi, ItalicBi, SizeBi and a corresponding font name will be used when rendering this run.

Also, when the contents of this run are displayed, this property acts as a right-to-left override for characters which are classified as "weak types" and "neutral types".

Example

Shows how to insert and format right-to-left text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Signal to Microsoft Word that this run of text contains right-to-left text.
builder.Font.Bidi = true;

// Specify the font and font size to be used for the right-to-left text.
builder.Font.NameBi = "Andalus";
builder.Font.SizeBi = 48;

// Specify that the right-to-left text in this run is bold and italic.
builder.Font.ItalicBi = true;
builder.Font.BoldBi = true;

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(ArtifactsDir + "Font.Bidi.doc");

See Also

Font Class | Aspose.Words Namespace


Bold Property

Aspose.Words

Font.Bold Property

True if the font is formatted as bold.

[Visual Basic]
Public Property Bold As Boolean
[C#]
public bool Bold {get; set;}

Example

Inserts formatted text using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Specify font formatting before adding text.
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

builder.Write("Sample text.");

See Also

Font Class | Aspose.Words Namespace


BoldBi Property

Aspose.Words

Font.BoldBi Property

True if the right-to-left text is formatted as bold.

[Visual Basic]
Public Property BoldBi As Boolean
[C#]
public bool BoldBi {get; set;}

Example

Shows how to insert and format right-to-left text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Signal to Microsoft Word that this run of text contains right-to-left text.
builder.Font.Bidi = true;

// Specify the font and font size to be used for the right-to-left text.
builder.Font.NameBi = "Andalus";
builder.Font.SizeBi = 48;

// Specify that the right-to-left text in this run is bold and italic.
builder.Font.ItalicBi = true;
builder.Font.BoldBi = true;

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(ArtifactsDir + "Font.Bidi.doc");

See Also

Font Class | Aspose.Words Namespace


Border Property

Aspose.Words

Font.Border Property

Returns a Border object that specifies border for the font.

[Visual Basic]
Public ReadOnly Property Border As Border
[C#]
public Border Border {get;}

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");

See Also

Font Class | Aspose.Words Namespace


Color Property

Aspose.Words

Font.Color Property

Gets or sets the color of the font.

[Visual Basic]
Public Property Color As Color
[C#]
public Color Color {get; set;}

Example

Inserts formatted text using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Specify font formatting before adding text.
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

builder.Write("Sample text.");
Inserts a hyperlink into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Please make sure to visit ");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
// Insert the link.
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false);

// Revert to default formatting.
builder.Font.ClearFormatting();

builder.Write(" for more information.");

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlink.doc");

See Also

Font Class | Aspose.Words Namespace


ComplexScript Property

Aspose.Words

Font.ComplexScript Property

Specifies whether the contents of this run shall be treated as complex script text regardless of their Unicode character values when determining the formatting for this run.

[Visual Basic]
Public Property ComplexScript As Boolean
[C#]
public bool ComplexScript {get; set;}

Example

Shows how to make a run that's always treated as complex script.

[C#]

Run run = new Run(doc, "Complex script");
run.Font.ComplexScript = true;

See Also

Font Class | Aspose.Words Namespace


DoubleStrikeThrough Property

Aspose.Words

Font.DoubleStrikeThrough Property

True if the font is formatted as double strikethrough text.

[Visual Basic]
Public Property DoubleStrikeThrough As Boolean
[C#]
public bool DoubleStrikeThrough {get; set;}

Example

Shows how to use strike-through character formatting properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

Run run = new Run(doc, "Double strike through text");
run.Font.DoubleStrikeThrough = true;
para.AppendChild(run);

run = new Run(doc, "Single strike through text");
run.Font.StrikeThrough = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Emboss Property

Aspose.Words

Font.Emboss Property

True if the font is formatted as embossed.

[Visual Basic]
Public Property Emboss As Boolean
[C#]
public bool Emboss {get; set;}

Example

Shows how to create a run of formatted text.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Emboss = true;
run.Font.Italic = true;

See Also

Font Class | Aspose.Words Namespace


Engrave Property

Aspose.Words

Font.Engrave Property

True if the font is formatted as engraved.

[Visual Basic]
Public Property Engrave As Boolean
[C#]
public bool Engrave {get; set;}

Example

Shows how to create a run of text formatted as engraved.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Engrave = true;

See Also

Font Class | Aspose.Words Namespace


Hidden Property

Aspose.Words

Font.Hidden Property

True if the font is formatted as hidden text.

[Visual Basic]
Public Property Hidden As Boolean
[C#]
public bool Hidden {get; set;}

Example

Shows how to create a hidden run of text.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Hidden = true;
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

Font Class | Aspose.Words Namespace


HighlightColor Property

Aspose.Words

Font.HighlightColor Property

Gets or sets the highlight (marker) color.

[Visual Basic]
Public Property HighlightColor As Color
[C#]
public Color HighlightColor {get; set;}

Example

Shows how to add a formatted run of text to a document using the object model.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Italic Property

Aspose.Words

Font.Italic Property

True if the font is formatted as italic.

[Visual Basic]
Public Property Italic As Boolean
[C#]
public bool Italic {get; set;}

Example

Shows how to create a run of formatted text.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Emboss = true;
run.Font.Italic = true;

See Also

Font Class | Aspose.Words Namespace


ItalicBi Property

Aspose.Words

Font.ItalicBi Property

True if the right-to-left text is formatted as italic.

[Visual Basic]
Public Property ItalicBi As Boolean
[C#]
public bool ItalicBi {get; set;}

Example

Shows how to insert and format right-to-left text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Signal to Microsoft Word that this run of text contains right-to-left text.
builder.Font.Bidi = true;

// Specify the font and font size to be used for the right-to-left text.
builder.Font.NameBi = "Andalus";
builder.Font.SizeBi = 48;

// Specify that the right-to-left text in this run is bold and italic.
builder.Font.ItalicBi = true;
builder.Font.BoldBi = true;

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(ArtifactsDir + "Font.Bidi.doc");

See Also

Font Class | Aspose.Words Namespace


Kerning Property

Aspose.Words

Font.Kerning Property

Gets or sets the font size at which kerning starts.

[Visual Basic]
Public Property Kerning As Double
[C#]
public double Kerning {get; set;}

Example

Shows how to specify the font size at which kerning starts.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Kerning = 24;

See Also

Font Class | Aspose.Words Namespace


LineSpacing Property

Aspose.Words

Font.LineSpacing Property

Returns line spacing of this font (in points).

[Visual Basic]
Public ReadOnly Property LineSpacing As Double
[C#]
public double LineSpacing {get;}

Example

Shows how to get line spacing of current font (in points)

[C#]

DocumentBuilder builder = new DocumentBuilder(new Document());
builder.Font.Name = "Calibri";
builder.Writeln("qText");

// Obtain line spacing.
Aspose.Words.Font font = builder.Document.FirstSection.Body.FirstParagraph.Runs[0].Font;
Console.WriteLine($"lineSpacing = { font.LineSpacing }");

See Also

Font Class | Aspose.Words Namespace


LocaleId Property

Aspose.Words

Font.LocaleId Property

Gets or sets the locale identifier (language) of the formatted characters.

[Visual Basic]
Public Property LocaleId As Integer
[C#]
public int LocaleId {get; set;}

Remarks

For the list of locale identifiers see https://msdn.microsoft.com/en-us/library/cc233965.aspx

Example

Shows how to specify the language of a text run so Microsoft Word can use a proper spell checker.

[C#]

//Create a run of text that contains Russian text.
Run run = new Run(doc, "Привет");

//Specify the locale so Microsoft Word recognizes this text as Russian.
//For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
run.Font.LocaleId = 1049;

See Also

Font Class | Aspose.Words Namespace


LocaleIdBi Property

Aspose.Words

Font.LocaleIdBi Property

Gets or sets the locale identifier (language) of the formatted right-to-left characters.

[Visual Basic]
Public Property LocaleIdBi As Integer
[C#]
public int LocaleIdBi {get; set;}

Remarks

For the list of locale identifiers see https://msdn.microsoft.com/en-us/library/cc233965.aspx

Example

Shows how to insert and format right-to-left text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Signal to Microsoft Word that this run of text contains right-to-left text.
builder.Font.Bidi = true;

// Specify the font and font size to be used for the right-to-left text.
builder.Font.NameBi = "Andalus";
builder.Font.SizeBi = 48;

// Specify that the right-to-left text in this run is bold and italic.
builder.Font.ItalicBi = true;
builder.Font.BoldBi = true;

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(ArtifactsDir + "Font.Bidi.doc");

See Also

Font Class | Aspose.Words Namespace


LocaleIdFarEast Property

Aspose.Words

Font.LocaleIdFarEast Property

Gets or sets the locale identifier (language) of the formatted Asian characters.

[Visual Basic]
Public Property LocaleIdFarEast As Integer
[C#]
public int LocaleIdFarEast {get; set;}

Remarks

For the list of locale identifiers see https://msdn.microsoft.com/en-us/library/cc233965.aspx

Example

Shows how to insert and format text in Chinese or any other Far East language.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Size = 48;

// Specify the font name. Make sure it the font has the glyphs that you want to display.
builder.Font.NameFarEast = "SimSun";

// Specify the locale so Microsoft Word recognizes this text as Chinese.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdFarEast = 2052;

// Insert some Chinese text.
builder.Writeln("你好世界");

builder.Document.Save(ArtifactsDir + "Font.FarEast.doc");

See Also

Font Class | Aspose.Words Namespace


Name Property

Aspose.Words

Font.Name Property

Gets or sets the name of the font.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

When getting, returns NameAscii.

When setting, sets NameAscii, NameBi, NameFarEast and NameOther to the specified value.

Example

Inserts formatted text using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Specify font formatting before adding text.
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

builder.Write("Sample text.");
Shows how to add a formatted run of text to a document using the object model.
[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


NameAscii Property

Aspose.Words

Font.NameAscii Property

Returns or sets the font used for Latin text (characters with character codes from 0 (zero) through 127).

[Visual Basic]
Public Property NameAscii As String
[C#]
public string NameAscii {get; set;}

Remarks

Example

A pretty unusual example of how Microsoft Word can combine two different fonts in one run.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// This tells Microsoft Word to use Arial for characters 0..127 and
// Times New Roman for characters 128..255.
// Looks like a pretty strange case to me, but it is possible.
builder.Font.NameAscii = "Arial";
builder.Font.NameOther = "Times New Roman";

builder.Writeln("Hello, Привет");

builder.Document.Save(ArtifactsDir + "Font.Names.doc");

See Also

Font Class | Aspose.Words Namespace | Name


NameBi Property

Aspose.Words

Font.NameBi Property

Returns or sets the name of the font in a right-to-left language document.

[Visual Basic]
Public Property NameBi As String
[C#]
public string NameBi {get; set;}

Remarks

Example

Shows how to insert and format right-to-left text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Signal to Microsoft Word that this run of text contains right-to-left text.
builder.Font.Bidi = true;

// Specify the font and font size to be used for the right-to-left text.
builder.Font.NameBi = "Andalus";
builder.Font.SizeBi = 48;

// Specify that the right-to-left text in this run is bold and italic.
builder.Font.ItalicBi = true;
builder.Font.BoldBi = true;

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(ArtifactsDir + "Font.Bidi.doc");

See Also

Font Class | Aspose.Words Namespace | Name


NameFarEast Property

Aspose.Words

Font.NameFarEast Property

Returns or sets an East Asian font name.

[Visual Basic]
Public Property NameFarEast As String
[C#]
public string NameFarEast {get; set;}

Remarks

Example

Shows how to insert and format text in Chinese or any other Far East language.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Size = 48;

// Specify the font name. Make sure it the font has the glyphs that you want to display.
builder.Font.NameFarEast = "SimSun";

// Specify the locale so Microsoft Word recognizes this text as Chinese.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdFarEast = 2052;

// Insert some Chinese text.
builder.Writeln("你好世界");

builder.Document.Save(ArtifactsDir + "Font.FarEast.doc");

See Also

Font Class | Aspose.Words Namespace | Name


NameOther Property

Aspose.Words

Font.NameOther Property

Returns or sets the font used for characters with character codes from 128 through 255.

[Visual Basic]
Public Property NameOther As String
[C#]
public string NameOther {get; set;}

Remarks

Example

A pretty unusual example of how Microsoft Word can combine two different fonts in one run.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// This tells Microsoft Word to use Arial for characters 0..127 and
// Times New Roman for characters 128..255.
// Looks like a pretty strange case to me, but it is possible.
builder.Font.NameAscii = "Arial";
builder.Font.NameOther = "Times New Roman";

builder.Writeln("Hello, Привет");

builder.Document.Save(ArtifactsDir + "Font.Names.doc");

See Also

Font Class | Aspose.Words Namespace | Name


NoProofing Property

Aspose.Words

Font.NoProofing Property

True when the formatted characters are not to be spell checked.

[Visual Basic]
Public Property NoProofing As Boolean
[C#]
public bool NoProofing {get; set;}

Example

Shows how to specify that the run of text is not to be spell checked by Microsoft Word.

[C#]

Run run = new Run(doc, "Hello");
run.Font.NoProofing = true;

See Also

Font Class | Aspose.Words Namespace


Outline Property

Aspose.Words

Font.Outline Property

True if the font is formatted as outline.

[Visual Basic]
Public Property Outline As Boolean
[C#]
public bool Outline {get; set;}

Example

Shows how to create a run of text formatted as outline.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Outline = true;

See Also

Font Class | Aspose.Words Namespace


Position Property

Aspose.Words

Font.Position Property

Gets or sets the position of text (in points) relative to the base line. A positive number raises the text, and a negative number lowers it.

[Visual Basic]
Public Property Position As Double
[C#]
public double Position {get; set;}

Example

Shows how to use subscript, superscript, complex script, text effects, and baseline text position properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Add a run of text that is raised 5 points above the baseline.
Run run = new Run(doc, "Raised text");
run.Font.Position = 5;
para.AppendChild(run);

// Add a run of normal text.
run = new Run(doc, "Normal text");
para.AppendChild(run);

// Add a run of text that appears as subscript.
run = new Run(doc, "Subscript");
run.Font.Subscript = true;
para.AppendChild(run);

// Add a run of text that appears as superscript.
run = new Run(doc, "Superscript");
run.Font.Superscript = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Scaling Property

Aspose.Words

Font.Scaling Property

Gets or sets character width scaling in percent.

[Visual Basic]
Public Property Scaling As Integer
[C#]
public int Scaling {get; set;}

Example

Shows how to use character scaling and spacing properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Add a run of text with characters 150% width of normal characters.
Run run = new Run(doc, "Wide characters");
run.Font.Scaling = 150;
para.AppendChild(run);

// Add a run of text with extra 1pt space between characters.
run = new Run(doc, "Expanded by 1pt");
run.Font.Spacing = 1;
para.AppendChild(run);

// Add a run of text with space between characters reduced by 1pt.
run = new Run(doc, "Condensed by 1pt");
run.Font.Spacing = -1;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Shading Property

Aspose.Words

Font.Shading Property

Returns a Shading object that refers to the shading formatting for the font.

[Visual Basic]
Public ReadOnly Property Shading As Shading
[C#]
public Shading Shading {get;}

Example

Shows how to apply shading for a run of text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

Shading shd = builder.Font.Shading;
shd.Texture = TextureIndex.TextureDiagonalCross;
shd.BackgroundPatternColor = Color.Blue;
shd.ForegroundPatternColor = Color.BlueViolet;

builder.Font.Color = Color.White;

builder.Writeln("White text on a blue background with texture.");

See Also

Font Class | Aspose.Words Namespace


Shadow Property

Aspose.Words

Font.Shadow Property

True if the font is formatted as shadowed.

[Visual Basic]
Public Property Shadow As Boolean
[C#]
public bool Shadow {get; set;}

Example

Shows how to create a run of text formatted with a shadow.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Shadow = true;

See Also

Font Class | Aspose.Words Namespace


Size Property

Aspose.Words

Font.Size Property

Gets or sets the font size in points.

[Visual Basic]
Public Property Size As Double
[C#]
public double Size {get; set;}

Example

Inserts formatted text using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Specify font formatting before adding text.
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

builder.Write("Sample text.");
Shows how to add a formatted run of text to a document using the object model.
[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


SizeBi Property

Aspose.Words

Font.SizeBi Property

Gets or sets the font size in points used in a right-to-left document.

[Visual Basic]
Public Property SizeBi As Double
[C#]
public double SizeBi {get; set;}

Example

Shows how to insert and format right-to-left text.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Signal to Microsoft Word that this run of text contains right-to-left text.
builder.Font.Bidi = true;

// Specify the font and font size to be used for the right-to-left text.
builder.Font.NameBi = "Andalus";
builder.Font.SizeBi = 48;

// Specify that the right-to-left text in this run is bold and italic.
builder.Font.ItalicBi = true;
builder.Font.BoldBi = true;

// Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia.
// For the list of locale identifiers see https://docs.microsoft.com/en-us/deployoffice/office2016/language-identifiers-and-optionstate-id-values-in-office-2016
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(ArtifactsDir + "Font.Bidi.doc");

See Also

Font Class | Aspose.Words Namespace


SmallCaps Property

Aspose.Words

Font.SmallCaps Property

True if the font is formatted as small capital letters.

[Visual Basic]
Public Property SmallCaps As Boolean
[C#]
public bool SmallCaps {get; set;}

Example

Shows how to use all capitals and small capitals character formatting properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

Run run = new Run(doc, "All capitals");
run.Font.AllCaps = true;
para.AppendChild(run);

run = new Run(doc, "SMALL CAPITALS");
run.Font.SmallCaps = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Spacing Property

Aspose.Words

Font.Spacing Property

Returns or sets the spacing (in points) between characters .

[Visual Basic]
Public Property Spacing As Double
[C#]
public double Spacing {get; set;}

Example

Shows how to use character scaling and spacing properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Add a run of text with characters 150% width of normal characters.
Run run = new Run(doc, "Wide characters");
run.Font.Scaling = 150;
para.AppendChild(run);

// Add a run of text with extra 1pt space between characters.
run = new Run(doc, "Expanded by 1pt");
run.Font.Spacing = 1;
para.AppendChild(run);

// Add a run of text with space between characters reduced by 1pt.
run = new Run(doc, "Condensed by 1pt");
run.Font.Spacing = -1;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


StrikeThrough Property

Aspose.Words

Font.StrikeThrough Property

True if the font is formatted as strikethrough text.

[Visual Basic]
Public Property StrikeThrough As Boolean
[C#]
public bool StrikeThrough {get; set;}

Example

Shows how to use strike-through character formatting properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

Run run = new Run(doc, "Double strike through text");
run.Font.DoubleStrikeThrough = true;
para.AppendChild(run);

run = new Run(doc, "Single strike through text");
run.Font.StrikeThrough = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Style Property

Aspose.Words

Font.Style Property

Gets or sets the character style applied to this formatting.

[Visual Basic]
Public Property Style As Style
[C#]
public Style Style {get; set;}

Example

Applies double underline to all runs in a document that are formatted with custom character styles.

[C#]

Document doc = new Document(MyDir + "Font.Style.doc");

// Select all run nodes in the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

// Loop through every run node.
foreach (Run run in runs.OfType<Run>())
{
    Style charStyle = run.Font.Style;

    // If the style of the run is not a built-in character style, apply double underline.
    if (!charStyle.BuiltIn)
        run.Font.Underline = Underline.Double;
}

doc.Save(ArtifactsDir + "Font.Style.doc");

See Also

Font Class | Aspose.Words Namespace


StyleIdentifier Property

Aspose.Words

Font.StyleIdentifier Property

Gets or sets the locale independent style identifier of the character style applied to this formatting.

[Visual Basic]
Public Property StyleIdentifier As StyleIdentifier
[C#]
public StyleIdentifier StyleIdentifier {get; set;}

Example

Shows how to use style identifier to find text formatted with a specific character style and apply different character style.

[C#]

Document doc = new Document(MyDir + "Font.StyleIdentifier.doc");

// Select all run nodes in the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

// Loop through every run node.
foreach (Run run in runs.OfType<Run>())
{
    // If the character style of the run is what we want, do what we need. Change the style in this case.
    // Note that using StyleIdentifier we can identify a built-in style regardless
    // of the language of Microsoft Word used to create the document.
    if (run.Font.StyleIdentifier.Equals(StyleIdentifier.Emphasis))
        run.Font.StyleIdentifier = StyleIdentifier.Strong;
}

doc.Save(ArtifactsDir + "Font.StyleIdentifier.doc");

See Also

Font Class | Aspose.Words Namespace


StyleName Property

Aspose.Words

Font.StyleName Property

Gets or sets the name of the character style applied to this formatting.

[Visual Basic]
Public Property StyleName As String
[C#]
public string StyleName {get; set;}

Example

Shows how to use style name to find text formatted with a specific character style and apply different character style.

[C#]

Document doc = new Document(MyDir + "Font.StyleName.doc");

// Select all run nodes in the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

// Loop through every run node.
foreach (Run run in runs.OfType<Run>())
{
    // If the character style of the run is what we want, do what we need. Change the style in this case.
    // Note that names of built in styles could be different in documents
    // created by Microsoft Word versions for different languages.
    if (run.Font.StyleName.Equals("Emphasis"))
        run.Font.StyleName = "Strong";
}

doc.Save(ArtifactsDir + "Font.StyleName.doc");

See Also

Font Class | Aspose.Words Namespace


Subscript Property

Aspose.Words

Font.Subscript Property

True if the font is formatted as subscript.

[Visual Basic]
Public Property Subscript As Boolean
[C#]
public bool Subscript {get; set;}

Example

Shows how to use subscript, superscript, complex script, text effects, and baseline text position properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Add a run of text that is raised 5 points above the baseline.
Run run = new Run(doc, "Raised text");
run.Font.Position = 5;
para.AppendChild(run);

// Add a run of normal text.
run = new Run(doc, "Normal text");
para.AppendChild(run);

// Add a run of text that appears as subscript.
run = new Run(doc, "Subscript");
run.Font.Subscript = true;
para.AppendChild(run);

// Add a run of text that appears as superscript.
run = new Run(doc, "Superscript");
run.Font.Superscript = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


Superscript Property

Aspose.Words

Font.Superscript Property

True if the font is formatted as superscript.

[Visual Basic]
Public Property Superscript As Boolean
[C#]
public bool Superscript {get; set;}

Example

Shows how to use subscript, superscript, complex script, text effects, and baseline text position properties.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Get the paragraph from the document, we will be adding runs of text to it.
Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Add a run of text that is raised 5 points above the baseline.
Run run = new Run(doc, "Raised text");
run.Font.Position = 5;
para.AppendChild(run);

// Add a run of normal text.
run = new Run(doc, "Normal text");
para.AppendChild(run);

// Add a run of text that appears as subscript.
run = new Run(doc, "Subscript");
run.Font.Subscript = true;
para.AppendChild(run);

// Add a run of text that appears as superscript.
run = new Run(doc, "Superscript");
run.Font.Superscript = true;
para.AppendChild(run);

See Also

Font Class | Aspose.Words Namespace


TextEffect Property

Aspose.Words

Font.TextEffect Property

Gets or sets the font animation effect.

[Visual Basic]
Public Property TextEffect As TextEffect
[C#]
public TextEffect TextEffect {get; set;}

Example

Shows how to apply a visual effect to a run.

[C#]

Run run = new Run(doc, "Text with effect");
run.Font.TextEffect = TextEffect.SparkleText;

See Also

Font Class | Aspose.Words Namespace


Underline Property

Aspose.Words

Font.Underline Property

Gets or sets the type of underline applied to the font.

[Visual Basic]
Public Property Underline As Underline
[C#]
public Underline Underline {get; set;}

Example

Shows how use the underline character formatting properties.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Underline = Underline.Dotted;
run.Font.UnderlineColor = Color.Red;
Inserts formatted text using DocumentBuilder.
[C#]

DocumentBuilder builder = new DocumentBuilder();

// Specify font formatting before adding text.
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

builder.Write("Sample text.");
Inserts a hyperlink into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Please make sure to visit ");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
// Insert the link.
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false);

// Revert to default formatting.
builder.Font.ClearFormatting();

builder.Write(" for more information.");

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlink.doc");

See Also

Font Class | Aspose.Words Namespace


UnderlineColor Property

Aspose.Words

Font.UnderlineColor Property

Gets or sets the color of the underline applied to the font.

[Visual Basic]
Public Property UnderlineColor As Color
[C#]
public Color UnderlineColor {get; set;}

Example

Shows how use the underline character formatting properties.

[C#]

Run run = new Run(doc, "Hello");
run.Font.Underline = Underline.Dotted;
run.Font.UnderlineColor = Color.Red;

See Also

Font Class | Aspose.Words Namespace


Font Methods

The methods of the Font class are listed below. For a complete list of Font class members, see the Font Members topic.

Public Instance Methods

ClearFormatting | Resets to default font formatting.
HasDmlEffect | Checks if particular Dml text effect is applied.

See Also

Font Class | Aspose.Words Namespace


Font.ClearFormatting Method

Resets to default font formatting.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Remarks

Removes all font formatting specified explicitly on the object from which Font was obtained so the font formatting will be inherited from the appropriate parent.

Example

Inserts a hyperlink into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Please make sure to visit ");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
// Insert the link.
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false);

// Revert to default formatting.
builder.Font.ClearFormatting();

builder.Write(" for more information.");

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlink.doc");

See Also

Font Class | Aspose.Words Namespace


Font.HasDmlEffect Method

Checks if particular Dml text effect is applied.

[Visual Basic]
Public Function HasDmlEffect( _
ByVal dmlEffectType As TextDmlEffect _
) As Boolean
[C#]
public bool HasDmlEffect(
TextDmlEffect dmlEffectType
);

Parameters

dmlEffectType
Dml text effect type.

Return Value

True if particular Dml text effect is applied.

Example

Shows how to checks if particular Dml text effect is applied.

[C#]

Document doc = new Document(MyDir + "Font.HasDmlEffect.docx");

RunCollection runs = doc.FirstSection.Body.FirstParagraph.Runs;

Assert.True(runs[0].Font.HasDmlEffect(TextDmlEffect.Shadow));
Assert.True(runs[1].Font.HasDmlEffect(TextDmlEffect.Shadow));
Assert.True(runs[2].Font.HasDmlEffect(TextDmlEffect.Reflection));
Assert.True(runs[3].Font.HasDmlEffect(TextDmlEffect.Effect3D));
Assert.True(runs[4].Font.HasDmlEffect(TextDmlEffect.Fill));

See Also

Font Class | Aspose.Words Namespace


Footnote Class

Represents a container for text of a footnote or endnote.

For a list of all members of this type, see Footnote Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.InlineStory
Aspose.Words.Footnote

[Visual Basic]
Public Class Footnote
Inherits InlineStory
[C#]
public class Footnote : InlineStory

Remarks

The Footnote class is used to represent both footnotes and endnotes in a Word document.

Footnote is an inline-level node and can only be a child of Paragraph.

Footnote can contain Paragraph and Table child nodes.

Example

Shows how to add a footnote to a paragraph in the document and set its marker.

[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Footnote Members | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions | EndnoteOptions


Footnote Members

Footnote overview

Public Instance Constructors

Footnote Constructor Initializes an instance of the Footnote class.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from InlineStory) | Gets the first paragraph in the story.
Font (inherited from InlineStory) | Provides access to the font formatting of the anchor character of this object.
FootnoteType | Returns a value that specifies whether this is a footnote or endnote.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsAuto | Holds a value that specifies whether this is a auto-numbered footnote or footnote with user defined custom reference mark.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from InlineStory) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from InlineStory) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from InlineStory) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from InlineStory) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from InlineStory) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Footnote.
Paragraphs (inherited from InlineStory) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from InlineStory) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
ReferenceMark | Gets/sets custom reference mark to be used for this footnote. Default value is empty string (Empty), meaning auto-numbered footnotes are used.
StoryType | Returns StoryType.Footnotes or StoryType.Endnotes.
Tables (inherited from InlineStory) | Gets a collection of tables that are immediate children of the story.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum (inherited from InlineStory) | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Footnote Class | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions | EndnoteOptions


Footnote Constructor

Initializes an instance of the Footnote class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal footnoteType As FootnoteType _
)
[C#]
public Footnote(
DocumentBase doc,
FootnoteType footnoteType
);

Parameters

doc
The owner document.
footnoteType
A FootnoteType value that specifies whether this is a footnote or endnote.

Remarks

When Footnote is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Footnote to the document use InsertAfter or InsertBefore on the paragraph where you want the footnote inserted.

Example

Shows how to add a footnote to a paragraph in the document and set its marker.

[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

See Also

Footnote Class | Aspose.Words Namespace


Footnote Properties

The properties of the Footnote class are listed below. For a complete list of Footnote class members, see the Footnote Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from InlineStory) | Gets the first paragraph in the story.
Font (inherited from InlineStory) | Provides access to the font formatting of the anchor character of this object.
FootnoteType | Returns a value that specifies whether this is a footnote or endnote.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsAuto | Holds a value that specifies whether this is a auto-numbered footnote or footnote with user defined custom reference mark.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from InlineStory) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from InlineStory) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from InlineStory) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from InlineStory) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from InlineStory) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Footnote.
Paragraphs (inherited from InlineStory) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from InlineStory) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
ReferenceMark | Gets/sets custom reference mark to be used for this footnote. Default value is empty string (Empty), meaning auto-numbered footnotes are used.
StoryType | Returns StoryType.Footnotes or StoryType.Endnotes.
Tables (inherited from InlineStory) | Gets a collection of tables that are immediate children of the story.

See Also

Footnote Class | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions | EndnoteOptions


FootnoteType Property

Aspose.Words

Footnote.FootnoteType Property

Returns a value that specifies whether this is a footnote or endnote.

[Visual Basic]
Public ReadOnly Property FootnoteType As FootnoteType
[C#]
public FootnoteType FootnoteType {get;}

Example

Demonstrates the difference between footnotes and endnotes.

[C#]

// Create a document and a corresponding document builder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Write text and insert a footnote to reference it at the bottom of the page
builder.Write("Footnote referenced main body text.");
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text, will appear at the bottom of the page that contains the referenced text.");

// Write text and insert an endnote to reference it at the end of the document
builder.Write("Endnote referenced main body text.");
Footnote endnote = builder.InsertFootnote(FootnoteType.Endnote, "Endnote text, will appear at the very end of the document.");

// Since endnotes are at the end of the document, breaks like this will push them down while the footnotes stay where they are
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.InsertBreak(BreakType.SectionBreakNewPage);

Assert.AreEqual(FootnoteType.Footnote, footnote.FootnoteType);
Assert.AreEqual(FootnoteType.Endnote, endnote.FootnoteType);

doc.Save(ArtifactsDir + "InlineStory.FootnoteEndnote.docx");

See Also

Footnote Class | Aspose.Words Namespace


IsAuto Property

Aspose.Words

Footnote.IsAuto Property

Holds a value that specifies whether this is a auto-numbered footnote or footnote with user defined custom reference mark.

[Visual Basic]
Public Property IsAuto As Boolean
[C#]
public bool IsAuto {get; set;}

Remarks

ReferenceMark initialized with empty string if IsAuto set to false.

Example

Shows how to add a footnote to a paragraph in the document and set its marker.

[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

See Also

Footnote Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Footnote.NodeType Property

Returns NodeType.Footnote.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Footnote Class | Aspose.Words Namespace


ReferenceMark Property

Aspose.Words

Footnote.ReferenceMark Property

Gets/sets custom reference mark to be used for this footnote. Default value is empty string (Empty), meaning auto-numbered footnotes are used.

[Visual Basic]
Public Property ReferenceMark As String
[C#]
public string ReferenceMark {get; set;}

Remarks

If this property is set to empty string (Empty) or null, then IsAuto property will automatically be set to true, if set to anything else then IsAuto will be set to false.

RTF-format can only store 1 symbol as custom reference mark, so upon export only the first symbol will be written others will be discard.

Example

Shows how to add a footnote to a paragraph in the document and set its marker.

[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

See Also

Footnote Class | Aspose.Words Namespace


StoryType Property

Aspose.Words

Footnote.StoryType Property

Returns StoryType.Footnotes or StoryType.Endnotes.

[Visual Basic]
Overrides Public ReadOnly Property StoryType As StoryType
[C#]
public override StoryType StoryType {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

Footnote Class | Aspose.Words Namespace


Footnote Methods

The methods of the Footnote class are listed below. For a complete list of Footnote class members, see the Footnote Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum (inherited from InlineStory) | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Footnote Class | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions | EndnoteOptions


Footnote.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitFootnoteStart, then calls Accept for all child nodes of the footnote and calls DocumentVisitor.VisitFootnoteEnd at the end.

Example

Traverse a document with a visitor that prints all footnotes that it encounters.

[C#]

public void FootnoteToText()
{
    // Open the document that has footnotes we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    FootnoteInfoPrinter visitor = new FootnoteInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about footnotes encountered in the document.
/// </summary>
public class FootnoteInfoPrinter : DocumentVisitor
{
    public FootnoteInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideFootnote = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Footnote node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        IndentAndAppendLine("[Footnote start] Type: " + footnote.FootnoteType);
        mDocTraversalDepth++;
        mVisitorIsInsideFootnote = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a Footnote node is ended.
    /// </summary>
    public override VisitorAction VisitFootnoteEnd(Footnote footnote)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[Footnote end]");
        mVisitorIsInsideFootnote = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideFootnote) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideFootnote;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

Footnote Class | Aspose.Words Namespace


FootnoteNumberingRule Enumeration

Determines when automatic footnote or endnote numbering restarts.

[Visual Basic]
Public Enum FootnoteNumberingRule
[C#]
public enum FootnoteNumberingRule

Remarks

Example

Shows how to define when automatic numbering for footnotes restarts in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.FootnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;

Members

Member Name | Description | Value
Continuous | Numbering continuous throughout the document. | 0
RestartSection | Numbering restarts at each section. | 1
RestartPage | Numbering restarts at each page. Valid for footnotes only. | 2
Default | Equals Continuous. | 0

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | FootnoteOptions | EndnoteOptions


FootnoteOptions Class

Represents the footnote numbering options for a document or section.

For a list of all members of this type, see FootnoteOptions Members.

System.Object
Aspose.Words.FootnoteOptions

[Visual Basic]
NotInheritable Public Class FootnoteOptions
[C#]
public sealed class FootnoteOptions

Remarks

Example

Shows how to set the number of columns with which the footnotes area is formatted.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

// Lets change number of columns for footnotes on page. If columns value is 0 than footnotes area
// is formatted with a number of columns based on the number of columns on the displayed page
doc.FootnoteOptions.Columns = 2;
doc.Save(ArtifactsDir + "Document.FootnoteOptions.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FootnoteOptions Members | Aspose.Words Namespace | FootnoteOptions | FootnoteOptions


FootnoteOptions Members

FootnoteOptions overview

Public Instance Properties

Columns | Specifies the number of columns with which the footnotes area is formatted.
NumberStyle | Specifies the number format for automatically numbered footnotes.
Position | Specifies the footnotes position.
RestartRule | Determines when automatic numbering restarts.
StartNumber | Specifies the starting number or character for the first automatically numbered footnotes.

See Also

FootnoteOptions Class | Aspose.Words Namespace | FootnoteOptions | FootnoteOptions


FootnoteOptions Properties

The properties of the FootnoteOptions class are listed below. For a complete list of FootnoteOptions class members, see the FootnoteOptions Members topic.

Public Instance Properties

Columns | Specifies the number of columns with which the footnotes area is formatted.
NumberStyle | Specifies the number format for automatically numbered footnotes.
Position | Specifies the footnotes position.
RestartRule | Determines when automatic numbering restarts.
StartNumber | Specifies the starting number or character for the first automatically numbered footnotes.

See Also

FootnoteOptions Class | Aspose.Words Namespace | FootnoteOptions | FootnoteOptions


Columns Property

Aspose.Words

FootnoteOptions.Columns Property

Specifies the number of columns with which the footnotes area is formatted.

[Visual Basic]
Public Property Columns As Integer
[C#]
public int Columns {get; set;}

Remarks

If this property has the value of 0, the footnotes area is formatted with a number of columns based on the number of columns on the displayed page. The default value is 0.

Example

Shows how to set the number of columns with which the footnotes area is formatted.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

// Lets change number of columns for footnotes on page. If columns value is 0 than footnotes area
// is formatted with a number of columns based on the number of columns on the displayed page
doc.FootnoteOptions.Columns = 2;
doc.Save(ArtifactsDir + "Document.FootnoteOptions.docx");

See Also

FootnoteOptions Class | Aspose.Words Namespace


NumberStyle Property

Aspose.Words

FootnoteOptions.NumberStyle Property

Specifies the number format for automatically numbered footnotes.

[Visual Basic]
NotOverridable Public Property NumberStyle As NumberStyle
[C#]
public NumberStyle NumberStyle {get; set;}

Remarks

Not all number styles are applicable for this property. For the list of applicable number styles see the Insert Footnote or Endnote dialog box in Microsoft Word. If you select a number style that is not applicable, Microsoft Word will revert to a default value.

Example

Shows how to define numbering format for footnotes in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.FootnoteOptions.NumberStyle = NumberStyle.Arabic1;

See Also

FootnoteOptions Class | Aspose.Words Namespace


Position Property

Aspose.Words

FootnoteOptions.Position Property

Specifies the footnotes position.

[Visual Basic]
Public Property Position As FootnotePosition
[C#]
public FootnotePosition Position {get; set;}

Example

Shows how to define footnote position in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.FootnoteOptions.Position = FootnotePosition.BeneathText;

See Also

FootnoteOptions Class | Aspose.Words Namespace


RestartRule Property

Aspose.Words

FootnoteOptions.RestartRule Property

Determines when automatic numbering restarts.

[Visual Basic]
NotOverridable Public Property RestartRule As FootnoteNumberingRule
[C#]
public FootnoteNumberingRule RestartRule {get; set;}

Example

Shows how to define when automatic numbering for footnotes restarts in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.FootnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;

See Also

FootnoteOptions Class | Aspose.Words Namespace


StartNumber Property

Aspose.Words

FootnoteOptions.StartNumber Property

Specifies the starting number or character for the first automatically numbered footnotes.

[Visual Basic]
NotOverridable Public Property StartNumber As Integer
[C#]
public int StartNumber {get; set;}

Remarks

This property has effect only when RestartRule is set to Continuous.

Example

Shows how to define the starting number or character for the first automatically numbered footnotes.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.FootnoteOptions.StartNumber = 1;

See Also

FootnoteOptions Class | Aspose.Words Namespace


FootnotePosition Enumeration

Defines the footnote position.

[Visual Basic]
Public Enum FootnotePosition
[C#]
public enum FootnotePosition

Remarks

Example

Shows how to define footnote position in the document.

[C#]

Document doc = new Document(MyDir + "Document.FootnoteEndnote.docx");

doc.FootnoteOptions.Position = FootnotePosition.BeneathText;

Members

Member Name | Description | Value
BottomOfPage | Footnotes are output at the bottom of each page. | 1
BeneathText | Footnotes are output beneath text on each page. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | FootnoteOptions


FootnoteType Enumeration

Specifies whether this is a footnote or an endnote.

[Visual Basic]
Public Enum FootnoteType
[C#]
public enum FootnoteType

Remarks

Both footnotes and endnotes are represented by objects by the Footnote class. Use FootnoteType to distinguish between footnotes and endnotes.

Example

Shows how to add a footnote to a paragraph in the document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

for (int i = 0; i <= 100; i++)
{
    builder.Write("Some text " + i);

    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i);
    builder.InsertFootnote(FootnoteType.Footnote, "Footnote text " + i, "242");
}
Shows how to add a footnote to a paragraph in the document and set its marker.
[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

Members

Member Name | Description | Value
Footnote | The object is a footnote. | 0
Endnote | The object is an endnote. | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | Footnote


FrameFormat Class

Represents frame related formatting for a paragraph.

For a list of all members of this type, see FrameFormat Members.

System.Object
Aspose.Words.FrameFormat

[Visual Basic]
Public Class FrameFormat
[C#]
public class FrameFormat

Remarks

This object is always created. If a paragraph is a frame, then all properties will contain respective values, otherwise all properties are set to their defaults.

Use IsFrame to check whether paragraph is a frame.

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FrameFormat Members | Aspose.Words Namespace


FrameFormat Members

FrameFormat overview

Public Instance Properties

Height | Gets the height of the specified frame.
HeightRule | Gets the rule for determining the height of the specified frame.
HorizontalAlignment | Gets horizontal alignment of the specified frame.
HorizontalDistanceFromText | Gets horizontal distance between a frame and the surrounding text, in points.
HorizontalPosition | Gets horizontal distance between the edge of the frame and the item specified by the RelativeHorizontalPosition property.
IsFrame | Returns true if the paragraph is a frame.
RelativeHorizontalPosition | Gets the relative horizontal position of a frame.
RelativeVerticalPosition | Gets the relative vertical position of a frame.
VerticalAlignment | Gets vertical alignment of the specified frame.
VerticalDistanceFromText | Specifies vertical distance (in points) between a frame and the surrounding text.
VerticalPosition | Gets vertical distance between the edge of the frame and the item specified by the RelativeVerticalPosition property.
Width | Gets the width of the specified frame, in points.

See Also

FrameFormat Class | Aspose.Words Namespace


FrameFormat Properties

The properties of the FrameFormat class are listed below. For a complete list of FrameFormat class members, see the FrameFormat Members topic.

Public Instance Properties

Height | Gets the height of the specified frame.
HeightRule | Gets the rule for determining the height of the specified frame.
HorizontalAlignment | Gets horizontal alignment of the specified frame.
HorizontalDistanceFromText | Gets horizontal distance between a frame and the surrounding text, in points.
HorizontalPosition | Gets horizontal distance between the edge of the frame and the item specified by the RelativeHorizontalPosition property.
IsFrame | Returns true if the paragraph is a frame.
RelativeHorizontalPosition | Gets the relative horizontal position of a frame.
RelativeVerticalPosition | Gets the relative vertical position of a frame.
VerticalAlignment | Gets vertical alignment of the specified frame.
VerticalDistanceFromText | Specifies vertical distance (in points) between a frame and the surrounding text.
VerticalPosition | Gets vertical distance between the edge of the frame and the item specified by the RelativeVerticalPosition property.
Width | Gets the width of the specified frame, in points.

See Also

FrameFormat Class | Aspose.Words Namespace


Height Property

Aspose.Words

FrameFormat.Height Property

Gets the height of the specified frame.

[Visual Basic]
Public ReadOnly Property Height As Double
[C#]
public double Height {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


HeightRule Property

Aspose.Words

FrameFormat.HeightRule Property

Gets the rule for determining the height of the specified frame.

[Visual Basic]
Public ReadOnly Property HeightRule As HeightRule
[C#]
public HeightRule HeightRule {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


HorizontalAlignment Property

Aspose.Words

FrameFormat.HorizontalAlignment Property

Gets horizontal alignment of the specified frame.

[Visual Basic]
Public ReadOnly Property HorizontalAlignment As HorizontalAlignment
[C#]
public HorizontalAlignment HorizontalAlignment {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


HorizontalDistanceFromText Property

Aspose.Words

FrameFormat.HorizontalDistanceFromText Property

Gets horizontal distance between a frame and the surrounding text, in points.

[Visual Basic]
Public ReadOnly Property HorizontalDistanceFromText As Double
[C#]
public double HorizontalDistanceFromText {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


HorizontalPosition Property

Aspose.Words

FrameFormat.HorizontalPosition Property

Gets horizontal distance between the edge of the frame and the item specified by the RelativeHorizontalPosition property.

[Visual Basic]
Public ReadOnly Property HorizontalPosition As Double
[C#]
public double HorizontalPosition {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


IsFrame Property

Aspose.Words

FrameFormat.IsFrame Property

Returns true if the paragraph is a frame.

[Visual Basic]
Public ReadOnly Property IsFrame As Boolean
[C#]
public bool IsFrame {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


RelativeHorizontalPosition Property

Aspose.Words

FrameFormat.RelativeHorizontalPosition Property

Gets the relative horizontal position of a frame.

[Visual Basic]
Public ReadOnly Property RelativeHorizontalPosition As RelativeHorizontalPosition
[C#]
public RelativeHorizontalPosition RelativeHorizontalPosition {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


RelativeVerticalPosition Property

Aspose.Words

FrameFormat.RelativeVerticalPosition Property

Gets the relative vertical position of a frame.

[Visual Basic]
Public ReadOnly Property RelativeVerticalPosition As RelativeVerticalPosition
[C#]
public RelativeVerticalPosition RelativeVerticalPosition {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


VerticalAlignment Property

Aspose.Words

FrameFormat.VerticalAlignment Property

Gets vertical alignment of the specified frame.

[Visual Basic]
Public ReadOnly Property VerticalAlignment As VerticalAlignment
[C#]
public VerticalAlignment VerticalAlignment {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


VerticalDistanceFromText Property

Aspose.Words

FrameFormat.VerticalDistanceFromText Property

Specifies vertical distance (in points) between a frame and the surrounding text.

[Visual Basic]
Public ReadOnly Property VerticalDistanceFromText As Double
[C#]
public double VerticalDistanceFromText {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


VerticalPosition Property

Aspose.Words

FrameFormat.VerticalPosition Property

Gets vertical distance between the edge of the frame and the item specified by the RelativeVerticalPosition property.

[Visual Basic]
Public ReadOnly Property VerticalPosition As Double
[C#]
public double VerticalPosition {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


Width Property

Aspose.Words

FrameFormat.Width Property

Gets the width of the specified frame, in points.

[Visual Basic]
Public ReadOnly Property Width As Double
[C#]
public double Width {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

FrameFormat Class | Aspose.Words Namespace


HeaderFooter Class

Represents a container for the header or footer text of a section.

For a list of all members of this type, see HeaderFooter Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Story
Aspose.Words.HeaderFooter

[Visual Basic]
Public Class HeaderFooter
Inherits Story
[C#]
public class HeaderFooter : Story

Remarks

HeaderFooter can contain Paragraph and Table child nodes.

HeaderFooter is a section-level node and can only be a child of Section. There can only be one HeaderFooter or each HeaderFooterType in a Section.

If Section does not have a HeaderFooter of a specific type or the HeaderFooter has no child nodes, this header/footer is considered linked to the header/footer of the same type of the previous section in Microsoft Word.

When HeaderFooter contains at least one Paragraph, it is no longer considered linked to previous in Microsoft Word.

Example

Shows how to replace text in the document footer.

[C#]

// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(MyDir + "HeaderFooter.ReplaceText.doc");

HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = false
};

footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options);

doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.doc");
Creates a header and footer using the document object model and insert them into a section.
[C#]

Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
doc.FirstSection.HeadersFooters.Add(header);

// Add a paragraph with text to the footer.
header.AppendParagraph("My header");

Assert.True(header.IsHeader);

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

Assert.False(footer.IsHeader);

// Add a paragraph with text to the footer.
footer.AppendParagraph("My footer");

Assert.AreEqual(header.ParentSection, footer.ParentSection);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterCreate.docx");
Deletes all footers from all sections, but leaves headers intact.
[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

foreach (Section section in doc.OfType<Section>())
{
    // Up to three different footers are possible in a section (for first, even and odd pages).
    // We check and delete all of them.
    HeaderFooter footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    footer?.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    footer?.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    footer?.Remove();
}

doc.Save(ArtifactsDir + "HeaderFooter.RemoveFooters.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

HeaderFooter Members | Aspose.Words Namespace


HeaderFooter Members

HeaderFooter overview

Public Instance Constructors

HeaderFooter Constructor Creates a new header or footer of the specified type.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from Story) | Gets the first paragraph in the story.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HeaderFooterType | Gets the type of this header/footer.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsHeader | True if this HeaderFooter object is a header.
IsLinkedToPrevious | True if this header or footer is linked to the corresponding header or footer in the previous section.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from Story) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.HeaderFooter.
Paragraphs (inherited from Story) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentSection | Gets the parent section of this story.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType (inherited from Story) | Gets the type of this story.
Tables (inherited from Story) | Gets a collection of tables that are immediate children of the story.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendParagraph (inherited from Story) | A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.
Clone (inherited from Node) |
DeleteShapes (inherited from Story) | Deletes all shapes from the text of this story.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

HeaderFooter Class | Aspose.Words Namespace


HeaderFooter Constructor

Creates a new header or footer of the specified type.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase, _
ByVal headerFooterType As HeaderFooterType _
)
[C#]
public HeaderFooter(
DocumentBase doc,
HeaderFooterType headerFooterType
);

Parameters

doc
The owner document.
headerFooterType
A HeaderFooterType value that specifies the type of the header or footer.

Remarks

When HeaderFooter is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append HederFooter to a Section use Section.InsertAfter, Section.InsertBefore, HeadersFooters.Add or HeadersFooters.Insert.

Example

Creates a header and footer using the document object model and insert them into a section.

[C#]

Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
doc.FirstSection.HeadersFooters.Add(header);

// Add a paragraph with text to the footer.
header.AppendParagraph("My header");

Assert.True(header.IsHeader);

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

Assert.False(footer.IsHeader);

// Add a paragraph with text to the footer.
footer.AppendParagraph("My footer");

Assert.AreEqual(header.ParentSection, footer.ParentSection);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterCreate.docx");

See Also

HeaderFooter Class | Aspose.Words Namespace


HeaderFooter Properties

The properties of the HeaderFooter class are listed below. For a complete list of HeaderFooter class members, see the HeaderFooter Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph (inherited from Story) | Gets the first paragraph in the story.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HeaderFooterType | Gets the type of this header/footer.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsHeader | True if this HeaderFooter object is a header.
IsLinkedToPrevious | True if this header or footer is linked to the corresponding header or footer in the previous section.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph (inherited from Story) | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.HeaderFooter.
Paragraphs (inherited from Story) | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentSection | Gets the parent section of this story.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType (inherited from Story) | Gets the type of this story.
Tables (inherited from Story) | Gets a collection of tables that are immediate children of the story.

See Also

HeaderFooter Class | Aspose.Words Namespace


HeaderFooterType Property

Aspose.Words

HeaderFooter.HeaderFooterType Property

Gets the type of this header/footer.

[Visual Basic]
Public ReadOnly Property HeaderFooterType As HeaderFooterType
[C#]
public HeaderFooterType HeaderFooterType {get;}

Example

Creates a header and footer using the document object model and insert them into a section.

[C#]

Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
doc.FirstSection.HeadersFooters.Add(header);

// Add a paragraph with text to the footer.
header.AppendParagraph("My header");

Assert.True(header.IsHeader);

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

Assert.False(footer.IsHeader);

// Add a paragraph with text to the footer.
footer.AppendParagraph("My footer");

Assert.AreEqual(header.ParentSection, footer.ParentSection);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterCreate.docx");

See Also

HeaderFooter Class | Aspose.Words Namespace


IsHeader Property

Aspose.Words

HeaderFooter.IsHeader Property

True if this HeaderFooter object is a header.

[Visual Basic]
Public ReadOnly Property IsHeader As Boolean
[C#]
public bool IsHeader {get;}

Example

Creates a header and footer using the document object model and insert them into a section.

[C#]

Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
doc.FirstSection.HeadersFooters.Add(header);

// Add a paragraph with text to the footer.
header.AppendParagraph("My header");

Assert.True(header.IsHeader);

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

Assert.False(footer.IsHeader);

// Add a paragraph with text to the footer.
footer.AppendParagraph("My footer");

Assert.AreEqual(header.ParentSection, footer.ParentSection);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterCreate.docx");

See Also

HeaderFooter Class | Aspose.Words Namespace


IsLinkedToPrevious Property

Aspose.Words

HeaderFooter.IsLinkedToPrevious Property

True if this header or footer is linked to the corresponding header or footer in the previous section.

[Visual Basic]
Public Property IsLinkedToPrevious As Boolean
[C#]
public bool IsLinkedToPrevious {get; set;}

Remarks

Default is true.

Note, when your link a header or footer, its contents is cleared.

Example

Shows how to link header/footers between sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create three sections
builder.Write("Section 1");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 3");

// Create a header and footer in the first section and give them text
builder.MoveToSection(0);

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("This is the header, which will be displayed in sections 1 and 2.");

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("This is the footer, which will be displayed in sections 1, 2 and 3.");

// If headers/footers are linked by the next section, they appear in that section also
// The second section will display the header/footers of the first
doc.Sections[1].HeadersFooters.LinkToPrevious(true);

// However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
// Linking just overrides the existing headers/footers from the latter section
Assert.AreEqual(doc.Sections[0].HeadersFooters[0].HeaderFooterType, doc.Sections[1].HeadersFooters[0].HeaderFooterType);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].ParentSection, doc.Sections[1].HeadersFooters[0].ParentSection);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].GetText(), doc.Sections[1].HeadersFooters[0].GetText());

// Likewise, unlinking headers/footers makes them not appear
doc.Sections[2].HeadersFooters.LinkToPrevious(false);

// We can also choose only certain header/footer types to get linked, like the footer in this case
// The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
doc.Sections[2].HeadersFooters.LinkToPrevious(HeaderFooterType.FooterPrimary, true);

// The first section's header/footers can't link themselves to anything because there is no previous section
Assert.AreEqual(2, doc.Sections[0].HeadersFooters.Count);
Assert.False(doc.Sections[0].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[0].HeadersFooters[1].IsLinkedToPrevious);

// All of the second section's header/footers are linked to those of the first
Assert.AreEqual(6, doc.Sections[1].HeadersFooters.Count);
Assert.True(doc.Sections[1].HeadersFooters[0].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[1].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[3].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[4].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[5].IsLinkedToPrevious);

// In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
Assert.AreEqual(6, doc.Sections[2].HeadersFooters.Count);
Assert.False(doc.Sections[2].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[1].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[2].HeadersFooters[3].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[4].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[5].IsLinkedToPrevious);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterLink.docx");

See Also

HeaderFooter Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

HeaderFooter.NodeType Property

Returns NodeType.HeaderFooter.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how you can enumerate through children of a composite node and detect types of the children nodes.

[C#]

// Open a document.
Document doc = new Document(MyDir + "Section.BodyNodeType.doc");

// Get the first section in the document.
Section section = doc.FirstSection;

// A Section is a composite node and therefore can contain child nodes.
// Section can contain only Body and HeaderFooter nodes.
foreach (Node node in section)
{
    // Every node has the NodeType property.
    switch (node.NodeType)
    {
        case NodeType.Body:
        {
            // If the node type is Body, we can cast the node to the Body class.
            Body body = (Body) node;

            // Write the content of the main story of the section to the console.
            Console.WriteLine("*** Body ***");
            Console.WriteLine(body.GetText());
            break;
        }
        case NodeType.HeaderFooter:
        {
            // If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
            HeaderFooter headerFooter = (HeaderFooter) node;

            // Write the content of the header footer to the console.
            Console.WriteLine("*** HeaderFooter ***");
            Console.WriteLine(headerFooter.HeaderFooterType);
            Console.WriteLine(headerFooter.GetText());
            break;
        }
        default:
        {
            // Other types of nodes never occur inside a Section node.
            throw new Exception("Unexpected node type in a section.");
        }
    }
}

See Also

HeaderFooter Class | Aspose.Words Namespace


ParentSection Property

Aspose.Words

HeaderFooter.ParentSection Property

Gets the parent section of this story.

[Visual Basic]
Public ReadOnly Property ParentSection As Section
[C#]
public Section ParentSection {get;}

Remarks

ParentSection is equivalent to (Section)ParentNode.

Example

Shows how to link header/footers between sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create three sections
builder.Write("Section 1");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 3");

// Create a header and footer in the first section and give them text
builder.MoveToSection(0);

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("This is the header, which will be displayed in sections 1 and 2.");

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("This is the footer, which will be displayed in sections 1, 2 and 3.");

// If headers/footers are linked by the next section, they appear in that section also
// The second section will display the header/footers of the first
doc.Sections[1].HeadersFooters.LinkToPrevious(true);

// However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
// Linking just overrides the existing headers/footers from the latter section
Assert.AreEqual(doc.Sections[0].HeadersFooters[0].HeaderFooterType, doc.Sections[1].HeadersFooters[0].HeaderFooterType);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].ParentSection, doc.Sections[1].HeadersFooters[0].ParentSection);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].GetText(), doc.Sections[1].HeadersFooters[0].GetText());

// Likewise, unlinking headers/footers makes them not appear
doc.Sections[2].HeadersFooters.LinkToPrevious(false);

// We can also choose only certain header/footer types to get linked, like the footer in this case
// The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
doc.Sections[2].HeadersFooters.LinkToPrevious(HeaderFooterType.FooterPrimary, true);

// The first section's header/footers can't link themselves to anything because there is no previous section
Assert.AreEqual(2, doc.Sections[0].HeadersFooters.Count);
Assert.False(doc.Sections[0].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[0].HeadersFooters[1].IsLinkedToPrevious);

// All of the second section's header/footers are linked to those of the first
Assert.AreEqual(6, doc.Sections[1].HeadersFooters.Count);
Assert.True(doc.Sections[1].HeadersFooters[0].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[1].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[3].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[4].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[5].IsLinkedToPrevious);

// In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
Assert.AreEqual(6, doc.Sections[2].HeadersFooters.Count);
Assert.False(doc.Sections[2].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[1].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[2].HeadersFooters[3].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[4].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[5].IsLinkedToPrevious);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterLink.docx");

See Also

HeaderFooter Class | Aspose.Words Namespace


HeaderFooter Methods

The methods of the HeaderFooter class are listed below. For a complete list of HeaderFooter class members, see the HeaderFooter Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendParagraph (inherited from Story) | A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.
Clone (inherited from Node) |
DeleteShapes (inherited from Story) | Deletes all shapes from the text of this story.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

HeaderFooter Class | Aspose.Words Namespace


HeaderFooter.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitHeaderFooterStart, then calls Accept for all child nodes of the section and calls DocumentVisitor.VisitHeaderFooterEnd at the end.

Example

Traverse a document with a visitor that prints all header/footer nodes that it encounters.

[C#]

public void HeaderFooterToText()
{
    // Open the document that has headers and/or footers we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    HeaderFooterInfoPrinter visitor = new HeaderFooterInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());

    // An alternative way of visiting a document's header/footers section-by-section is by accessing the collection
    // We can also turn it into an array
    HeaderFooter[] headerFooters = doc.FirstSection.HeadersFooters.ToArray();
    Assert.AreEqual(6, headerFooters.Length);
}

/// <summary>
/// This Visitor implementation prints information about HeaderFooter nodes encountered in the document.
/// </summary>
public class HeaderFooterInfoPrinter : DocumentVisitor
{
    public HeaderFooterInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideHeaderFooter = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideHeaderFooter) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        IndentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.HeaderFooterType);
        mDocTraversalDepth++;
        mVisitorIsInsideHeaderFooter = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a HeaderFooter node is ended.
    /// </summary>
    public override VisitorAction VisitHeaderFooterEnd(HeaderFooter headerFooter)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[HeaderFooter end]");
        mVisitorIsInsideHeaderFooter = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideHeaderFooter;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

HeaderFooter Class | Aspose.Words Namespace


HeaderFooterCollection Class

Provides typed access to HeaderFooter nodes of a Section.

For a list of all members of this type, see HeaderFooterCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.HeaderFooterCollection

[Visual Basic]
Public Class HeaderFooterCollection
Inherits NodeCollection
[C#]
public class HeaderFooterCollection : NodeCollection

Remarks

There can be maximum of one HeaderFooter

of each HeaderFooterType per Section.

HeaderFooter objects can occur in any order in the collection.

Example

Creates a header and footer using the document object model and insert them into a section.

[C#]

Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
doc.FirstSection.HeadersFooters.Add(header);

// Add a paragraph with text to the footer.
header.AppendParagraph("My header");

Assert.True(header.IsHeader);

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

Assert.False(footer.IsHeader);

// Add a paragraph with text to the footer.
footer.AppendParagraph("My footer");

Assert.AreEqual(header.ParentSection, footer.ParentSection);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterCreate.docx");
Deletes all footers from all sections, but leaves headers intact.
[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

foreach (Section section in doc.OfType<Section>())
{
    // Up to three different footers are possible in a section (for first, even and odd pages).
    // We check and delete all of them.
    HeaderFooter footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    footer?.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    footer?.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    footer?.Remove();
}

doc.Save(ArtifactsDir + "HeaderFooter.RemoveFooters.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

HeaderFooterCollection Members | Aspose.Words Namespace


HeaderFooterCollection Members

HeaderFooterCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a HeaderFooter at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
LinkToPrevious | Overloaded. Links or unlinks all headers and footers to the corresponding headers and footers in the previous section.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all HeaderFoorters from the collection to a new array of HeaderFoorters.

See Also

HeaderFooterCollection Class | Aspose.Words Namespace


HeaderFooterCollection Properties

The properties of the HeaderFooterCollection class are listed below. For a complete list of HeaderFooterCollection class members, see the HeaderFooterCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a HeaderFooter at the given index.

See Also

HeaderFooterCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

HeaderFooterCollection.Item Property

Retrieves a HeaderFooter of the specified type.

Overload List

Retrieves a HeaderFooter of the specified type.

public HeaderFooter this[Aspose.Words.HeaderFooterType] {get;}

Retrieves a HeaderFooter at the given index.

new public HeaderFooter this[int] {get;}

See Also

HeaderFooterCollection Class | Aspose.Words Namespace


Item Property (HeaderFooterType)

Aspose.Words

HeaderFooterCollection.Item Property (HeaderFooterType)

Retrieves a HeaderFooter of the specified type.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal headerFooterType As HeaderFooterType _
) As HeaderFooter
[C#]
public HeaderFooter this[
Aspose.Words.HeaderFooterType headerFooterType
] {get;}

Parameters

headerFooterType
A HeaderFooterType value that specifies the type of the header/footer to retrieve.

Remarks

Returns null if the header/footer of the specified type is not found.

Example

Shows how to replace text in the document footer.

[C#]

// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(MyDir + "HeaderFooter.ReplaceText.doc");

HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = false
};

footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options);

doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.doc");
Deletes all footers from all sections, but leaves headers intact.
[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

foreach (Section section in doc.OfType<Section>())
{
    // Up to three different footers are possible in a section (for first, even and odd pages).
    // We check and delete all of them.
    HeaderFooter footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    footer?.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    footer?.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    footer?.Remove();
}

doc.Save(ArtifactsDir + "HeaderFooter.RemoveFooters.doc");

See Also

HeaderFooterCollection Class | Aspose.Words Namespace | HeaderFooterCollection.Item Overload List


Item Property (Int32)

Aspose.Words

HeaderFooterCollection.Item Property (Int32)

Retrieves a HeaderFooter at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As HeaderFooter
[C#]
new public HeaderFooter this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to link header/footers between sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create three sections
builder.Write("Section 1");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 3");

// Create a header and footer in the first section and give them text
builder.MoveToSection(0);

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("This is the header, which will be displayed in sections 1 and 2.");

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("This is the footer, which will be displayed in sections 1, 2 and 3.");

// If headers/footers are linked by the next section, they appear in that section also
// The second section will display the header/footers of the first
doc.Sections[1].HeadersFooters.LinkToPrevious(true);

// However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
// Linking just overrides the existing headers/footers from the latter section
Assert.AreEqual(doc.Sections[0].HeadersFooters[0].HeaderFooterType, doc.Sections[1].HeadersFooters[0].HeaderFooterType);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].ParentSection, doc.Sections[1].HeadersFooters[0].ParentSection);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].GetText(), doc.Sections[1].HeadersFooters[0].GetText());

// Likewise, unlinking headers/footers makes them not appear
doc.Sections[2].HeadersFooters.LinkToPrevious(false);

// We can also choose only certain header/footer types to get linked, like the footer in this case
// The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
doc.Sections[2].HeadersFooters.LinkToPrevious(HeaderFooterType.FooterPrimary, true);

// The first section's header/footers can't link themselves to anything because there is no previous section
Assert.AreEqual(2, doc.Sections[0].HeadersFooters.Count);
Assert.False(doc.Sections[0].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[0].HeadersFooters[1].IsLinkedToPrevious);

// All of the second section's header/footers are linked to those of the first
Assert.AreEqual(6, doc.Sections[1].HeadersFooters.Count);
Assert.True(doc.Sections[1].HeadersFooters[0].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[1].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[3].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[4].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[5].IsLinkedToPrevious);

// In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
Assert.AreEqual(6, doc.Sections[2].HeadersFooters.Count);
Assert.False(doc.Sections[2].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[1].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[2].HeadersFooters[3].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[4].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[5].IsLinkedToPrevious);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterLink.docx");

See Also

HeaderFooterCollection Class | Aspose.Words Namespace | HeaderFooterCollection.Item Overload List


HeaderFooterCollection Methods

The methods of the HeaderFooterCollection class are listed below. For a complete list of HeaderFooterCollection class members, see the HeaderFooterCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
LinkToPrevious | Overloaded. Links or unlinks all headers and footers to the corresponding headers and footers in the previous section.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all HeaderFoorters from the collection to a new array of HeaderFoorters.

See Also

HeaderFooterCollection Class | Aspose.Words Namespace


LinkToPrevious Method

Aspose.Words

HeaderFooterCollection.LinkToPrevious Method

Links or unlinks the specified header or footer to the corresponding header or footer in the previous section.

Overload List

Links or unlinks the specified header or footer to the corresponding header or footer in the previous section.

public void LinkToPrevious(HeaderFooterType,bool);

Links or unlinks all headers and footers to the corresponding headers and footers in the previous section.

public void LinkToPrevious(bool);

See Also

HeaderFooterCollection Class | Aspose.Words Namespace


HeaderFooterCollection.LinkToPrevious Method (HeaderFooterType, Boolean)

Links or unlinks the specified header or footer to the corresponding header or footer in the previous section.

[Visual Basic]
Overloads Public Sub LinkToPrevious( _
ByVal headerFooterType As HeaderFooterType, _
ByVal isLinkToPrevious As Boolean _
)
[C#]
public void LinkToPrevious(
HeaderFooterType headerFooterType,
bool isLinkToPrevious
);

Parameters

headerFooterType
A HeaderFooterType value that specifies the header or footer to link/unlink.
isLinkToPrevious
True to link the header or footer to the previous section; false to unlink.

Remarks

If the header or footer of the specified type does not exist, creates it automatically.

Example

Shows how to link header/footers between sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create three sections
builder.Write("Section 1");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 3");

// Create a header and footer in the first section and give them text
builder.MoveToSection(0);

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("This is the header, which will be displayed in sections 1 and 2.");

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("This is the footer, which will be displayed in sections 1, 2 and 3.");

// If headers/footers are linked by the next section, they appear in that section also
// The second section will display the header/footers of the first
doc.Sections[1].HeadersFooters.LinkToPrevious(true);

// However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
// Linking just overrides the existing headers/footers from the latter section
Assert.AreEqual(doc.Sections[0].HeadersFooters[0].HeaderFooterType, doc.Sections[1].HeadersFooters[0].HeaderFooterType);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].ParentSection, doc.Sections[1].HeadersFooters[0].ParentSection);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].GetText(), doc.Sections[1].HeadersFooters[0].GetText());

// Likewise, unlinking headers/footers makes them not appear
doc.Sections[2].HeadersFooters.LinkToPrevious(false);

// We can also choose only certain header/footer types to get linked, like the footer in this case
// The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
doc.Sections[2].HeadersFooters.LinkToPrevious(HeaderFooterType.FooterPrimary, true);

// The first section's header/footers can't link themselves to anything because there is no previous section
Assert.AreEqual(2, doc.Sections[0].HeadersFooters.Count);
Assert.False(doc.Sections[0].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[0].HeadersFooters[1].IsLinkedToPrevious);

// All of the second section's header/footers are linked to those of the first
Assert.AreEqual(6, doc.Sections[1].HeadersFooters.Count);
Assert.True(doc.Sections[1].HeadersFooters[0].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[1].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[3].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[4].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[5].IsLinkedToPrevious);

// In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
Assert.AreEqual(6, doc.Sections[2].HeadersFooters.Count);
Assert.False(doc.Sections[2].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[1].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[2].HeadersFooters[3].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[4].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[5].IsLinkedToPrevious);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterLink.docx");

See Also

HeaderFooterCollection Class | Aspose.Words Namespace | HeaderFooterCollection.LinkToPrevious Overload List


HeaderFooterCollection.LinkToPrevious Method (Boolean)

Links or unlinks all headers and footers to the corresponding headers and footers in the previous section.

[Visual Basic]
Overloads Public Sub LinkToPrevious( _
ByVal isLinkToPrevious As Boolean _
)
[C#]
public void LinkToPrevious(
bool isLinkToPrevious
);

Parameters

isLinkToPrevious
True to link the headers and footers to the previous section; false to unlink them.

Remarks

If any of the headers or footers do not exist, creates them automatically.

Example

Shows how to link header/footers between sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create three sections
builder.Write("Section 1");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 3");

// Create a header and footer in the first section and give them text
builder.MoveToSection(0);

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("This is the header, which will be displayed in sections 1 and 2.");

builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("This is the footer, which will be displayed in sections 1, 2 and 3.");

// If headers/footers are linked by the next section, they appear in that section also
// The second section will display the header/footers of the first
doc.Sections[1].HeadersFooters.LinkToPrevious(true);

// However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
// Linking just overrides the existing headers/footers from the latter section
Assert.AreEqual(doc.Sections[0].HeadersFooters[0].HeaderFooterType, doc.Sections[1].HeadersFooters[0].HeaderFooterType);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].ParentSection, doc.Sections[1].HeadersFooters[0].ParentSection);
Assert.AreNotEqual(doc.Sections[0].HeadersFooters[0].GetText(), doc.Sections[1].HeadersFooters[0].GetText());

// Likewise, unlinking headers/footers makes them not appear
doc.Sections[2].HeadersFooters.LinkToPrevious(false);

// We can also choose only certain header/footer types to get linked, like the footer in this case
// The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
doc.Sections[2].HeadersFooters.LinkToPrevious(HeaderFooterType.FooterPrimary, true);

// The first section's header/footers can't link themselves to anything because there is no previous section
Assert.AreEqual(2, doc.Sections[0].HeadersFooters.Count);
Assert.False(doc.Sections[0].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[0].HeadersFooters[1].IsLinkedToPrevious);

// All of the second section's header/footers are linked to those of the first
Assert.AreEqual(6, doc.Sections[1].HeadersFooters.Count);
Assert.True(doc.Sections[1].HeadersFooters[0].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[1].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[3].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[4].IsLinkedToPrevious);
Assert.True(doc.Sections[1].HeadersFooters[5].IsLinkedToPrevious);

// In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
Assert.AreEqual(6, doc.Sections[2].HeadersFooters.Count);
Assert.False(doc.Sections[2].HeadersFooters[0].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[1].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[2].IsLinkedToPrevious);
Assert.True(doc.Sections[2].HeadersFooters[3].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[4].IsLinkedToPrevious);
Assert.False(doc.Sections[2].HeadersFooters[5].IsLinkedToPrevious);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterLink.docx");

See Also

HeaderFooterCollection Class | Aspose.Words Namespace | HeaderFooterCollection.LinkToPrevious Overload List


HeaderFooterCollection.ToArray Method

Copies all HeaderFoorters from the collection to a new array of HeaderFoorters.

[Visual Basic]
Public Function ToArray() As HeaderFooter()
[C#]
new public HeaderFooter[] ToArray();

Return Value

An array of HeaderFoorters.

Example

Traverse a document with a visitor that prints all header/footer nodes that it encounters.

[C#]

public void HeaderFooterToText()
{
    // Open the document that has headers and/or footers we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    HeaderFooterInfoPrinter visitor = new HeaderFooterInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());

    // An alternative way of visiting a document's header/footers section-by-section is by accessing the collection
    // We can also turn it into an array
    HeaderFooter[] headerFooters = doc.FirstSection.HeadersFooters.ToArray();
    Assert.AreEqual(6, headerFooters.Length);
}

/// <summary>
/// This Visitor implementation prints information about HeaderFooter nodes encountered in the document.
/// </summary>
public class HeaderFooterInfoPrinter : DocumentVisitor
{
    public HeaderFooterInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideHeaderFooter = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideHeaderFooter) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        IndentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.HeaderFooterType);
        mDocTraversalDepth++;
        mVisitorIsInsideHeaderFooter = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a HeaderFooter node is ended.
    /// </summary>
    public override VisitorAction VisitHeaderFooterEnd(HeaderFooter headerFooter)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[HeaderFooter end]");
        mVisitorIsInsideHeaderFooter = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideHeaderFooter;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

HeaderFooterCollection Class | Aspose.Words Namespace


HeaderFooterType Enumeration

Identifies the type of header or footer found in a Word file.

[Visual Basic]
Public Enum HeaderFooterType
[C#]
public enum HeaderFooterType

Example

Deletes all footers from all sections, but leaves headers intact.

[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

foreach (Section section in doc.OfType<Section>())
{
    // Up to three different footers are possible in a section (for first, even and odd pages).
    // We check and delete all of them.
    HeaderFooter footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    footer?.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    footer?.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    footer?.Remove();
}

doc.Save(ArtifactsDir + "HeaderFooter.RemoveFooters.doc");
Inserts a watermark image into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Creates headers and footers in a document using DocumentBuilder.
[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");

Members

Member Name | Description | Value
HeaderEven | Header for even numbered pages. | 0
HeaderPrimary | Primary header, also used for odd numbered pages. | 1
FooterEven | Footer for even numbered pages. | 2
FooterPrimary | Primary footer, also used for odd numbered pages. | 3
HeaderFirst | Header for the first page of the section. | 4
FooterFirst | Footer for the first page of the section. | 5

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


HeightRule Enumeration

Specifies the rule for determining the height of an object.

[Visual Basic]
Public Enum HeightRule
[C#]
public enum HeightRule

Members

Member Name | Description | Value
AtLeast | The height will be at least the specified height in points. It will grow, if needed, to accommodate all text inside an object. | 0
Exactly | The height is specified exactly in points. Please note that if the text cannot fit inside the object of this height, it will appear truncated. | 1
Auto | The height will grow automatically to accommodate all text inside an object. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


HtmlControlType Enumeration

Type of document nodes that represent <input> and <select> elements imported from HTML.

[Visual Basic]
Public Enum HtmlControlType
[C#]
public enum HtmlControlType

Members

Member Name | Description | Value
FormField |  | 0
StructuredDocumentTag |  | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


HtmlLoadOptions Class

Allows to specify additional options when loading HTML document into a Document object.

For a list of all members of this type, see HtmlLoadOptions Members.

System.Object
Aspose.Words.LoadOptions
Aspose.Words.HtmlLoadOptions

[Visual Basic]
Public Class HtmlLoadOptions
Inherits LoadOptions
[C#]
public class HtmlLoadOptions : LoadOptions

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

HtmlLoadOptions Members | Aspose.Words Namespace


HtmlLoadOptions Members

HtmlLoadOptions overview

Public Instance Constructors

HtmlLoadOptions Overloaded. Initializes a new instance of the HtmlLoadOptions class.

Public Instance Properties

AnnotationsAtBlockLevel (inherited from LoadOptions) | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri (inherited from LoadOptions) | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath (inherited from LoadOptions) | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
Encoding (inherited from LoadOptions) | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings (inherited from LoadOptions) | Allows to specify document font settings.
LanguagePreferences (inherited from LoadOptions) | Gets language preferences that will be used when document is loading.
LoadFormat (inherited from LoadOptions) | Specifies the format of the document to be loaded. Default is Auto.
MswVersion (inherited from LoadOptions) | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password (inherited from LoadOptions) | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreferredControlType | Gets or sets preffered type of document nodes that will represent imported <input> and <select> elements. Default value is FormField.
PreserveIncludePictureField (inherited from LoadOptions) | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
ResourceLoadingCallback (inherited from LoadOptions) | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
SupportVml | Specifies HTML parser to parse conditional comments exactly like <!--[if gte vml 1]> and not to parse conditional comments exactly like <![if !vml]>.
UpdateDirtyFields (inherited from LoadOptions) | Specifies whether to update the fields with the dirty attribute.
WarningCallback (inherited from LoadOptions) | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.
WebRequestTimeout | The number of milliseconds to wait before the web request times out. The default value is 100000 milliseconds (100 seconds).

See Also

HtmlLoadOptions Class | Aspose.Words Namespace


HtmlLoadOptions Constructor

Initializes a new instance of this class with default values.

Overload List

Initializes a new instance of this class with default values.

public HtmlLoadOptions();

A shortcut to initialize a new instance of this class with properties set to the specified values.

public HtmlLoadOptions(LoadFormat,string,string);

A shortcut to initialize a new instance of this class with the specified password to load an encrypted document.

public HtmlLoadOptions(string);

See Also

HtmlLoadOptions Class | Aspose.Words Namespace


HtmlLoadOptions Constructor ()

Initializes a new instance of this class with default values.

[Visual Basic]
Overloads Public Sub New()
[C#]
public HtmlLoadOptions();

See Also

HtmlLoadOptions Class | Aspose.Words Namespace | HtmlLoadOptions Constructor Overload List


HtmlLoadOptions Constructor (String)

A shortcut to initialize a new instance of this class with the specified password to load an encrypted document.

[Visual Basic]
Overloads Public Sub New( _
ByVal password As String _
)
[C#]
public HtmlLoadOptions(
string password
);

Parameters

password
The password to open an encrypted document. Can be null or empty string.

See Also

HtmlLoadOptions Class | Aspose.Words Namespace | HtmlLoadOptions Constructor Overload List


HtmlLoadOptions Constructor (LoadFormat, String, String)

A shortcut to initialize a new instance of this class with properties set to the specified values.

[Visual Basic]
Overloads Public Sub New( _
ByVal loadFormat As LoadFormat, _
ByVal password As String, _
ByVal baseUri As String _
)
[C#]
public HtmlLoadOptions(
LoadFormat loadFormat,
string password,
string baseUri
);

Parameters

loadFormat
The format of the document to be loaded.
password
The password to open an encrypted document. Can be null or empty string.
baseUri
The string that will be used to resolve relative URIs to absolute. Can be null or empty string.

See Also

HtmlLoadOptions Class | Aspose.Words Namespace | HtmlLoadOptions Constructor Overload List


HtmlLoadOptions Properties

The properties of the HtmlLoadOptions class are listed below. For a complete list of HtmlLoadOptions class members, see the HtmlLoadOptions Members topic.

Public Instance Properties

AnnotationsAtBlockLevel (inherited from LoadOptions) | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri (inherited from LoadOptions) | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath (inherited from LoadOptions) | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
Encoding (inherited from LoadOptions) | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings (inherited from LoadOptions) | Allows to specify document font settings.
LanguagePreferences (inherited from LoadOptions) | Gets language preferences that will be used when document is loading.
LoadFormat (inherited from LoadOptions) | Specifies the format of the document to be loaded. Default is Auto.
MswVersion (inherited from LoadOptions) | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password (inherited from LoadOptions) | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreferredControlType | Gets or sets preffered type of document nodes that will represent imported <input> and <select> elements. Default value is FormField.
PreserveIncludePictureField (inherited from LoadOptions) | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
ResourceLoadingCallback (inherited from LoadOptions) | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
SupportVml | Specifies HTML parser to parse conditional comments exactly like <!--[if gte vml 1]> and not to parse conditional comments exactly like <![if !vml]>.
UpdateDirtyFields (inherited from LoadOptions) | Specifies whether to update the fields with the dirty attribute.
WarningCallback (inherited from LoadOptions) | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.
WebRequestTimeout | The number of milliseconds to wait before the web request times out. The default value is 100000 milliseconds (100 seconds).

See Also

HtmlLoadOptions Class | Aspose.Words Namespace


PreferredControlType Property

Aspose.Words

HtmlLoadOptions.PreferredControlType Property

Gets or sets preffered type of document nodes that will represent imported <input> and <select> elements. Default value is FormField.

[Visual Basic]
Public Property PreferredControlType As HtmlControlType
[C#]
public HtmlControlType PreferredControlType {get; set;}

Remarks

Please note that setting this property does not guarantee that all imported controls will be of the specified type. If an HTML control is not representable with document nodes of the preferred type, Aspose.Words will use a compatible HtmlControlType for that control.

Example

Shows how to set preferred type of document nodes that will represent imported <input> and <select> elements.

[C#]

const string html = @"
    <html>
        <select name='ComboBox' size='1'>
            <option value='val1'>item1</option>
            <option value='val2'></option>
        </select>
    </html>
";

HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions();
htmlLoadOptions.PreferredControlType = HtmlControlType.StructuredDocumentTag;

Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), htmlLoadOptions);
NodeCollection nodes = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

StructuredDocumentTag tag = (StructuredDocumentTag) nodes[0];

See Also

HtmlLoadOptions Class | Aspose.Words Namespace


SupportVml Property

Aspose.Words

HtmlLoadOptions.SupportVml Property

Specifies HTML parser to parse conditional comments exactly like <!--[if gte vml 1]> and not to parse conditional comments exactly like <![if !vml]>.

[Visual Basic]
Public Property SupportVml As Boolean
[C#]
public bool SupportVml {get; set;}

Example

Shows how to parse HTML document with conditional comments like "<!--[if gte vml 1]>" and "<![if !vml]>"

[C#]

HtmlLoadOptions loadOptions = new HtmlLoadOptions();

//If value is true, then we parse "<!--[if gte vml 1]>", else parse "<![if !vml]>"
loadOptions.SupportVml = true;
//Wait for a response, when loading external resources
loadOptions.WebRequestTimeout = 1000;

Document doc = new Document(MyDir + "Shape.VmlAndDml.htm", loadOptions);
doc.Save(ArtifactsDir + "Shape.VmlAndDml.docx");

See Also

HtmlLoadOptions Class | Aspose.Words Namespace


WebRequestTimeout Property

Aspose.Words

HtmlLoadOptions.WebRequestTimeout Property

The number of milliseconds to wait before the web request times out. The default value is 100000 milliseconds (100 seconds).

[Visual Basic]
Public Property WebRequestTimeout As Integer
[C#]
public int WebRequestTimeout {get; set;}

Remarks

The number of milliseconds that Aspose.Words waits for a response, when loading external resources (images, style sheets) linked in HTML and MHTML documents.

See Also

HtmlLoadOptions Class | Aspose.Words Namespace


Hyphenation Class

Provides methods for working with hyphenation dictionaries. These dictionaries prescribe where words of a specific language can be hyphenated.

For a list of all members of this type, see Hyphenation Members.

System.Object
Aspose.Words.Hyphenation

[Visual Basic]
MustInherit NotInheritable Public Class Hyphenation
[C#]
public abstract sealed class Hyphenation

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Hyphenation Members | Aspose.Words Namespace


Hyphenation Members

Hyphenation overview

Public Static (Shared) Properties

Callback | Gets or sets callback interface used to request dictionaries when page layout of the document is built. This allows delay loading of dictionaries which may be usefull when processing documents in many languages.
WarningCallback | Called during a load hyphenation patterns, when an issue is detected that might result in formatting fidelity loss.

Public Static (Shared) Methods

IsDictionaryRegistered | Returns False if for the specified language there is no dictionary registered or if registered is Null dictionary, True otherwise.
RegisterDictionary | Overloaded. Registers and loads a hyphenation dictionary for the specified language from a stream. Throws if dictionary cannot be read or has invalid format.
UnregisterDictionary | Unregisters a hyphenation dictionary for the specified language. This is different from registering Null dictionary. Unregistering a dictionary enables callback for the specified language.

See Also

Hyphenation Class | Aspose.Words Namespace


Hyphenation Properties

The properties of the Hyphenation class are listed below. For a complete list of Hyphenation class members, see the Hyphenation Members topic.

Public Static (Shared) Properties

Callback | Gets or sets callback interface used to request dictionaries when page layout of the document is built. This allows delay loading of dictionaries which may be usefull when processing documents in many languages.
WarningCallback | Called during a load hyphenation patterns, when an issue is detected that might result in formatting fidelity loss.

See Also

Hyphenation Class | Aspose.Words Namespace


Callback Property

Aspose.Words

Hyphenation.Callback Property

Gets or sets callback interface used to request dictionaries when page layout of the document is built. This allows delay loading of dictionaries which may be usefull when processing documents in many languages.

[Visual Basic]
Public Shared Property Callback As IHyphenationCallback
[C#]
public static IHyphenationCallback Callback {get; set;}

See Also

Hyphenation Class | Aspose.Words Namespace


WarningCallback Property

Aspose.Words

Hyphenation.WarningCallback Property

Called during a load hyphenation patterns, when an issue is detected that might result in formatting fidelity loss.

[Visual Basic]
Public Shared Property WarningCallback As IWarningCallback
[C#]
public static IWarningCallback WarningCallback {get; set;}

See Also

Hyphenation Class | Aspose.Words Namespace


Hyphenation Methods

The methods of the Hyphenation class are listed below. For a complete list of Hyphenation class members, see the Hyphenation Members topic.

Public Static (Shared) Methods

IsDictionaryRegistered | Returns False if for the specified language there is no dictionary registered or if registered is Null dictionary, True otherwise.
RegisterDictionary | Overloaded. Registers and loads a hyphenation dictionary for the specified language from a stream. Throws if dictionary cannot be read or has invalid format.
UnregisterDictionary | Unregisters a hyphenation dictionary for the specified language. This is different from registering Null dictionary. Unregistering a dictionary enables callback for the specified language.

See Also

Hyphenation Class | Aspose.Words Namespace


Hyphenation.IsDictionaryRegistered Method

Returns False if for the specified language there is no dictionary registered or if registered is Null dictionary, True otherwise.

[Visual Basic]
Public Shared Function IsDictionaryRegistered( _
ByVal language As String _
) As Boolean
[C#]
public static bool IsDictionaryRegistered(
string language
);

Example

Shows how to open check if some dictionary is registered.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Hyphenation.RegisterDictionary("en-US", MyDir + "hyph_en_US.dic");

Assert.AreEqual(true, Hyphenation.IsDictionaryRegistered("en-US"));

See Also

Hyphenation Class | Aspose.Words Namespace


RegisterDictionary Method

Aspose.Words

Hyphenation.RegisterDictionary Method

Registers and loads a hyphenation dictionary for the specified language from a stream. Throws if dictionary cannot be read or has invalid format.

Overload List

Registers and loads a hyphenation dictionary for the specified language from a stream. Throws if dictionary cannot be read or has invalid format.

public static void RegisterDictionary(string,Stream);

Registers and loads a hyphenation dictionary for the specified language from file. Throws if dictionary cannot be read or has invalid format. This method can also be used to register Null dictionary to prevent Callback from being called repeatedly for the same language.

public static void RegisterDictionary(string,string);

See Also

Hyphenation Class | Aspose.Words Namespace


Hyphenation.RegisterDictionary Method (String, Stream)

Registers and loads a hyphenation dictionary for the specified language from a stream. Throws if dictionary cannot be read or has invalid format.

[Visual Basic]
Overloads Public Shared Sub RegisterDictionary( _
ByVal language As String, _
ByVal stream As Stream _
)
[C#]
public static void RegisterDictionary(
string language,
Stream stream
);

Parameters

language
A language name, e.g. "en-US". See .NET documentation for "culture name" and RFC 4646 for details.
stream
A stream for the dictionary file in OpenOffice format.

Example

Shows how to open and register a dictionary from a file.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Register by String
Hyphenation.RegisterDictionary("en-US", MyDir + "hyph_en_US.dic");

// Register by stream
Stream dictionaryStream = new FileStream(MyDir + "hyph_de_CH.dic", FileMode.Open);
Hyphenation.RegisterDictionary("de-CH", dictionaryStream);

See Also

Hyphenation Class | Aspose.Words Namespace | Hyphenation.RegisterDictionary Overload List


Hyphenation.RegisterDictionary Method (String, String)

Registers and loads a hyphenation dictionary for the specified language from file. Throws if dictionary cannot be read or has invalid format.

This method can also be used to register Null dictionary to prevent Callback from being called repeatedly for the same language.
[Visual Basic]
Overloads Public Shared Sub RegisterDictionary( _
ByVal language As String, _
ByVal fileName As String _
)
[C#]
public static void RegisterDictionary(
string language,
string fileName
);

Parameters

language
A language name, e.g. "en-US". See .NET documentation for "culture name" and RFC 4646 for details.
fileName
A path to the dictionary file in Open Office format.

If this parameter is null or empty string then registered is Null dictionary and callback is not called anymore for this language.

To enable callback again use UnregisterDictionary method.

Example

Shows how to open and register a dictionary from a file.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Register by String
Hyphenation.RegisterDictionary("en-US", MyDir + "hyph_en_US.dic");

// Register by stream
Stream dictionaryStream = new FileStream(MyDir + "hyph_de_CH.dic", FileMode.Open);
Hyphenation.RegisterDictionary("de-CH", dictionaryStream);

See Also

Hyphenation Class | Aspose.Words Namespace | Hyphenation.RegisterDictionary Overload List


Hyphenation.UnregisterDictionary Method

Unregisters a hyphenation dictionary for the specified language.

This is different from registering Null dictionary. Unregistering a dictionary enables callback for the specified language.
[Visual Basic]
Public Shared Sub UnregisterDictionary( _
ByVal language As String _
)
[C#]
public static void UnregisterDictionary(
string language
);

Parameters

language
A language name, e.g. "en-US". See .NET documentation for "culture name" and RFC 4646 for details.

If null or empty string then all dictionaries are unregistered.

Example

Shows how to un-register a dictionary

[C#]

Document doc = new Document(MyDir + "Document.doc");
Hyphenation.RegisterDictionary("en-US", MyDir + "hyph_en_US.dic");

Hyphenation.UnregisterDictionary("en-US");

Assert.AreEqual(false, Hyphenation.IsDictionaryRegistered("en-US"));

See Also

Hyphenation Class | Aspose.Words Namespace


IHyphenationCallback Interface

Implemented by classes which can register hyphenation dictionaries. Use this mehod

For a list of all members of this type, see IHyphenationCallback Members.

[Visual Basic]
Public Interface IHyphenationCallback
[C#]
public interface IHyphenationCallback

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IHyphenationCallback Members | Aspose.Words Namespace


IHyphenationCallback Members

IHyphenationCallback overview

Public Instance Methods

RequestDictionary Notifies application that hyphenation dictionary for the specified language wasn't found and may need to be registered. Implementation should find a dictionary and register it using RegisterDictionary methods. If dictionary is unavailable for the specified language implementation can opt out of further calls for the same language using RegisterDictionary with null value.

See Also

IHyphenationCallback Interface | Aspose.Words Namespace


IHyphenationCallback Methods

The methods of the IHyphenationCallback interface are listed below. For a complete list of IHyphenationCallback interface members, see the IHyphenationCallback Members topic.

Public Instance Methods

RequestDictionary Notifies application that hyphenation dictionary for the specified language wasn't found and may need to be registered. Implementation should find a dictionary and register it using RegisterDictionary methods. If dictionary is unavailable for the specified language implementation can opt out of further calls for the same language using RegisterDictionary with null value.

See Also

IHyphenationCallback Interface | Aspose.Words Namespace


IHyphenationCallback.RequestDictionary Method

Notifies application that hyphenation dictionary for the specified language wasn't found and may need to be registered.

Implementation should find a dictionary and register it using RegisterDictionary methods.

If dictionary is unavailable for the specified language implementation can opt out of further calls for the same language using RegisterDictionary with null value.
[Visual Basic]
Sub RequestDictionary( _
ByVal language As String _
)
[C#]
void RequestDictionary(
string language
);

Parameters

language
A language name, e.g. "en-US". See .NET documentation for "culture name" and RFC 4646 for details.

Remarks

Exceptions thrown by this method will abort execution of page layout process.

See Also

IHyphenationCallback Interface | Aspose.Words Namespace


ImportFormatMode Enumeration

Specifies how formatting is merged when importing content from another document.

[Visual Basic]
Public Enum ImportFormatMode
[C#]
public enum ImportFormatMode

Remarks

When you copy nodes from one document to another, this option specifies how formatting is resolved when both documents have a style with the same name, but different formatting.

The formatting is resolved as follows:

  1. Built-in styles are matched using their locale independent style identifier. User defined styles are matched using case-sensitive style name.
  2. If a matching style is not found in the destination document, the style (and all styles referenced by it) are copied into the destination document and the imported nodes are updated to reference the new style.
  3. If a matching style already exists in the destination document, what happens depends on the importFormatMode parameter passed to Document.ImportNode as described below.

When using the UseDestinationStyles option, if a matching style already exists in the destination document, the style is not copied and the imported nodes are updated to reference the existing style.

The drawback of using UseDestinationStyles is that the imported text might look different in the destination document comparing to the source document. For example, the "Heading 1" style in the source document uses Arial 16pt font and the "Heading 1" style in the destination document uses Times New Roman 14pt font. When importing text of "Heading 1" style with no other direct formatting, it will appear as Times New Roman 14pt font in the destination document.

Using the KeepSourceFormatting option allows to make sure the imported text looks in the destination document exactly like it was in the source document. If a matching style already exists in the destination document, the source style is copied and given a unique name by appending a suffix number to it, for example "Normal_0" or "Heading 1_5".

The drawback of using KeepSourceFormatting is that if you perform several imports, you could end up with many styles in the destination document and that could make using consistent style formatting in Microsoft Word difficult for this document.

Using KeepDifferentStyles option allows to reuse destination styles if the formatting they provide is identical to the styles in the source document. If the style in destination document is different from the source then it is imported.

Example

Shows how to insert a document content into another document keep formatting of inserted document.

[C#]

Document doc = new Document(MyDir + "Document.docx");

DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);

Document docToInsert = new Document(MyDir + "DocumentBuilder.KeepSourceFormatting.docx");

builder.InsertDocument(docToInsert, ImportFormatMode.KeepSourceFormatting);
builder.Document.Save(ArtifactsDir + "DocumentBuilder.InsertDocument.docx");

Members

Member Name | Description | Value
UseDestinationStyles | Use the destination document styles and copy new styles. This is the default option. | 0
KeepSourceFormatting | Copy all required styles to the destination document, generate unique style names if needed. | 1
KeepDifferentStyles | Only copy styles that are different from those in the source document. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | ImportNode


ImportFormatOptions Class

Allows to specify various import options to format output.

For a list of all members of this type, see ImportFormatOptions Members.

System.Object
Aspose.Words.ImportFormatOptions

[Visual Basic]
Public Class ImportFormatOptions
[C#]
public class ImportFormatOptions

Example

Shows how to resolve styles behavior while inserting documents.

[C#]

Document destDoc = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.DestinationDocument.docx");
Document sourceDoc1 = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.SourceDocument01.docx");
Document sourceDoc2 = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.SourceDocument02.docx");

DocumentBuilder builder = new DocumentBuilder(destDoc);

builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);
builder.MoveToDocumentEnd();

ImportFormatOptions importFormatOptions = new ImportFormatOptions();
importFormatOptions.SmartStyleBehavior = true;

// When SmartStyleBehavior is enabled,
// a source style will be expanded into a direct attributes inside a destination document,
// if KeepSourceFormatting importing mode is used.
builder.InsertDocument(sourceDoc1, ImportFormatMode.KeepSourceFormatting, importFormatOptions);

builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);

// When SmartStyleBehavior is disabled,
// a source style will be expanded only if it is numbered.
// Existing destination attributes will not be overridden, including lists.
builder.InsertDocument(sourceDoc2, ImportFormatMode.UseDestinationStyles);

destDoc.Save(ArtifactsDir + @"DocumentBuilder.SmartStyleBehavior.ResultDocument.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ImportFormatOptions Members | Aspose.Words Namespace


ImportFormatOptions Members

ImportFormatOptions overview

Public Instance Constructors

ImportFormatOptions Constructor Initializes a new instance of the ImportFormatOptions class.

Public Instance Properties

IgnoreTextBoxes | Gets or sets a boolean value that indicates whether to ignore formatting in the text boxes of the source destination during the import. Default value is true.
KeepSourceNumbering | Gets or sets a boolean value that specifies how the numbering will be imported when it clashes in source and destination documents. The default value is false.
SmartStyleBehavior | Gets or sets a boolean value that specifies how styles will be imported when they have equal names in source and destination documents. The default value is false.

See Also

ImportFormatOptions Class | Aspose.Words Namespace


ImportFormatOptions Constructor

Initializes a new instance of the ImportFormatOptions class.

[Visual Basic]
Public Sub New()
[C#]
public ImportFormatOptions();

See Also

ImportFormatOptions Class | Aspose.Words Namespace


ImportFormatOptions Properties

The properties of the ImportFormatOptions class are listed below. For a complete list of ImportFormatOptions class members, see the ImportFormatOptions Members topic.

Public Instance Properties

IgnoreTextBoxes | Gets or sets a boolean value that indicates whether to ignore formatting in the text boxes of the source destination during the import. Default value is true.
KeepSourceNumbering | Gets or sets a boolean value that specifies how the numbering will be imported when it clashes in source and destination documents. The default value is false.
SmartStyleBehavior | Gets or sets a boolean value that specifies how styles will be imported when they have equal names in source and destination documents. The default value is false.

See Also

ImportFormatOptions Class | Aspose.Words Namespace


IgnoreTextBoxes Property

Aspose.Words

ImportFormatOptions.IgnoreTextBoxes Property

Gets or sets a boolean value that indicates whether to ignore formatting in the text boxes of the source destination during the import. Default value is true.

[Visual Basic]
Public Property IgnoreTextBoxes As Boolean
[C#]
public bool IgnoreTextBoxes {get; set;}

Example

Shows how to manage formatting in the text boxes of the source destination during the import.

[C#]

Document dstDoc = new Document(MyDir + "DocumentBuilder.IgnoreTextBoxes.DestinationDocument.docx");
Document srcDoc = new Document(MyDir + "DocumentBuilder.IgnoreTextBoxes.SourceDocument.docx");

ImportFormatOptions importFormatOptions = new ImportFormatOptions();
// Keep the source text boxes formatting when importing
importFormatOptions.IgnoreTextBoxes = false;

NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting, importFormatOptions);

ParagraphCollection srcParas = srcDoc.FirstSection.Body.Paragraphs;
foreach (Node node in srcParas)
{
    Paragraph srcPara = (Paragraph) node;
    Node importedNode = importer.ImportNode(srcPara, true);
    dstDoc.FirstSection.Body.AppendChild(importedNode);
}

dstDoc.Save(ArtifactsDir + "DocumentBuilder.IgnoreTextBoxes.ResultDocument.docx");

See Also

ImportFormatOptions Class | Aspose.Words Namespace


KeepSourceNumbering Property

Aspose.Words

ImportFormatOptions.KeepSourceNumbering Property

Gets or sets a boolean value that specifies how the numbering will be imported when it clashes in source and destination documents. The default value is false.

[Visual Basic]
Public Property KeepSourceNumbering As Boolean
[C#]
public bool KeepSourceNumbering {get; set;}

Example

Shows how the numbering will be imported when it clashes in source and destination documents.

[C#]

Document dstDoc = new Document(MyDir + "DocumentBuilder.KeepSourceNumbering.DestinationDocument.docx");
Document srcDoc = new Document(MyDir + "DocumentBuilder.KeepSourceNumbering.SourceDocument.docx");

ImportFormatOptions importFormatOptions = new ImportFormatOptions();
// Keep source list formatting when importing numbered paragraphs
importFormatOptions.KeepSourceNumbering = true;

NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting, importFormatOptions);

ParagraphCollection srcParas = srcDoc.FirstSection.Body.Paragraphs;
foreach (Node node in srcParas)
{
    Paragraph srcPara = (Paragraph) node;
    Node importedNode = importer.ImportNode(srcPara, true);
    dstDoc.FirstSection.Body.AppendChild(importedNode);
}

dstDoc.Save(ArtifactsDir + "DocumentBuilder.KeepSourceNumbering.ResultDocument.docx");

See Also

ImportFormatOptions Class | Aspose.Words Namespace


SmartStyleBehavior Property

Aspose.Words

ImportFormatOptions.SmartStyleBehavior Property

Gets or sets a boolean value that specifies how styles will be imported when they have equal names in source and destination documents. The default value is false.

[Visual Basic]
Public Property SmartStyleBehavior As Boolean
[C#]
public bool SmartStyleBehavior {get; set;}

Remarks

When this option is enabled, the source style will be expanded into a direct attributes inside a destination document, if KeepSourceFormatting importing mode is used.

When this option is disabled, the source style will be expanded only if it is numbered. Existing destination attributes will not be overridden, including lists.

Example

Shows how to resolve styles behavior while inserting documents.

[C#]

Document destDoc = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.DestinationDocument.docx");
Document sourceDoc1 = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.SourceDocument01.docx");
Document sourceDoc2 = new Document(MyDir + "DocumentBuilder.SmartStyleBehavior.SourceDocument02.docx");

DocumentBuilder builder = new DocumentBuilder(destDoc);

builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);
builder.MoveToDocumentEnd();

ImportFormatOptions importFormatOptions = new ImportFormatOptions();
importFormatOptions.SmartStyleBehavior = true;

// When SmartStyleBehavior is enabled,
// a source style will be expanded into a direct attributes inside a destination document,
// if KeepSourceFormatting importing mode is used.
builder.InsertDocument(sourceDoc1, ImportFormatMode.KeepSourceFormatting, importFormatOptions);

builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);

// When SmartStyleBehavior is disabled,
// a source style will be expanded only if it is numbered.
// Existing destination attributes will not be overridden, including lists.
builder.InsertDocument(sourceDoc2, ImportFormatMode.UseDestinationStyles);

destDoc.Save(ArtifactsDir + @"DocumentBuilder.SmartStyleBehavior.ResultDocument.docx");

See Also

ImportFormatOptions Class | Aspose.Words Namespace


IncorrectPasswordException Class

Thrown if a document is encrypted with a password and the password specified when opening the document is incorrect or missing.

System.Object
System.Exception
Aspose.Words.IncorrectPasswordException

[Visual Basic]
Public Class IncorrectPasswordException
Inherits Exception
[C#]
public class IncorrectPasswordException : Exception

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Inline Class

Base class for inline-level nodes that can have character formatting associated with them, but cannot have child nodes of their own.

For a list of all members of this type, see Inline Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.Run
Aspose.Words.SpecialChar

[Visual Basic]
MustInherit Public Class Inline
Inherits Node
[C#]
public abstract class Inline : Node

Remarks

A class derived from Inline can be a child of Paragraph.

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Inline Members | Aspose.Words Namespace


Inline Members

Inline overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Inline Class | Aspose.Words Namespace


Inline Properties

The properties of the Inline class are listed below. For a complete list of Inline class members, see the Inline Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

Inline Class | Aspose.Words Namespace


Font Property

Aspose.Words

Inline.Font Property

Provides access to the font formatting of this object.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Inline Class | Aspose.Words Namespace


IsDeleteRevision Property

Aspose.Words

Inline.IsDeleteRevision Property

Returns true if this object was deleted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsDeleteRevision As Boolean
[C#]
public bool IsDeleteRevision {get;}

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

See Also

Inline Class | Aspose.Words Namespace


IsFormatRevision Property

Aspose.Words

Inline.IsFormatRevision Property

Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsFormatRevision As Boolean
[C#]
public bool IsFormatRevision {get;}

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

See Also

Inline Class | Aspose.Words Namespace


IsInsertRevision Property

Aspose.Words

Inline.IsInsertRevision Property

Returns true if this object was inserted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsInsertRevision As Boolean
[C#]
public bool IsInsertRevision {get;}

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

See Also

Inline Class | Aspose.Words Namespace


IsMoveFromRevision Property

Aspose.Words

Inline.IsMoveFromRevision Property

Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveFromRevision As Boolean
[C#]
public bool IsMoveFromRevision {get;}

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

See Also

Inline Class | Aspose.Words Namespace


IsMoveToRevision Property

Aspose.Words

Inline.IsMoveToRevision Property

Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveToRevision As Boolean
[C#]
public bool IsMoveToRevision {get;}

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

See Also

Inline Class | Aspose.Words Namespace


ParentParagraph Property

Aspose.Words

Inline.ParentParagraph Property

Retrieves the parent Paragraph of this node.

[Visual Basic]
Public ReadOnly Property ParentParagraph As Paragraph
[C#]
public Paragraph ParentParagraph {get;}

Example

Shows how to process revision-related properties of Inline nodes.

[C#]

Document doc = new Document(MyDir + "Inline.Revisions.docx");

// This document has 6 revisions
Assert.AreEqual(6, doc.Revisions.Count);

// The parent node of a revision is the run that the revision concerns, which is an Inline node
Run run = (Run)doc.Revisions[0].ParentNode;

// Get the parent paragraph
Paragraph firstParagraph = run.ParentParagraph;
RunCollection runs = firstParagraph.Runs;

Assert.AreEqual(6, runs.Count);

// The text in the run at index #2 was typed after revisions were tracked, so it will count as an insert revision
// The font was changed, so it will also be a format revision
Assert.IsTrue(runs[2].IsInsertRevision);
Assert.IsTrue(runs[2].IsFormatRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(runs[1].IsMoveToRevision);
Assert.IsTrue(runs[4].IsMoveFromRevision);

// If an Inline node gets deleted while changes are being tracked, it will leave behind a node with the IsDeleteRevision flag set to true until changes are accepted
Assert.IsTrue(runs[5].IsDeleteRevision);

See Also

Inline Class | Aspose.Words Namespace


InlineStory Class

Base class for inline-level nodes that can contain paragraphs and tables.

For a list of all members of this type, see InlineStory Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.InlineStory
Aspose.Words.Comment
Aspose.Words.Footnote

[Visual Basic]
MustInherit Public Class InlineStory
Inherits CompositeNode
[C#]
public abstract class InlineStory : CompositeNode

Remarks

InlineStory is a container for block-level nodes Paragraph and Table.

The classes that derive from InlineStory are inline-level nodes that can contain their own text (paragraphs and tables). For example, a Comment node contains text of a comment and a Footnote contains text of a footnote.

Example

Shows how to add a comment to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Comment comment = new Comment(doc, "Amy Lee", "AL", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
Shows how to add a footnote to a paragraph in the document and set its marker.
[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

InlineStory Members | Aspose.Words Namespace


InlineStory Members

InlineStory overview

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph in the story.
Font | Provides access to the font formatting of the anchor character of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
Paragraphs | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType | Returns the type of the story.
Tables | Gets a collection of tables that are immediate children of the story.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

InlineStory Class | Aspose.Words Namespace


InlineStory Properties

The properties of the InlineStory class are listed below. For a complete list of InlineStory class members, see the InlineStory Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph in the story.
Font | Provides access to the font formatting of the anchor character of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
Paragraphs | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType | Returns the type of the story.
Tables | Gets a collection of tables that are immediate children of the story.

See Also

InlineStory Class | Aspose.Words Namespace


FirstParagraph Property

Aspose.Words

InlineStory.FirstParagraph Property

Gets the first paragraph in the story.

[Visual Basic]
Public ReadOnly Property FirstParagraph As Paragraph
[C#]
public Paragraph FirstParagraph {get;}

Example

Shows how to add a comment to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Comment comment = new Comment(doc, "Amy Lee", "AL", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
Shows how to add a footnote to a paragraph in the document and set its marker.
[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

See Also

InlineStory Class | Aspose.Words Namespace


Font Property

Aspose.Words

InlineStory.Font Property

Provides access to the font formatting of the anchor character of this object.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

InlineStory Class | Aspose.Words Namespace


IsDeleteRevision Property

Aspose.Words

InlineStory.IsDeleteRevision Property

Returns true if this object was deleted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsDeleteRevision As Boolean
[C#]
public bool IsDeleteRevision {get;}

Example

Shows how to process revision-related properties of InlineStory nodes.

[C#]

// Open a document that has revisions from changes being tracked
Document doc = new Document(MyDir + "InlineStory.Revisions.docx");
Assert.IsTrue(doc.HasRevisions);

// Get a collection of all footnotes from the document
List<Footnote> footnotes = doc.GetChildNodes(NodeType.Footnote, true).Cast<Footnote>().ToList();
Assert.AreEqual(5, footnotes.Count);

// If a node was inserted in Microsoft Word while changes were being tracked, this flag will be set to true
Assert.IsTrue(footnotes[2].IsInsertRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(footnotes[1].IsMoveToRevision);
Assert.IsTrue(footnotes[4].IsMoveFromRevision);

// If a node was deleted while changes were being tracked, it will stay behind as a delete revision until we accept/reject changes
Assert.IsTrue(footnotes[3].IsDeleteRevision);

See Also

InlineStory Class | Aspose.Words Namespace


IsInsertRevision Property

Aspose.Words

InlineStory.IsInsertRevision Property

Returns true if this object was inserted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsInsertRevision As Boolean
[C#]
public bool IsInsertRevision {get;}

Example

Shows how to process revision-related properties of InlineStory nodes.

[C#]

// Open a document that has revisions from changes being tracked
Document doc = new Document(MyDir + "InlineStory.Revisions.docx");
Assert.IsTrue(doc.HasRevisions);

// Get a collection of all footnotes from the document
List<Footnote> footnotes = doc.GetChildNodes(NodeType.Footnote, true).Cast<Footnote>().ToList();
Assert.AreEqual(5, footnotes.Count);

// If a node was inserted in Microsoft Word while changes were being tracked, this flag will be set to true
Assert.IsTrue(footnotes[2].IsInsertRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(footnotes[1].IsMoveToRevision);
Assert.IsTrue(footnotes[4].IsMoveFromRevision);

// If a node was deleted while changes were being tracked, it will stay behind as a delete revision until we accept/reject changes
Assert.IsTrue(footnotes[3].IsDeleteRevision);

See Also

InlineStory Class | Aspose.Words Namespace


IsMoveFromRevision Property

Aspose.Words

InlineStory.IsMoveFromRevision Property

Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveFromRevision As Boolean
[C#]
public bool IsMoveFromRevision {get;}

Example

Shows how to process revision-related properties of InlineStory nodes.

[C#]

// Open a document that has revisions from changes being tracked
Document doc = new Document(MyDir + "InlineStory.Revisions.docx");
Assert.IsTrue(doc.HasRevisions);

// Get a collection of all footnotes from the document
List<Footnote> footnotes = doc.GetChildNodes(NodeType.Footnote, true).Cast<Footnote>().ToList();
Assert.AreEqual(5, footnotes.Count);

// If a node was inserted in Microsoft Word while changes were being tracked, this flag will be set to true
Assert.IsTrue(footnotes[2].IsInsertRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(footnotes[1].IsMoveToRevision);
Assert.IsTrue(footnotes[4].IsMoveFromRevision);

// If a node was deleted while changes were being tracked, it will stay behind as a delete revision until we accept/reject changes
Assert.IsTrue(footnotes[3].IsDeleteRevision);

See Also

InlineStory Class | Aspose.Words Namespace


IsMoveToRevision Property

Aspose.Words

InlineStory.IsMoveToRevision Property

Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveToRevision As Boolean
[C#]
public bool IsMoveToRevision {get;}

Example

Shows how to process revision-related properties of InlineStory nodes.

[C#]

// Open a document that has revisions from changes being tracked
Document doc = new Document(MyDir + "InlineStory.Revisions.docx");
Assert.IsTrue(doc.HasRevisions);

// Get a collection of all footnotes from the document
List<Footnote> footnotes = doc.GetChildNodes(NodeType.Footnote, true).Cast<Footnote>().ToList();
Assert.AreEqual(5, footnotes.Count);

// If a node was inserted in Microsoft Word while changes were being tracked, this flag will be set to true
Assert.IsTrue(footnotes[2].IsInsertRevision);

// If one node was moved from one place to another while changes were tracked,
// the node will be placed at the departure location as a "move to revision",
// and a "move from revision" node will be left behind at the origin, in case we want to reject changes
// Highlighting text and dragging it to another place with the mouse and cut-and-pasting (but not copy-pasting) both count as "move revisions"
// The node with the "IsMoveToRevision" flag is the arrival of the move operation, and the node with the "IsMoveFromRevision" flag is the departure point
Assert.IsTrue(footnotes[1].IsMoveToRevision);
Assert.IsTrue(footnotes[4].IsMoveFromRevision);

// If a node was deleted while changes were being tracked, it will stay behind as a delete revision until we accept/reject changes
Assert.IsTrue(footnotes[3].IsDeleteRevision);

See Also

InlineStory Class | Aspose.Words Namespace


LastParagraph Property

Aspose.Words

InlineStory.LastParagraph Property

Gets the last paragraph in the story.

[Visual Basic]
Public ReadOnly Property LastParagraph As Paragraph
[C#]
public Paragraph LastParagraph {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

InlineStory Class | Aspose.Words Namespace


Paragraphs Property

Aspose.Words

InlineStory.Paragraphs Property

Gets a collection of paragraphs that are immediate children of the story.

[Visual Basic]
Public ReadOnly Property Paragraphs As ParagraphCollection
[C#]
public ParagraphCollection Paragraphs {get;}

Example

Shows how to add a comment to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Comment comment = new Comment(doc, "Amy Lee", "AL", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
Shows how to add a footnote to a paragraph in the document and set its marker.
[C#]

// Create a new document and append some text that we will reference with a footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Main body text.");

// Add a footnote and give it text, which will appear at the bottom of the page
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// This attribute means the footnote in the main text will automatically be assigned a number, "1" in this instance
// The next footnote will get "2"
Assert.True(footnote.IsAuto);

// We can edit the footnote's text like this
// Make sure to move the builder back into the document body afterwards
builder.MoveTo(footnote.FirstParagraph);
builder.Write(" More text added by a DocumentBuilder.");
builder.MoveToDocumentEnd();

Assert.AreEqual("Footnote text. More text added by a DocumentBuilder.", footnote.Paragraphs[0].ToString(SaveFormat.Text).Trim());

builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");

// Substitute the reference number for our own custom mark by setting this variable, "IsAuto" will also be set to false
footnote.ReferenceMark = "RefMark";
Assert.False(footnote.IsAuto);

// This bookmark will get a number "3" even though there was no "2"
builder.Write(" More main body text.");
footnote = builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
Assert.True(footnote.IsAuto);

doc.Save(ArtifactsDir + "InlineStory.AddFootnote.docx");

See Also

InlineStory Class | Aspose.Words Namespace


ParentParagraph Property

Aspose.Words

InlineStory.ParentParagraph Property

Retrieves the parent Paragraph of this node.

[Visual Basic]
Public ReadOnly Property ParentParagraph As Paragraph
[C#]
public Paragraph ParentParagraph {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

InlineStory Class | Aspose.Words Namespace


StoryType Property

Aspose.Words

InlineStory.StoryType Property

Returns the type of the story.

[Visual Basic]
MustOverride Public ReadOnly Property StoryType As StoryType
[C#]
public abstract StoryType StoryType {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

InlineStory Class | Aspose.Words Namespace


Tables Property

Aspose.Words

InlineStory.Tables Property

Gets a collection of tables that are immediate children of the story.

[Visual Basic]
Public ReadOnly Property Tables As TableCollection
[C#]
public TableCollection Tables {get;}

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

InlineStory Class | Aspose.Words Namespace


InlineStory Methods

The methods of the InlineStory class are listed below. For a complete list of InlineStory class members, see the InlineStory Members topic.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum | If the last child is not a paragraph, creates and appends one empty paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

InlineStory Class | Aspose.Words Namespace


InlineStory.EnsureMinimum Method

If the last child is not a paragraph, creates and appends one empty paragraph.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Shows how to insert InlineStory nodes.

[C#]

// Create a new document and insert a blank footnote
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null);

// Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell
Table table = new Table(doc);
table.EnsureMinimum();

// We can place a table inside a footnote, which will make it appear at the footer of the referencing page
Assert.That(footnote.Tables, Is.Empty);
footnote.AppendChild(table);
Assert.AreEqual(1, footnote.Tables.Count);
Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType);

// An InlineStory has an "EnsureMinimum()" method as well, but in this case it makes sure the last child of the node is a paragraph,
// so we can click and write text easily in Microsoft Word
footnote.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType);

// Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote
footnote.Font.Name = "Arial";
footnote.Font.Color = Color.Green;

// All inline story nodes have their own respective story types
Assert.AreEqual(StoryType.Footnotes, footnote.StoryType);

// A comment is another type of inline story
Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now));

// The parent paragraph of an inline story node will be the one from the main document body
Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph);

// However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble
// A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well
Assert.Null(comment.LastParagraph);
comment.EnsureMinimum();
Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType);

// Once we have a paragraph, we can move the builder do it and write our comment
builder.MoveTo(comment.LastParagraph);
builder.Write("My comment");

Assert.AreEqual(StoryType.Comments, comment.StoryType);

doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx");

See Also

InlineStory Class | Aspose.Words Namespace


INodeChangingCallback Interface

Implement this interface if you want to receive notifications when nodes are inserted or removed in the document.

For a list of all members of this type, see INodeChangingCallback Members.

[Visual Basic]
Public Interface INodeChangingCallback
[C#]
public interface INodeChangingCallback

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

INodeChangingCallback Members | Aspose.Words Namespace


INodeChangingCallback Members

INodeChangingCallback overview

Public Instance Methods

NodeInserted | Called when a node belonging to this document has been inserted into another node.
NodeInserting | Called just before a node belonging to this document is about to be inserted into another node.
NodeRemoved | Called when a node belonging to this document has been removed from its parent.
NodeRemoving | Called just before a node belonging to this document is about to be removed from the document.

See Also

INodeChangingCallback Interface | Aspose.Words Namespace


INodeChangingCallback Methods

The methods of the INodeChangingCallback interface are listed below. For a complete list of INodeChangingCallback interface members, see the INodeChangingCallback Members topic.

Public Instance Methods

NodeInserted | Called when a node belonging to this document has been inserted into another node.
NodeInserting | Called just before a node belonging to this document is about to be inserted into another node.
NodeRemoved | Called when a node belonging to this document has been removed from its parent.
NodeRemoving | Called just before a node belonging to this document is about to be removed from the document.

See Also

INodeChangingCallback Interface | Aspose.Words Namespace


INodeChangingCallback.NodeInserted Method

Called when a node belonging to this document has been inserted into another node.

[Visual Basic]
Sub NodeInserted( _
ByVal args As NodeChangingArgs _
)
[C#]
void NodeInserted(
NodeChangingArgs args
);

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

See Also

INodeChangingCallback Interface | Aspose.Words Namespace


INodeChangingCallback.NodeInserting Method

Called just before a node belonging to this document is about to be inserted into another node.

[Visual Basic]
Sub NodeInserting( _
ByVal args As NodeChangingArgs _
)
[C#]
void NodeInserting(
NodeChangingArgs args
);

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

See Also

INodeChangingCallback Interface | Aspose.Words Namespace


INodeChangingCallback.NodeRemoved Method

Called when a node belonging to this document has been removed from its parent.

[Visual Basic]
Sub NodeRemoved( _
ByVal args As NodeChangingArgs _
)
[C#]
void NodeRemoved(
NodeChangingArgs args
);

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

See Also

INodeChangingCallback Interface | Aspose.Words Namespace


INodeChangingCallback.NodeRemoving Method

Called just before a node belonging to this document is about to be removed from the document.

[Visual Basic]
Sub NodeRemoving( _
ByVal args As NodeChangingArgs _
)
[C#]
void NodeRemoving(
NodeChangingArgs args
);

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

See Also

INodeChangingCallback Interface | Aspose.Words Namespace


InternableComplexAttr Class

Base class for internable complex attribute. Internable complex attribute should notify parent collection when going to be changed.

System.Object
Aspose.Words.InternableComplexAttr
Aspose.Words.Border
Aspose.Words.Shading
Aspose.Words.TabStopCollection

[Visual Basic]
MustInherit Public Class InternableComplexAttr
[C#]
public abstract class InternableComplexAttr

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


InterruptionToken Class

This class provides members to manually interrupt Aspose.Words during long running tasks.

For a list of all members of this type, see InterruptionToken Members.

System.Object
Aspose.Words.InterruptionToken

[Visual Basic]
Public Class InterruptionToken
[C#]
public class InterruptionToken

Remarks

At the moment only interruption when rendering to fixed-page formats such as PDF, XPS, image is supported

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

InterruptionToken Members | Aspose.Words Namespace


InterruptionToken Members

InterruptionToken overview

Public Instance Constructors

InterruptionToken Constructor Initializes a new instance of the InterruptionToken class.

Public Instance Methods

BindToCurrentThread | Associates the current thread with this InterruptionToken instance.
Interrupt | Requests Aspose.Words to abandon the current task.

See Also

InterruptionToken Class | Aspose.Words Namespace


InterruptionToken Constructor

Initializes a new instance of the InterruptionToken class.

[Visual Basic]
Public Sub New()
[C#]
public InterruptionToken();

See Also

InterruptionToken Class | Aspose.Words Namespace


InterruptionToken Methods

The methods of the InterruptionToken class are listed below. For a complete list of InterruptionToken class members, see the InterruptionToken Members topic.

Public Instance Methods

BindToCurrentThread | Associates the current thread with this InterruptionToken instance.
Interrupt | Requests Aspose.Words to abandon the current task.

See Also

InterruptionToken Class | Aspose.Words Namespace


InterruptionToken.BindToCurrentThread Method

Associates the current thread with this InterruptionToken instance.

[Visual Basic]
Public Sub BindToCurrentThread()
[C#]
public void BindToCurrentThread();

Remarks

Use this method before calling Interrupt

See Also

InterruptionToken Class | Aspose.Words Namespace


InterruptionToken.Interrupt Method

Requests Aspose.Words to abandon the current task.

[Visual Basic]
Public Sub Interrupt()
[C#]
public void Interrupt();

Remarks

Throws a ThreadInterruptedException on processing the interrupt request.

See Also

InterruptionToken Class | Aspose.Words Namespace


IWarningCallback Interface

Implement this interface if you want to have your own custom method called to capture loss of fidelity warnings that can occur during document loading or saving.

For a list of all members of this type, see IWarningCallback Members.

[Visual Basic]
Public Interface IWarningCallback
[C#]
public interface IWarningCallback

Types that implement IWarningCallback

Type | Description
WarningInfoCollection | Represents a typed collection of WarningInfo objects.

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}
Demonstrates how to receive notifications of font substitutions by using IWarningCallback.
[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Document.doc");

// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;

// We can choose the default font to use in the case of any missing fonts.
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial";

// For testing we will set Aspose.Words to look for fonts only in a folder which doesn't exist. Since Aspose.Words won't
// find any fonts in the specified directory, then during rendering the fonts in the document will be substituted with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this substitution using our callback.
FontSettings.DefaultInstance.SetFontsFolder(String.Empty, false);

// Pass the save options along with the save path to the save method.
doc.Save(ArtifactsDir + "Rendering.MissingFontNotification.pdf");
Shows added fallback to bitmap rendering and changing type of warnings about unsupported metafile records
[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.HandleRasterWarnings.doc");

    MetafileRenderingOptions metafileRenderingOptions =
        new MetafileRenderingOptions
        {
            EmulateRasterOperations = false,
            RenderingMode = MetafileRenderingMode.VectorWithFallback
        };

    // If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
    HandleDocumentWarnings callback = new HandleDocumentWarnings();
    doc.WarningCallback = callback;

    PdfSaveOptions saveOptions = new PdfSaveOptions();
    saveOptions.MetafileRenderingOptions = metafileRenderingOptions;

    doc.Save(ArtifactsDir + "PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);

    Assert.AreEqual(1, callback.mWarnings.Count);
    Assert.True(callback.mWarnings[0].Description.Contains("R2_XORPEN"));
}

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        //For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
        if (info.WarningType == WarningType.MinorFormattingLoss)
        {
            Console.WriteLine("Unsupported operation: " + info.Description);
            mWarnings.Warning(info);
        }
    }

    public WarningInfoCollection mWarnings = new WarningInfoCollection();
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IWarningCallback Members | Aspose.Words Namespace


IWarningCallback Members

IWarningCallback overview

Public Instance Methods

Warning Aspose.Words invokes this method when it encounters some issue during document loading or saving that might result in loss of formatting or data fidelity.

See Also

IWarningCallback Interface | Aspose.Words Namespace


IWarningCallback Methods

The methods of the IWarningCallback interface are listed below. For a complete list of IWarningCallback interface members, see the IWarningCallback Members topic.

Public Instance Methods

Warning Aspose.Words invokes this method when it encounters some issue during document loading or saving that might result in loss of formatting or data fidelity.

See Also

IWarningCallback Interface | Aspose.Words Namespace


IWarningCallback.Warning Method

Aspose.Words invokes this method when it encounters some issue during document loading or saving that might result in loss of formatting or data fidelity.

[Visual Basic]
Sub Warning( _
ByVal info As WarningInfo _
)
[C#]
void Warning(
WarningInfo info
);

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

See Also

IWarningCallback Interface | Aspose.Words Namespace


LanguagePreferences Class

Allows to set up language preferences.

For a list of all members of this type, see LanguagePreferences Members.

System.Object
Aspose.Words.LanguagePreferences

[Visual Basic]
Public Class LanguagePreferences
[C#]
public class LanguagePreferences

Remarks

Implements 'Set the Office Language Preferences' dialog in Word.

Example

Shows how to set up language preferences that will be used when document is loading

[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LanguagePreferences.AddEditingLanguage(EditingLanguage.Japanese);

Document doc = new Document(MyDir + "Document.EditingLanguage.docx", loadOptions);

int localeIdFarEast = doc.Styles.DefaultFont.LocaleIdFarEast;
if (localeIdFarEast == (int)EditingLanguage.Japanese)
    Console.WriteLine("The document either has no any FarEast language set in defaults or it was set to Japanese originally.");
else
    Console.WriteLine("The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

LanguagePreferences Members | Aspose.Words Namespace


LanguagePreferences Members

LanguagePreferences overview

Public Instance Constructors

LanguagePreferences Constructor Initializes a new instance of the LanguagePreferences class.

Public Instance Properties

DefaultEditingLanguage Gets or sets default editing language. The default value is EnglishUS.

Public Instance Methods

AddEditingLanguage | Adds additional editing language.
AddEditingLanguages | Adds additional editing languages.

See Also

LanguagePreferences Class | Aspose.Words Namespace


LanguagePreferences Constructor

Initializes a new instance of the LanguagePreferences class.

[Visual Basic]
Public Sub New()
[C#]
public LanguagePreferences();

See Also

LanguagePreferences Class | Aspose.Words Namespace


LanguagePreferences Properties

The properties of the LanguagePreferences class are listed below. For a complete list of LanguagePreferences class members, see the LanguagePreferences Members topic.

Public Instance Properties

DefaultEditingLanguage Gets or sets default editing language. The default value is EnglishUS.

See Also

LanguagePreferences Class | Aspose.Words Namespace


DefaultEditingLanguage Property

Aspose.Words

LanguagePreferences.DefaultEditingLanguage Property

Gets or sets default editing language.

The default value is EnglishUS.

[Visual Basic]
Public Property DefaultEditingLanguage As EditingLanguage
[C#]
public EditingLanguage DefaultEditingLanguage {get; set;}

Example

Shows how to set language as default

[C#]

LoadOptions loadOptions = new LoadOptions();
// You can set language which only
loadOptions.LanguagePreferences.DefaultEditingLanguage = EditingLanguage.Russian;

Document doc = new Document(MyDir + "Document.EditingLanguage.docx", loadOptions);

int localeId = doc.Styles.DefaultFont.LocaleId;
if (localeId == (int)EditingLanguage.Russian)
    Console.WriteLine("The document either has no any language set in defaults or it was set to Russian originally.");
else
    Console.WriteLine("The document default language was set to another than Russian language originally, so it is not overridden.");

See Also

LanguagePreferences Class | Aspose.Words Namespace


LanguagePreferences Methods

The methods of the LanguagePreferences class are listed below. For a complete list of LanguagePreferences class members, see the LanguagePreferences Members topic.

Public Instance Methods

AddEditingLanguage | Adds additional editing language.
AddEditingLanguages | Adds additional editing languages.

See Also

LanguagePreferences Class | Aspose.Words Namespace


LanguagePreferences.AddEditingLanguage Method

Adds additional editing language.

[Visual Basic]
Public Sub AddEditingLanguage( _
ByVal language As EditingLanguage _
)
[C#]
public void AddEditingLanguage(
EditingLanguage language
);

Example

Shows how to set up language preferences that will be used when document is loading

[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LanguagePreferences.AddEditingLanguage(EditingLanguage.Japanese);

Document doc = new Document(MyDir + "Document.EditingLanguage.docx", loadOptions);

int localeIdFarEast = doc.Styles.DefaultFont.LocaleIdFarEast;
if (localeIdFarEast == (int)EditingLanguage.Japanese)
    Console.WriteLine("The document either has no any FarEast language set in defaults or it was set to Japanese originally.");
else
    Console.WriteLine("The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");

See Also

LanguagePreferences Class | Aspose.Words Namespace


LanguagePreferences.AddEditingLanguages Method

Adds additional editing languages.

[Visual Basic]
Public Sub AddEditingLanguages( _
ByVal languages As EditingLanguage() _
)
[C#]
public void AddEditingLanguages(
EditingLanguage[] languages
);

See Also

LanguagePreferences Class | Aspose.Words Namespace


License Class

Provides methods to license the component.

For a list of all members of this type, see License Members.

System.Object
Aspose.Words.License

[Visual Basic]
Public Class License
[C#]
public class License

Example

Aspose.Words will attempt to find the license file in the embedded resources or in the assembly folders.

[C#]

License license = new License();
license.SetLicense("Aspose.Words.lic");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

License Members | Aspose.Words Namespace


License Members

License overview

Public Instance Constructors

License Constructor Initializes a new instance of this class.

Public Instance Properties

IsLicensed Obsolete. Returns true if a valid license has been applied; false if the component is running in evaluation mode.

Public Instance Methods

SetLicense Overloaded. Licenses the component.

See Also

License Class | Aspose.Words Namespace


License Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New()
[C#]
public License();

Example

Aspose.Words will attempt to find the license file in the embedded resources or in the assembly folders.

[C#]

License license = new License();
license.SetLicense("Aspose.Words.lic");

See Also

License Class | Aspose.Words Namespace


License Properties

The properties of the License class are listed below. For a complete list of License class members, see the License Members topic.

Public Instance Properties

IsLicensed Obsolete. Returns true if a valid license has been applied; false if the component is running in evaluation mode.

See Also

License Class | Aspose.Words Namespace


IsLicensed Property

Aspose.Words

License.IsLicensed Property

NOTE: This property is now obsolete.

This property is obsolete. SetLicense() method raises an exception if license is invalid.

Returns true if a valid license has been applied; false if the component is running in evaluation mode.

[Visual Basic]
Public ReadOnly Property IsLicensed As Boolean
[C#]
public bool IsLicensed {get;}

See Also

License Class | Aspose.Words Namespace


License Methods

The methods of the License class are listed below. For a complete list of License class members, see the License Members topic.

Public Instance Methods

SetLicense Overloaded. Licenses the component.

See Also

License Class | Aspose.Words Namespace


SetLicense Method

Aspose.Words

License.SetLicense Method

Licenses the component.

Overload List

Licenses the component.

public void SetLicense(Stream);

Licenses the component.

public void SetLicense(string);

See Also

License Class | Aspose.Words Namespace


License.SetLicense Method (Stream)

Licenses the component.

[Visual Basic]
Overloads Public Sub SetLicense( _
ByVal stream As Stream _
)
[C#]
public void SetLicense(
Stream stream
);

Parameters

stream
A stream that contains the license.

Remarks

Use this method to load a license from a stream.

Example

Initializes a license from a stream.

[C#]

License license = new License();
license.SetLicense(myStream);

See Also

License Class | Aspose.Words Namespace | License.SetLicense Overload List


License.SetLicense Method (String)

Licenses the component.

[Visual Basic]
Overloads Public Sub SetLicense( _
ByVal licenseName As String _
)
[C#]
public void SetLicense(
string licenseName
);

Parameters

licenseName
Can be a full or short file name or name of an embedded resource. Use an empty string to switch to evaluation mode.

Remarks

Tries to find the license in the following locations:

1. Explicit path.

2. The folder that contains the Aspose component assembly.

3. The folder that contains the client's calling assembly.

4. The folder that contains the entry (startup) assembly.

5. An embedded resource in the client's calling assembly.

Note:On the .NET Compact Framework, tries to find the license only in these locations:

1. Explicit path.

2. An embedded resource in the client's calling assembly.

Example

Aspose.Words will attempt to find the license file in the embedded resources or in the assembly folders.

[C#]

License license = new License();
license.SetLicense("Aspose.Words.lic");

See Also

License Class | Aspose.Words Namespace | License.SetLicense Overload List


LineNumberRestartMode Enumeration

Determines when automatic line numbering restarts.

[Visual Basic]
Public Enum LineNumberRestartMode
[C#]
public enum LineNumberRestartMode

Remarks

Example

Turns on Microsoft Word line numbering for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.LineStartingNumber = 1;
ps.LineNumberCountBy = 5;
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage;
ps.LineNumberDistanceFromText = 50.0d;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(ArtifactsDir + "PageSetup.LineNumbers.doc");

Members

Member Name | Description | Value
RestartPage | Line numbering restarts at the start of every page. | 0
RestartSection | Line numbering restarts at the section start. | 1
Continuous | Line numbering continuous from the previous section. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | PageSetup | LineNumberRestartMode


LineSpacingRule Enumeration

Specifies line spacing values for a paragraph.

[Visual Basic]
Public Enum LineSpacingRule
[C#]
public enum LineSpacingRule

Members

Member Name | Description | Value
AtLeast | The line spacing can be greater than or equal to, but never less than, the value specified in the LineSpacing property. | 0
Exactly | The line spacing never changes from the value specified in the LineSpacing property, even if a larger font is used within the paragraph. | 1
Multiple | The line spacing is specified in the LineSpacing property as the number of lines. One line equals 12 points. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


LineStyle Enumeration

Specifies line style of a Border.

[Visual Basic]
Public Enum LineStyle
[C#]
public enum LineStyle

Example

Inserts a String surrounded by a border into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Font.Border.Color = Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");

Members

Member Name | Description | Value
None |  | 0
Single |  | 1
Thick |  | 2
Double |  | 3
Hairline |  | 5
Dot |  | 6
DashLargeGap |  | 7
DotDash |  | 8
DotDotDash |  | 9
Triple |  | 10
ThinThickSmallGap |  | 11
ThickThinSmallGap |  | 12
ThinThickThinSmallGap |  | 13
ThinThickMediumGap |  | 14
ThickThinMediumGap |  | 15
ThinThickThinMediumGap |  | 16
ThinThickLargeGap |  | 17
ThickThinLargeGap |  | 18
ThinThickThinLargeGap |  | 19
Wave |  | 20
DoubleWave |  | 21
DashSmallGap |  | 22
DashDotStroker |  | 23
Emboss3D |  | 24
Engrave3D |  | 25
Outset |  | 26
Inset |  | 27

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


ListFormat Class

Allows to control what list formatting is applied to a paragraph.

For a list of all members of this type, see ListFormat Members.

System.Object
Aspose.Words.ListFormat

[Visual Basic]
Public Class ListFormat
[C#]
public class ListFormat

Remarks

A paragraph in a Microsoft Word document can be bulleted or numbered. When a paragraph is bulleted or numbered, it is said that list formatting is applied to the paragraph.

You do not create objects of the ListFormat class directly. You access ListFormat as a property of another object that can have list formatting associated with it. At the moment the objects that can have list formatting are: Paragraph, Style and DocumentBuilder.

ListFormat of a Paragraph specifies what list formatting and list level is applied to that particular paragraph.

ListFormat of a Style (applicable to paragraph styles only) allows to specify what list formatting and list level is applied to all paragraphs of that particular style.

ListFormat of a DocumentBuilder provides access to the list formatting at the current cursor position inside the DocumentBuilder.

The list formatting itself is stored inside a List object that is stored separately from the paragraphs. The list objects are stored inside a ListCollection collection. There is a single ListCollection collection per Document.

The paragraphs do not physically belong to a list. The paragraphs just reference a particular list object via the List property and a particular level in the list via the ListLevelNumber property. By setting these two properties you control what bullets and numbering is applied to a paragraph.

Example

Shows how to specify list level number when building a list using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ListFormat Members | Aspose.Words Namespace


ListFormat Members

ListFormat overview

Public Instance Properties

IsListItem | True when the paragraph has bulleted or numbered formatting applied to it.
List | Gets or sets the list this paragraph is a member of.
ListLevel | Returns the list level formatting plus any formatting overrides applied to the current paragraph.
ListLevelNumber | Gets or sets the list level number (0 to 8) for the paragraph.

Public Instance Methods

ApplyBulletDefault | Starts a new default bulleted list and applies it to the paragraph.
ApplyNumberDefault | Starts a new default numbered list and applies it to the paragraph.
ListIndent | Increases the list level of the current paragraph by one level.
ListOutdent | Decreases the list level of the current paragraph by one level.
RemoveNumbers | Removes numbers or bullets from the current paragraph and sets list level to zero.

See Also

ListFormat Class | Aspose.Words Namespace


ListFormat Properties

The properties of the ListFormat class are listed below. For a complete list of ListFormat class members, see the ListFormat Members topic.

Public Instance Properties

IsListItem | True when the paragraph has bulleted or numbered formatting applied to it.
List | Gets or sets the list this paragraph is a member of.
ListLevel | Returns the list level formatting plus any formatting overrides applied to the current paragraph.
ListLevelNumber | Gets or sets the list level number (0 to 8) for the paragraph.

See Also

ListFormat Class | Aspose.Words Namespace


IsListItem Property

Aspose.Words

ListFormat.IsListItem Property

True when the paragraph has bulleted or numbered formatting applied to it.

[Visual Basic]
Public ReadOnly Property IsListItem As Boolean
[C#]
public bool IsListItem {get;}

Example

Finds and outputs all paragraphs in a document that are bulleted or numbered.

[C#]

NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph para in paras.OfType<Paragraph>())
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}",
            para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}

See Also

ListFormat Class | Aspose.Words Namespace


List Property

Aspose.Words

ListFormat.List Property

Gets or sets the list this paragraph is a member of.

[Visual Basic]
Public Property List As List
[C#]
public List List {get; set;}

Remarks

The list that is being assigned to this property must belong to the current document.

The list that is being assigned to this property must not be a list style definition.

Setting this property to null removes bullets and numbering from the paragraph and sets the list level number to zero. Setting this property to null is equivalent to calling RemoveNumbers.

Example

Applies list formatting of an existing list to a collection of paragraphs.

[C#]

Body body = doc.FirstSection.Body;
List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
Shows how to specify list level number when building a list using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");
Shows how to restart numbering in a list by copying a list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");
Shows how to start a numbered list, add a bulleted list inside it, then return to the numbered list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an outline list for the headings.
List outlineList = doc.Lists.Add(ListTemplate.OutlineNumbers);
builder.ListFormat.List = outlineList;
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("This is my Chapter 1");

// Create a numbered list.
List numberedList = doc.Lists.Add(ListTemplate.NumberDefault);
builder.ListFormat.List = numberedList;
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
builder.Writeln("Numbered list item 1.");

// Create a bulleted list.
List bulletedList = doc.Lists.Add(ListTemplate.BulletDefault);
builder.ListFormat.List = bulletedList;
builder.ParagraphFormat.LeftIndent = 72;
builder.Writeln("Bulleted list item 1.");
builder.Writeln("Bulleted list item 2.");
builder.ParagraphFormat.ClearFormatting();

// Revert to the numbered list.
builder.ListFormat.List = numberedList;
builder.Writeln("Numbered list item 2.");
builder.Writeln("Numbered list item 3.");

// Revert to the outline list.
builder.ListFormat.List = outlineList;
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("This is my Chapter 2");

builder.ParagraphFormat.ClearFormatting();

builder.Document.Save(ArtifactsDir + "Lists.NestedLists.doc");

See Also

ListFormat Class | Aspose.Words Namespace | ListLevelNumber | RemoveNumbers


ListLevel Property

Aspose.Words

ListFormat.ListLevel Property

Returns the list level formatting plus any formatting overrides applied to the current paragraph.

[Visual Basic]
Public ReadOnly Property ListLevel As ListLevel
[C#]
public ListLevel ListLevel {get;}

Example

Shows how to modify list formatting of the current list level.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create and apply list formatting to the current paragraph.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberDefault);

// Modify formatting of the current (first) list level.
builder.ListFormat.ListLevel.Font.Bold = true;

builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

See Also

ListFormat Class | Aspose.Words Namespace


ListLevelNumber Property

Aspose.Words

ListFormat.ListLevelNumber Property

Gets or sets the list level number (0 to 8) for the paragraph.

[Visual Basic]
Public Property ListLevelNumber As Integer
[C#]
public int ListLevelNumber {get; set;}

Remarks

In Word documents, lists may consist of 1 or 9 levels, numbered 0 to 8.

Has effect only when the List property is set to reference a valid list.

Example

Applies list formatting of an existing list to a collection of paragraphs.

[C#]

Body body = doc.FirstSection.Body;
List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
Creates new list formatting and applies it to a collection of paragraphs.
[C#]

List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

Body body = doc.FirstSection.Body;
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 1;
}
Shows how to specify list level number when building a list using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");

See Also

ListFormat Class | Aspose.Words Namespace | List


ListFormat Methods

The methods of the ListFormat class are listed below. For a complete list of ListFormat class members, see the ListFormat Members topic.

Public Instance Methods

ApplyBulletDefault | Starts a new default bulleted list and applies it to the paragraph.
ApplyNumberDefault | Starts a new default numbered list and applies it to the paragraph.
ListIndent | Increases the list level of the current paragraph by one level.
ListOutdent | Decreases the list level of the current paragraph by one level.
RemoveNumbers | Removes numbers or bullets from the current paragraph and sets list level to zero.

See Also

ListFormat Class | Aspose.Words Namespace


ListFormat.ApplyBulletDefault Method

Starts a new default bulleted list and applies it to the paragraph.

[Visual Basic]
Public Sub ApplyBulletDefault()
[C#]
public void ApplyBulletDefault();

Remarks

This is a shortcut method that creates a new list using the default bulleted template, applies it to the paragraph and selects the 1st list level.

Example

Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln("Aspose.Words allows:");
builder.Writeln();

// Start a numbered list with default formatting.
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Opening documents from different formats:");

// Go to second list level, add more text.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");

// Outdent to the first list level.
builder.ListFormat.ListOutdent();
builder.Writeln("Processing documents");
builder.Writeln("Saving documents in different formats:");

// Indent the list level again.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");
builder.Writeln("MHTML");
builder.Writeln("Plain text");

// Outdent the list level again.
builder.ListFormat.ListOutdent();
builder.Writeln("Doing many other things!");

// End the numbered list.
builder.ListFormat.RemoveNumbers();
builder.Writeln();

builder.Writeln("Aspose.Words main advantages are:");
builder.Writeln();

// Start a bulleted list with default formatting.
builder.ListFormat.ApplyBulletDefault();
builder.Writeln("Great performance");
builder.Writeln("High reliability");
builder.Writeln("Quality code and working");
builder.Writeln("Wide variety of features");
builder.Writeln("Easy to understand API");

// End the bulleted list.
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.ApplyDefaultBulletsAndNumbers.doc");

See Also

ListFormat Class | Aspose.Words Namespace | List | RemoveNumbers | ListLevelNumber


ListFormat.ApplyNumberDefault Method

Starts a new default numbered list and applies it to the paragraph.

[Visual Basic]
Public Sub ApplyNumberDefault()
[C#]
public void ApplyNumberDefault();

Remarks

This is a shortcut method that creates a new list using the default numbered template, applies it to the paragraph and selects the 1st list level.

Example

Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln("Aspose.Words allows:");
builder.Writeln();

// Start a numbered list with default formatting.
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Opening documents from different formats:");

// Go to second list level, add more text.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");

// Outdent to the first list level.
builder.ListFormat.ListOutdent();
builder.Writeln("Processing documents");
builder.Writeln("Saving documents in different formats:");

// Indent the list level again.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");
builder.Writeln("MHTML");
builder.Writeln("Plain text");

// Outdent the list level again.
builder.ListFormat.ListOutdent();
builder.Writeln("Doing many other things!");

// End the numbered list.
builder.ListFormat.RemoveNumbers();
builder.Writeln();

builder.Writeln("Aspose.Words main advantages are:");
builder.Writeln();

// Start a bulleted list with default formatting.
builder.ListFormat.ApplyBulletDefault();
builder.Writeln("Great performance");
builder.Writeln("High reliability");
builder.Writeln("Quality code and working");
builder.Writeln("Wide variety of features");
builder.Writeln("Easy to understand API");

// End the bulleted list.
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.ApplyDefaultBulletsAndNumbers.doc");

See Also

ListFormat Class | Aspose.Words Namespace | List | RemoveNumbers | ListLevelNumber


ListFormat.ListIndent Method

Increases the list level of the current paragraph by one level.

[Visual Basic]
Public Sub ListIndent()
[C#]
public void ListIndent();

Remarks

This method changes the list level and applies formatting properties of the new level.

In Word documents, lists may consist of up to nine levels. List formatting for each level specifies what bullet or number is used, left indent, space between the bullet and text etc.

Example

Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln("Aspose.Words allows:");
builder.Writeln();

// Start a numbered list with default formatting.
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Opening documents from different formats:");

// Go to second list level, add more text.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");

// Outdent to the first list level.
builder.ListFormat.ListOutdent();
builder.Writeln("Processing documents");
builder.Writeln("Saving documents in different formats:");

// Indent the list level again.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");
builder.Writeln("MHTML");
builder.Writeln("Plain text");

// Outdent the list level again.
builder.ListFormat.ListOutdent();
builder.Writeln("Doing many other things!");

// End the numbered list.
builder.ListFormat.RemoveNumbers();
builder.Writeln();

builder.Writeln("Aspose.Words main advantages are:");
builder.Writeln();

// Start a bulleted list with default formatting.
builder.ListFormat.ApplyBulletDefault();
builder.Writeln("Great performance");
builder.Writeln("High reliability");
builder.Writeln("Quality code and working");
builder.Writeln("Wide variety of features");
builder.Writeln("Easy to understand API");

// End the bulleted list.
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.ApplyDefaultBulletsAndNumbers.doc");

See Also

ListFormat Class | Aspose.Words Namespace


ListFormat.ListOutdent Method

Decreases the list level of the current paragraph by one level.

[Visual Basic]
Public Sub ListOutdent()
[C#]
public void ListOutdent();

Remarks

This method changes the list level and applies formatting properties of the new level.

In Word documents, lists may consist of up to nine levels. List formatting for each level specifies what bullet or number is used, left indent, space between the bullet and text etc.

Example

Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln("Aspose.Words allows:");
builder.Writeln();

// Start a numbered list with default formatting.
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Opening documents from different formats:");

// Go to second list level, add more text.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");

// Outdent to the first list level.
builder.ListFormat.ListOutdent();
builder.Writeln("Processing documents");
builder.Writeln("Saving documents in different formats:");

// Indent the list level again.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");
builder.Writeln("MHTML");
builder.Writeln("Plain text");

// Outdent the list level again.
builder.ListFormat.ListOutdent();
builder.Writeln("Doing many other things!");

// End the numbered list.
builder.ListFormat.RemoveNumbers();
builder.Writeln();

builder.Writeln("Aspose.Words main advantages are:");
builder.Writeln();

// Start a bulleted list with default formatting.
builder.ListFormat.ApplyBulletDefault();
builder.Writeln("Great performance");
builder.Writeln("High reliability");
builder.Writeln("Quality code and working");
builder.Writeln("Wide variety of features");
builder.Writeln("Easy to understand API");

// End the bulleted list.
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.ApplyDefaultBulletsAndNumbers.doc");

See Also

ListFormat Class | Aspose.Words Namespace


ListFormat.RemoveNumbers Method

Removes numbers or bullets from the current paragraph and sets list level to zero.

[Visual Basic]
Public Sub RemoveNumbers()
[C#]
public void RemoveNumbers();

Remarks

Calling this method is equivalent to setting the List property to null.

Example

Removes bullets and numbering from all paragraphs in the main text of a section.

[C#]

Body body = doc.FirstSection.Body;

foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
    paragraph.ListFormat.RemoveNumbers();
Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.
[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln("Aspose.Words allows:");
builder.Writeln();

// Start a numbered list with default formatting.
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Opening documents from different formats:");

// Go to second list level, add more text.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");

// Outdent to the first list level.
builder.ListFormat.ListOutdent();
builder.Writeln("Processing documents");
builder.Writeln("Saving documents in different formats:");

// Indent the list level again.
builder.ListFormat.ListIndent();
builder.Writeln("DOC");
builder.Writeln("PDF");
builder.Writeln("HTML");
builder.Writeln("MHTML");
builder.Writeln("Plain text");

// Outdent the list level again.
builder.ListFormat.ListOutdent();
builder.Writeln("Doing many other things!");

// End the numbered list.
builder.ListFormat.RemoveNumbers();
builder.Writeln();

builder.Writeln("Aspose.Words main advantages are:");
builder.Writeln();

// Start a bulleted list with default formatting.
builder.ListFormat.ApplyBulletDefault();
builder.Writeln("Great performance");
builder.Writeln("High reliability");
builder.Writeln("Quality code and working");
builder.Writeln("Wide variety of features");
builder.Writeln("Easy to understand API");

// End the bulleted list.
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.ApplyDefaultBulletsAndNumbers.doc");

See Also

ListFormat Class | Aspose.Words Namespace


LoadFormat Enumeration

Indicates the format of the document that is to be loaded.

[Visual Basic]
Public Enum LoadFormat
[C#]
public enum LoadFormat

Example

Explicitly loads a document as HTML without automatic file format detection.

[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

Document doc = new Document(MyDir + "Document.LoadFormat.html", loadOptions);
Shows how to open older binary DOC format for Word6.0/Word95 documents
[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LoadFormat = Aspose.Words.LoadFormat.DocPreWord60;

Document doc = new Document(MyDir + "Document.PreWord60.doc", loadOptions);
Shows how to insert the HTML contents from a web page into a new document.
[C#]

// The url of the page to load
String url = "http://www.aspose.com/";

// Create a WebClient object to easily extract the HTML from the page.
WebClient client = new WebClient();
String pageSource = client.DownloadString(url);
client.Dispose();

// Get the HTML as bytes for loading into a stream.
Encoding encoding = client.Encoding;
byte[] pageBytes = encoding.GetBytes(pageSource);

// Load the HTML into a stream.
using (MemoryStream stream = new MemoryStream(pageBytes))
{
    // The baseUri property should be set to ensure any relative img paths are retrieved correctly.
    LoadOptions options = new LoadOptions(Aspose.Words.LoadFormat.Html, "", url);

    // Load the HTML document from stream and pass the LoadOptions object.
    Document doc = new Document(stream, options);

    // Save the document to disk.
    // The extension of the filename can be changed to save the document into other formats. e.g PDF, DOCX, ODT, RTF.
    doc.Save(ArtifactsDir + "Document.HtmlPageFromWebpage.doc");
}

Members

Member Name | Description | Value
Auto | Instructs Aspose.Words to recognize the format automatically. | 0
Doc | Microsoft Word 97 - 2007 Document. | 10
Dot | Microsoft Word 97 - 2007 Template. | 11
DocPreWord60 | The document is in the Word 6 or Word 95 format. Aspose.Words does not currently support loading such documents. | 12
Docx | Office Open XML WordprocessingML Document (macro-free). | 20
Docm | Office Open XML WordprocessingML Macro-Enabled Document. | 21
Dotx | Office Open XML WordprocessingML Template (macro-free). | 22
Dotm | Office Open XML WordprocessingML Macro-Enabled Template. | 23
FlatOpc | Office Open XML WordprocessingML stored in a flat XML file instead of a ZIP package. | 24
FlatOpcMacroEnabled | Office Open XML WordprocessingML Macro-Enabled Document stored in a flat XML file instead of a ZIP package. | 25
FlatOpcTemplate | Office Open XML WordprocessingML Template (macro-free) stored in a flat XML file instead of a ZIP package. | 26
FlatOpcTemplateMacroEnabled | Office Open XML WordprocessingML Macro-Enabled Template stored in a flat XML file instead of a ZIP package. | 27
Rtf | RTF format. | 30
WordML | Microsoft Word 2003 WordprocessingML format. | 31
Html | HTML format. | 50
Mhtml | MHTML (Web archive) format. | 51
Mobi | MOBI is an eBook format used by the MobiPocket Reader and Amazon Kindle Readers. | 52
Odt | ODF Text Document. | 60
Ott | ODF Text Document Template. | 61
Text | Plain Text. | 62
Markdown | Markdown text document. | 63
Unknown | Unrecognized format, cannot be loaded by Aspose.Words. | 255

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


LoadOptions Class

Allows to specify additional options (such as password or base URI) when loading a document into a Document object.

For a list of all members of this type, see LoadOptions Members.

System.Object
Aspose.Words.LoadOptions
Aspose.Words.HtmlLoadOptions
Aspose.Words.RtfLoadOptions
Aspose.Words.TxtLoadOptions

[Visual Basic]
Public Class LoadOptions
[C#]
public class LoadOptions

Example

Loads a Microsoft Word document encrypted with a password.

[C#]

Document doc = new Document(MyDir + "Document.LoadEncrypted.doc", new LoadOptions("qwerty"));

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

LoadOptions Members | Aspose.Words Namespace


LoadOptions Members

LoadOptions overview

Public Static (Shared) Properties

AnnotationsAtBlockLevelAsDefault Gets or sets a default value for the AnnotationsAtBlockLevel property.

Public Instance Constructors

LoadOptions Overloaded. Initializes a new instance of the LoadOptions class.

Public Instance Properties

AnnotationsAtBlockLevel | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
Encoding | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings | Allows to specify document font settings.
LanguagePreferences | Gets language preferences that will be used when document is loading.
LoadFormat | Specifies the format of the document to be loaded. Default is Auto.
MswVersion | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreserveIncludePictureField | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
ResourceLoadingCallback | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
UpdateDirtyFields | Specifies whether to update the fields with the dirty attribute.
WarningCallback | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

LoadOptions Class | Aspose.Words Namespace


LoadOptions Constructor

Initializes a new instance of this class with default values.

Overload List

Initializes a new instance of this class with default values.

public LoadOptions();

A shortcut to initialize a new instance of this class with properties set to the specified values.

public LoadOptions(LoadFormat,string,string);

A shortcut to initialize a new instance of this class with the specified password to load an encrypted document.

public LoadOptions(string);

See Also

LoadOptions Class | Aspose.Words Namespace


LoadOptions Constructor ()

Initializes a new instance of this class with default values.

[Visual Basic]
Overloads Public Sub New()
[C#]
public LoadOptions();

Example

Opens an HTML document with images from a stream using a base URI.

[C#]

Document doc = new Document();
// We are opening this HTML file:
//    <html>
//    <body>
//    <p>Simple file.</p>
//    <p><img src="Aspose.Words.gif" width="80" height="60"></p>
//    </body>
//    </html>
String fileName = MyDir + "Document.OpenFromStreamWithBaseUri.html";
// Open the stream.
using (Stream stream = File.OpenRead(fileName))
{
    // Open the document. Note the Document constructor detects HTML format automatically.
    // Pass the URI of the base folder so any images with relative URIs in the HTML document can be found.
    LoadOptions loadOptions = new LoadOptions();
    loadOptions.BaseUri = MyDir;

    doc = new Document(stream, loadOptions);
}

// Save in the DOC format.
doc.Save(ArtifactsDir + "Document.OpenFromStreamWithBaseUri.doc");

See Also

LoadOptions Class | Aspose.Words Namespace | LoadOptions Constructor Overload List


LoadOptions Constructor (String)

A shortcut to initialize a new instance of this class with the specified password to load an encrypted document.

[Visual Basic]
Overloads Public Sub New( _
ByVal password As String _
)
[C#]
public LoadOptions(
string password
);

Parameters

password
The password to open an encrypted document. Can be null or empty string.

Example

Loads a Microsoft Word document encrypted with a password.

[C#]

Document doc = new Document(MyDir + "Document.LoadEncrypted.doc", new LoadOptions("qwerty"));

See Also

LoadOptions Class | Aspose.Words Namespace | LoadOptions Constructor Overload List


LoadOptions Constructor (LoadFormat, String, String)

A shortcut to initialize a new instance of this class with properties set to the specified values.

[Visual Basic]
Overloads Public Sub New( _
ByVal loadFormat As LoadFormat, _
ByVal password As String, _
ByVal baseUri As String _
)
[C#]
public LoadOptions(
LoadFormat loadFormat,
string password,
string baseUri
);

Parameters

loadFormat
The format of the document to be loaded.
password
The password to open an encrypted document. Can be null or empty string.
baseUri
The string that will be used to resolve relative URIs to absolute. Can be null or empty string.

Example

Shows how to insert the HTML contents from a web page into a new document.

[C#]

// The url of the page to load
String url = "http://www.aspose.com/";

// Create a WebClient object to easily extract the HTML from the page.
WebClient client = new WebClient();
String pageSource = client.DownloadString(url);
client.Dispose();

// Get the HTML as bytes for loading into a stream.
Encoding encoding = client.Encoding;
byte[] pageBytes = encoding.GetBytes(pageSource);

// Load the HTML into a stream.
using (MemoryStream stream = new MemoryStream(pageBytes))
{
    // The baseUri property should be set to ensure any relative img paths are retrieved correctly.
    LoadOptions options = new LoadOptions(Aspose.Words.LoadFormat.Html, "", url);

    // Load the HTML document from stream and pass the LoadOptions object.
    Document doc = new Document(stream, options);

    // Save the document to disk.
    // The extension of the filename can be changed to save the document into other formats. e.g PDF, DOCX, ODT, RTF.
    doc.Save(ArtifactsDir + "Document.HtmlPageFromWebpage.doc");
}

See Also

LoadOptions Class | Aspose.Words Namespace | LoadOptions Constructor Overload List


LoadOptions Properties

The properties of the LoadOptions class are listed below. For a complete list of LoadOptions class members, see the LoadOptions Members topic.

Public Static (Shared) Properties

AnnotationsAtBlockLevelAsDefault Gets or sets a default value for the AnnotationsAtBlockLevel property.

Public Instance Properties

AnnotationsAtBlockLevel | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
Encoding | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings | Allows to specify document font settings.
LanguagePreferences | Gets language preferences that will be used when document is loading.
LoadFormat | Specifies the format of the document to be loaded. Default is Auto.
MswVersion | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreserveIncludePictureField | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
ResourceLoadingCallback | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
UpdateDirtyFields | Specifies whether to update the fields with the dirty attribute.
WarningCallback | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

LoadOptions Class | Aspose.Words Namespace


AnnotationsAtBlockLevel Property

Aspose.Words

LoadOptions.AnnotationsAtBlockLevel Property

Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.

[Visual Basic]
Public Property AnnotationsAtBlockLevel As Boolean
[C#]
public bool AnnotationsAtBlockLevel {get; set;}

Remarks

Currently only bookmarks are affected by this option.

Example

Shows how to place bookmark nodes on the block, cell and row levels.

[C#]

// Any LoadOptions instances we create will have a default AnnotationsAtBlockLevel value equal to this
LoadOptions.AnnotationsAtBlockLevelAsDefault = false;

LoadOptions loadOptions = new LoadOptions();
Assert.AreEqual(loadOptions.AnnotationsAtBlockLevel, LoadOptions.AnnotationsAtBlockLevelAsDefault);

// If we want to work with annotations that transcend structures like tables, we will need to set this to true
loadOptions.AnnotationsAtBlockLevel = true;

// Open a document with a structured document tag and get that tag
Document doc = new Document(MyDir + "Document.AnnotationsAtBlockLevel.docx", loadOptions);
DocumentBuilder builder = new DocumentBuilder(doc);

StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChildNodes(NodeType.StructuredDocumentTag, true)[1];

// Insert a bookmark and make it envelop our tag
BookmarkStart start = builder.StartBookmark("MyBookmark");
BookmarkEnd end = builder.EndBookmark("MyBookmark");

sdt.ParentNode.InsertBefore(start, sdt);
sdt.ParentNode.InsertAfter(end, sdt);

doc.Save(ArtifactsDir + "Document.AnnotationsAtBlockLevel.docx", SaveFormat.Docx);

See Also

LoadOptions Class | Aspose.Words Namespace


AnnotationsAtBlockLevelAsDefault Property

Aspose.Words

LoadOptions.AnnotationsAtBlockLevelAsDefault Property

Gets or sets a default value for the AnnotationsAtBlockLevel property.

[Visual Basic]
Public Shared Property AnnotationsAtBlockLevelAsDefault As Boolean
[C#]
public static bool AnnotationsAtBlockLevelAsDefault {get; set;}

Remarks

Allows defining necessary behavior when an instance of LoadOptions is not specified on opening a document.

Example

Shows how to place bookmark nodes on the block, cell and row levels.

[C#]

// Any LoadOptions instances we create will have a default AnnotationsAtBlockLevel value equal to this
LoadOptions.AnnotationsAtBlockLevelAsDefault = false;

LoadOptions loadOptions = new LoadOptions();
Assert.AreEqual(loadOptions.AnnotationsAtBlockLevel, LoadOptions.AnnotationsAtBlockLevelAsDefault);

// If we want to work with annotations that transcend structures like tables, we will need to set this to true
loadOptions.AnnotationsAtBlockLevel = true;

// Open a document with a structured document tag and get that tag
Document doc = new Document(MyDir + "Document.AnnotationsAtBlockLevel.docx", loadOptions);
DocumentBuilder builder = new DocumentBuilder(doc);

StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChildNodes(NodeType.StructuredDocumentTag, true)[1];

// Insert a bookmark and make it envelop our tag
BookmarkStart start = builder.StartBookmark("MyBookmark");
BookmarkEnd end = builder.EndBookmark("MyBookmark");

sdt.ParentNode.InsertBefore(start, sdt);
sdt.ParentNode.InsertAfter(end, sdt);

doc.Save(ArtifactsDir + "Document.AnnotationsAtBlockLevel.docx", SaveFormat.Docx);

See Also

LoadOptions Class | Aspose.Words Namespace


BaseUri Property

Aspose.Words

LoadOptions.BaseUri Property

Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.

[Visual Basic]
Public Property BaseUri As String
[C#]
public string BaseUri {get; set;}

Remarks

This property is used to resolve relative URIs into absolute in the following cases:

  1. When loading an HTML document from a stream and the document contains images with relative URIs and does not have a base URI specified in the BASE HTML element.
  2. When saving a document to PDF and other formats, to retrieve images linked using relative URIs so the images can be saved into the output document.

Example

Opens an HTML document with images from a stream using a base URI.

[C#]

Document doc = new Document();
// We are opening this HTML file:
//    <html>
//    <body>
//    <p>Simple file.</p>
//    <p><img src="Aspose.Words.gif" width="80" height="60"></p>
//    </body>
//    </html>
String fileName = MyDir + "Document.OpenFromStreamWithBaseUri.html";
// Open the stream.
using (Stream stream = File.OpenRead(fileName))
{
    // Open the document. Note the Document constructor detects HTML format automatically.
    // Pass the URI of the base folder so any images with relative URIs in the HTML document can be found.
    LoadOptions loadOptions = new LoadOptions();
    loadOptions.BaseUri = MyDir;

    doc = new Document(stream, loadOptions);
}

// Save in the DOC format.
doc.Save(ArtifactsDir + "Document.OpenFromStreamWithBaseUri.doc");

See Also

LoadOptions Class | Aspose.Words Namespace


ConvertShapeToOfficeMath Property

Aspose.Words

LoadOptions.ConvertShapeToOfficeMath Property

Gets or sets whether to convert shapes with EquationXML to Office Math objects.

[Visual Basic]
Public Property ConvertShapeToOfficeMath As Boolean
[C#]
public bool ConvertShapeToOfficeMath {get; set;}

Example

Shows how to convert shapes with EquationXML to Office Math objects.

[C#]

LoadOptions loadOptions = new LoadOptions { ConvertShapeToOfficeMath = false };

// Specify load option to convert math shapes to office math objects on loading stage.
Document doc = new Document(MyDir + "Document.ConvertShapeToOfficeMath.docx", loadOptions);
doc.Save(ArtifactsDir + "Document.ConvertShapeToOfficeMath.docx", SaveFormat.Docx);

See Also

LoadOptions Class | Aspose.Words Namespace


Encoding Property

Aspose.Words

LoadOptions.Encoding Property

Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.

[Visual Basic]
Public Property Encoding As Encoding
[C#]
public Encoding Encoding {get; set;}

Remarks

This property is used only when loading HTML or TXT documents.

If encoding is not specified in HTML/TXT and this property is null, then the system will try to automatically detect the encoding.

Example

Shows how to set the encoding with which to open a document.

[C#]

// Get the file format info of a file in our local file system
FileFormatInfo fileFormatInfo = FileFormatUtil.DetectFileFormat(MyDir + "EncodedInUTF-7.txt");

// One of the aspects of a document that the FileFormatUtil can pick up is the text encoding
// This automatically takes place every time we open a document programmatically
// Occasionally, due to the text content in the document as well as the lack of an encoding declaration,
// the encoding of a document may be ambiguous
// In this case, while we know that our document is in UTF-7, the file encoding detector doesn't
Assert.AreNotEqual(Encoding.UTF7, fileFormatInfo.Encoding);

// If we open the document normally, the wrong encoding will be applied,
// and the content of the document will not be represented correctly
Document doc = new Document(MyDir + "EncodedInUTF-7.txt");
Assert.AreEqual("Hello world+ACE-\r\n\r\n", doc.ToString(SaveFormat.Text));

// In these cases we can set the Encoding attribute in a LoadOptions object
// to override the automatically chosen encoding with the one we know to be correct
LoadOptions loadOptions = new LoadOptions { Encoding = Encoding.UTF7 };
doc = new Document(MyDir + "EncodedInUTF-7.txt", loadOptions);

// This will give us the correct text
Assert.AreEqual("Hello world!\r\n\r\n", doc.ToString(SaveFormat.Text));

See Also

LoadOptions Class | Aspose.Words Namespace


FontSettings Property

Aspose.Words

LoadOptions.FontSettings Property

Allows to specify document font settings.

[Visual Basic]
Public Property FontSettings As FontSettings
[C#]
public FontSettings FontSettings {get; set;}

Remarks

When loading some formats, Aspose.Words may require to resolve the fonts. For example, when loading HTML documents Aspose.Words may resolve the fonts to perform font fallback.

If set to null, default static font settings DefaultInstance will be used.

The default value is null.

Example

Shows how to resolve fonts before loading HTML and SVG documents.

[C#]

FontSettings fontSettings = new FontSettings();
TableSubstitutionRule substitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
// If "HaettenSchweiler" is not installed on the local machine,
// it is still considered available, because it is substituted with "Comic Sans MS"
substitutionRule.AddSubstitutes("HaettenSchweiler", new string[] { "Comic Sans MS" });

LoadOptions loadOptions = new LoadOptions();
loadOptions.FontSettings = fontSettings;
// The same for SVG document
Document doc = new Document(MyDir + "Document.LoadFormat.html", loadOptions);
Shows how to set font settings and apply them during the loading of a document.
[C#]

// Create a FontSettings object that will substitute the "Times New Roman" font with the font "Arvo" from our "MyFonts" folder
FontSettings fontSettings = new FontSettings();
fontSettings.SetFontsFolder(MyDir + @"MyFonts\", false);
fontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Times New Roman", "Arvo");

// Set that FontSettings object as a member of a newly created LoadOptions object
LoadOptions loadOptions = new LoadOptions { FontSettings = fontSettings };

// We can now open a document while also passing the LoadOptions object into the constructor so the font substitution occurs upon loading
Document doc = new Document(MyDir + "Document.docx", loadOptions);

// The effects of our font settings can be observed after rendering
doc.Save(ArtifactsDir + "Document.LoadOptionsFontSettings.pdf");

See Also

LoadOptions Class | Aspose.Words Namespace


LanguagePreferences Property

Aspose.Words

LoadOptions.LanguagePreferences Property

Gets language preferences that will be used when document is loading.

[Visual Basic]
Public ReadOnly Property LanguagePreferences As LanguagePreferences
[C#]
public LanguagePreferences LanguagePreferences {get;}

Example

Shows how to set up language preferences that will be used when document is loading

[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LanguagePreferences.AddEditingLanguage(EditingLanguage.Japanese);

Document doc = new Document(MyDir + "Document.EditingLanguage.docx", loadOptions);

int localeIdFarEast = doc.Styles.DefaultFont.LocaleIdFarEast;
if (localeIdFarEast == (int)EditingLanguage.Japanese)
    Console.WriteLine("The document either has no any FarEast language set in defaults or it was set to Japanese originally.");
else
    Console.WriteLine("The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");

See Also

LoadOptions Class | Aspose.Words Namespace


LoadFormat Property

Aspose.Words

LoadOptions.LoadFormat Property

Specifies the format of the document to be loaded. Default is Auto.

[Visual Basic]
Public Property LoadFormat As LoadFormat
[C#]
public LoadFormat LoadFormat {get; set;}

Remarks

It is recommended that you specify the Auto value and let Aspose.Words detect the file format automatically. If you know the format of the document you are about to load, you can specify the format explicitly and this will slightly reduce the loading time by the overhead associated with auto detecting the format. If you specify an explicit load format and it will turn out to be wrong, the auto detection will be invoked and a second attempt to load the file will be made.

Example

Explicitly loads a document as HTML without automatic file format detection.

[C#]

LoadOptions loadOptions = new LoadOptions();
loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html;

Document doc = new Document(MyDir + "Document.LoadFormat.html", loadOptions);

See Also

LoadOptions Class | Aspose.Words Namespace


MswVersion Property

Aspose.Words

LoadOptions.MswVersion Property

Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007

[Visual Basic]
Public Property MswVersion As MsWordVersion
[C#]
public MsWordVersion MswVersion {get; set;}

Remarks

Different Word versions may handle certain aspects of document content and formatting slightly differently during the loading process, which may result in minor differences in Document Object Model.

Example

Shows how to emulate the loading procedure of a specific Microsoft Word version during document loading.

[C#]

// Create a new LoadOptions object, which will load documents according to MS Word 2007 specification by default
LoadOptions loadOptions = new LoadOptions();
Assert.AreEqual(MsWordVersion.Word2007, loadOptions.MswVersion);

// This document is missing the default paragraph format style,
// so when it is opened with either Microsoft Word or Aspose Words, that default style will be regenerated,
// and will show up in the Styles collection, with values according to Microsoft Word 2007 specifications
Document doc = new Document(MyDir + "Document.docx", loadOptions);
Assert.AreEqual(13.8, doc.Styles.DefaultParagraphFormat.LineSpacing, 0.005f);

// We can change the loading version like this, to Microsoft Word 2016
loadOptions.MswVersion = MsWordVersion.Word2016;

// The generated default style now has a different spacing, which will impact the appearance of our document
doc = new Document(MyDir + "Document.docx", loadOptions);
Assert.AreEqual(12.95, doc.Styles.DefaultParagraphFormat.LineSpacing, 0.005f);

See Also

LoadOptions Class | Aspose.Words Namespace


Password Property

Aspose.Words

LoadOptions.Password Property

Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.

[Visual Basic]
Public Property Password As String
[C#]
public string Password {get; set;}

Remarks

You need to know the password to open an encrypted document. If the document is not encrypted, set this to null or empty string.

Example

Shows how to sign encrypted document file.

[C#]

string outputFileName = ArtifactsDir + "Document.Encrypted.docx";

Document doc = new Document(MyDir + "Document.Encrypted.docx", new LoadOptions("docPassword"));

// Create certificate holder from a file.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions
{
    Comments = "Comment",
    SignTime = DateTime.Now,
    DecryptionPassword = "docPassword"
};

// Digitally sign encrypted with "docPassword" document in the specified path.
DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, certificateHolder, signOptions);

See Also

LoadOptions Class | Aspose.Words Namespace


PreserveIncludePictureField Property

Aspose.Words

LoadOptions.PreserveIncludePictureField Property

Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.

[Visual Basic]
Public Property PreserveIncludePictureField As Boolean
[C#]
public bool PreserveIncludePictureField {get; set;}

Remarks

By default, the INCLUDEPICTURE field is converted into a shape object. You can override that if you need the field to be preserved, for example, if you wish to update it programmatically. Note however that this approach is not common for Aspose.Words. Use it on your own risk.

One of the possible use cases may be using a MERGEFIELD as a child field to dynamically change the source path of the picture. In this case you need the INCLUDEPICTURE to be preserved in the model.

Example

Shows a way to update a field ignoring the MERGEFORMAT switch

[C#]

LoadOptions loadOptions = new LoadOptions { PreserveIncludePictureField = true };

Document doc = new Document(MyDir + "Field.UpdateFieldIgnoringMergeFormat.docx", loadOptions);

foreach (Field field in doc.Range.Fields)
{
    if (field.Type.Equals(FieldType.FieldIncludePicture))
    {
        FieldIncludePicture includePicture = (FieldIncludePicture)field;

        includePicture.SourceFullName = MyDir + "Images/dotnet-logo.png";
        includePicture.Update(true);
    }
}

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.UpdateFieldIgnoringMergeFormat.docx");

See Also

LoadOptions Class | Aspose.Words Namespace


ResourceLoadingCallback Property

Aspose.Words

LoadOptions.ResourceLoadingCallback Property

Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.

[Visual Basic]
Public Property ResourceLoadingCallback As IResourceLoadingCallback
[C#]
public IResourceLoadingCallback ResourceLoadingCallback {get; set;}

Example

Shows how to handle external resources in Html documents during loading.

[C#]

public void LoadOptionsCallback()
{
    // Create a new LoadOptions object and set its ResourceLoadingCallback attribute
    // as an instance of our IResourceLoadingCallback implementation
    LoadOptions loadOptions = new LoadOptions { ResourceLoadingCallback = new HtmlLinkedResourceLoadingCallback() };

    // When we open an Html document, external resources such as references to CSS stylesheet files and external images
    // will be handled in a custom manner by the loading callback as the document is loaded
    Document doc = new Document(MyDir + "ResourcesForCallback.html", loadOptions);
    doc.Save(ArtifactsDir + "Document.LoadOptionsCallback.pdf");
}

/// <summary>
/// Resource loading callback that, upon encountering external resources,
/// acknowledges CSS style sheets and replaces all images with a substitute.
/// </summary>
private class HtmlLinkedResourceLoadingCallback : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        switch (args.ResourceType)
        {
            case ResourceType.CssStyleSheet:
                Console.WriteLine($"External CSS Stylesheet found upon loading: {args.OriginalUri}");
                return ResourceLoadingAction.Default;
            case ResourceType.Image:
                Console.WriteLine($"External Image found upon loading: {args.OriginalUri}");

                string newImageFilename =  "Images\\Aspose.Words.gif";
                Console.WriteLine($"\tImage will be substituted with: {newImageFilename}");

                System.Drawing.Image newImage = System.Drawing.Image.FromFile(MyDir + newImageFilename);

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;

        }
        return ResourceLoadingAction.Default;
    }
}

See Also

LoadOptions Class | Aspose.Words Namespace


UpdateDirtyFields Property

Aspose.Words

LoadOptions.UpdateDirtyFields Property

Specifies whether to update the fields with the dirty attribute.

[Visual Basic]
Public Property UpdateDirtyFields As Boolean
[C#]
public bool UpdateDirtyFields {get; set;}

Example

Shows how to use special property for updating field result

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Field fieldToc = builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
fieldToc.IsDirty = true;

MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Docx);

Assert.IsTrue(doc.Range.Fields[0].IsDirty);

LoadOptions loadOptions = new LoadOptions { UpdateDirtyFields = false };
doc = new Document(stream, loadOptions);

See Also

LoadOptions Class | Aspose.Words Namespace


WarningCallback Property

Aspose.Words

LoadOptions.WarningCallback Property

Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

[Visual Basic]
Public Property WarningCallback As IWarningCallback
[C#]
public IWarningCallback WarningCallback {get; set;}

Example

Shows how to print warnings that occur during document loading.

[C#]

public void LoadOptionsWarningCallback()
{
    // Create a new LoadOptions object and set its WarningCallback attribute as an instance of our IWarningCallback implementation
    LoadOptions loadOptions = new LoadOptions { WarningCallback = new DocumentLoadingWarningCallback() };

    // Minor warnings that might not prevent the effective loading of the document will now be printed
    Document doc = new Document(MyDir + "Document.docx", loadOptions);
}

/// <summary>
/// IWarningCallback that prints warnings and their details as they arise during document loading.
/// </summary>
private class DocumentLoadingWarningCallback : IWarningCallback
{
    public void Warning(WarningInfo info)
    {
        Console.WriteLine($"WARNING: {info.WarningType}, source: {info.Source}");
        Console.WriteLine($"\tDescription: {info.Description}");
    }
}

See Also

LoadOptions Class | Aspose.Words Namespace


Metered Class

Provides methods to set metered key.

For a list of all members of this type, see Metered Members.

System.Object
Aspose.Words.Metered

[Visual Basic]
Public Class Metered
[C#]
public class Metered

Example

In this example, an attempt will be made to set metered public and private key

[C#]

Metered matered = new Metered();
matered.SetMeteredKey("PublicKey", "PrivateKey");

[Visual Basic]

Dim matered As Metered = New Metered
matered.SetMeteredKey("PublicKey", "PrivateKey")

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Metered Members | Aspose.Words Namespace


Metered Members

Metered overview

Public Static (Shared) Methods

GetConsumptionCredit | Gets consumption credit
GetConsumptionQuantity | Gets consumption file size

Public Instance Constructors

Metered Constructor Initializes a new instance of this class.

Public Instance Methods

SetMeteredKey Sets metered public and private key

See Also

Metered Class | Aspose.Words Namespace


Metered Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New()
[C#]
public Metered();

See Also

Metered Class | Aspose.Words Namespace


Metered Methods

The methods of the Metered class are listed below. For a complete list of Metered class members, see the Metered Members topic.

Public Static (Shared) Methods

GetConsumptionCredit | Gets consumption credit
GetConsumptionQuantity | Gets consumption file size

Public Instance Methods

SetMeteredKey Sets metered public and private key

See Also

Metered Class | Aspose.Words Namespace


Metered.GetConsumptionCredit Method

Gets consumption credit

[Visual Basic]
Public Shared Function GetConsumptionCredit() As Decimal
[C#]
public static decimal GetConsumptionCredit();

Return Value

consumption quantity

See Also

Metered Class | Aspose.Words Namespace


Metered.GetConsumptionQuantity Method

Gets consumption file size

[Visual Basic]
Public Shared Function GetConsumptionQuantity() As Decimal
[C#]
public static decimal GetConsumptionQuantity();

Return Value

consumption quantity

See Also

Metered Class | Aspose.Words Namespace


Metered.SetMeteredKey Method

Sets metered public and private key

[Visual Basic]
Public Sub SetMeteredKey( _
ByVal publicKey As String, _
ByVal privateKey As String _
)
[C#]
public void SetMeteredKey(
string publicKey,
string privateKey
);

Parameters

publicKey
public key
privateKey
private key

See Also

Metered Class | Aspose.Words Namespace


Node Class

Base class for all nodes of a Word document.

For a list of all members of this type, see Node Members.

System.Object
Aspose.Words.Node
Derived types

[Visual Basic]
MustInherit Public Class Node
[C#]
public abstract class Node

Remarks

A document is represented as a tree of nodes, similar to DOM or XmlDocument.

For more info see the Composite design pattern.

The Node class:

  • Defines the child node interface.
  • Defines the interface for visiting nodes.
  • Provides default cloning capability.
  • Implements parent node and owner document mechanisms.
  • Implements access to sibling nodes.

Example

Shows how to extract a specific child node from a CompositeNode by using the GetChild method and passing the NodeType and index.

[C#]

Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);
Shows how to clone composite nodes with and without their child nodes.
[C#]

// Create a new empty document.
Document doc = new Document();

// Add some text to the first paragraph
Paragraph para = doc.FirstSection.Body.FirstParagraph;
para.AppendChild(new Run(doc, "Some text"));

// Clone the paragraph and the child nodes.
Node cloneWithChildren = para.Clone(true);
// Only clone the paragraph and no child nodes.
Node cloneWithoutChildren = para.Clone(false);
Shows how to remove all nodes of a specific type from a composite node. In this example we remove tables from a section body.
[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Select the first child node in the body.
Node curNode = body.FirstChild;

while (curNode != null)
{
    // Save the pointer to the next sibling node because if the current
    // node is removed from the parent in the next step, we will have
    // no way of finding the next node to continue the loop.
    Node nextNode = curNode.NextSibling;

    // A section body can contain Paragraph and Table nodes.
    // If the node is a Table, remove it from the parent.
    if (curNode.NodeType.Equals(NodeType.Table))
        curNode.Remove();

    // Continue going through child nodes until null (no more siblings) is reached.
    curNode = nextNode;
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Node Members | Aspose.Words Namespace


Node Members

Node overview

Public Static (Shared) Methods

NodeTypeToString A utility method that converts a node type enum value into a user friendly string.

Public Instance Properties

Document | Gets the document to which this node belongs.
IsComposite | Returns true if this node can contain other nodes.
NextSibling | Gets the node immediately following this node.
NodeType | Gets the type of this node.
ParentNode | Gets the immediate parent of this node.
PreviousSibling | Gets the node immediately preceding this node.
Range | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone |
GetAncestor | Overloaded. Gets the first ancestor of the specified object type.
GetText | Gets the text of this node and of all its children.
NextPreOrder | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder | Gets the previous node according to the pre-order tree traversal algorithm.
Remove | Removes itself from the parent.
ToString | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Node Class | Aspose.Words Namespace


Node Properties

The properties of the Node class are listed below. For a complete list of Node class members, see the Node Members topic.

Public Instance Properties

Document | Gets the document to which this node belongs.
IsComposite | Returns true if this node can contain other nodes.
NextSibling | Gets the node immediately following this node.
NodeType | Gets the type of this node.
ParentNode | Gets the immediate parent of this node.
PreviousSibling | Gets the node immediately preceding this node.
Range | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

Node Class | Aspose.Words Namespace


Document Property

Aspose.Words

Node.Document Property

Gets the document to which this node belongs.

[Visual Basic]
Public ReadOnly Property Document As DocumentBase
[C#]
public DocumentBase Document {get;}

Remarks

The node always belongs to a document even if it has just been created and not yet added to the tree, or if it has been removed from the tree.

Example

Shows that when you create any node, it requires a document that will own the node.

[C#]

// Open a file from disk.
Document doc = new Document();

// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);

// The new paragraph node does not yet have a parent.
Console.WriteLine("Paragraph has no parent node: " + (para.ParentNode == null));

// But the paragraph node knows its document.
Console.WriteLine("Both nodes' documents are the same: " + (para.Document == doc));

// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.ParagraphFormat.StyleName = "Heading 1";

// Now add the paragraph to the main text of the first section.
doc.FirstSection.Body.AppendChild(para);

// The paragraph node is now a child of the Body node.
Console.WriteLine("Paragraph has a parent node: " + (para.ParentNode != null));

See Also

Node Class | Aspose.Words Namespace


IsComposite Property

Aspose.Words

Node.IsComposite Property

Returns true if this node can contain other nodes.

[Visual Basic]
Overridable Public ReadOnly Property IsComposite As Boolean
[C#]
public virtual bool IsComposite {get;}

Property Value

This method returns false as Node cannot have child nodes.

Example

Shows how to efficiently visit all direct and indirect children of a composite node.

[C#]

public void RecurseAllNodes()
{
    // Open a document.
    Document doc = new Document(MyDir + "Node.RecurseAllNodes.doc");

    // Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc);
}

/// <summary>
/// A simple function that will walk through all children of a specified node recursively
/// and print the type of each node to the screen.
/// </summary>
public void TraverseAllNodes(CompositeNode parentNode)
{
    // This is the most efficient way to loop through immediate children of a node.
    for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
    {
        // Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType));

        // Recurse into the node if it is a composite node.
        if (childNode.IsComposite)
            TraverseAllNodes((CompositeNode) childNode);
    }
}

See Also

Node Class | Aspose.Words Namespace


NextSibling Property

Aspose.Words

Node.NextSibling Property

Gets the node immediately following this node.

[Visual Basic]
Public ReadOnly Property NextSibling As Node
[C#]
public Node NextSibling {get;}

Remarks

If there is no next node, a null is returned.

Example

Shows how to enumerate immediate child nodes of a composite node using NextSibling. In this example we enumerate all paragraphs of a section body.

[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Loop starting from the first child until we reach null.
for (Node node = body.FirstChild; node != null; node = node.NextSibling)
{
    // Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType));
}
Shows how to efficiently visit all direct and indirect children of a composite node.
[C#]

public void RecurseAllNodes()
{
    // Open a document.
    Document doc = new Document(MyDir + "Node.RecurseAllNodes.doc");

    // Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc);
}

/// <summary>
/// A simple function that will walk through all children of a specified node recursively
/// and print the type of each node to the screen.
/// </summary>
public void TraverseAllNodes(CompositeNode parentNode)
{
    // This is the most efficient way to loop through immediate children of a node.
    for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
    {
        // Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType));

        // Recurse into the node if it is a composite node.
        if (childNode.IsComposite)
            TraverseAllNodes((CompositeNode) childNode);
    }
}

See Also

Node Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Node.NodeType Property

Gets the type of this node.

[Visual Basic]
MustOverride Public ReadOnly Property NodeType As NodeType
[C#]
public abstract NodeType NodeType {get;}

Example

Shows how to enumerate immediate child nodes of a composite node using NextSibling. In this example we enumerate all paragraphs of a section body.

[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Loop starting from the first child until we reach null.
for (Node node = body.FirstChild; node != null; node = node.NextSibling)
{
    // Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType));
}
Shows how to remove all nodes of a specific type from a composite node. In this example we remove tables from a section body.
[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Select the first child node in the body.
Node curNode = body.FirstChild;

while (curNode != null)
{
    // Save the pointer to the next sibling node because if the current
    // node is removed from the parent in the next step, we will have
    // no way of finding the next node to continue the loop.
    Node nextNode = curNode.NextSibling;

    // A section body can contain Paragraph and Table nodes.
    // If the node is a Table, remove it from the parent.
    if (curNode.NodeType.Equals(NodeType.Table))
        curNode.Remove();

    // Continue going through child nodes until null (no more siblings) is reached.
    curNode = nextNode;
}
Shows how to retrieve the NodeType enumeration of nodes.
[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Node Class | Aspose.Words Namespace


ParentNode Property

Aspose.Words

Node.ParentNode Property

Gets the immediate parent of this node.

[Visual Basic]
Public ReadOnly Property ParentNode As CompositeNode
[C#]
public CompositeNode ParentNode {get;}

Remarks

If a node has just been created and not yet added to the tree, or if it has been removed from the tree, the parent is null.

Example

Shows how to access the parent node.

[C#]

// Create a new empty document. It has one section.
Document doc = new Document();

// The section is the first child node of the document.
Node section = doc.FirstChild;

// The section's parent node is the document.
Console.WriteLine("Section parent is the document: " + (doc == section.ParentNode));
Shows that when you create any node, it requires a document that will own the node.
[C#]

// Open a file from disk.
Document doc = new Document();

// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);

// The new paragraph node does not yet have a parent.
Console.WriteLine("Paragraph has no parent node: " + (para.ParentNode == null));

// But the paragraph node knows its document.
Console.WriteLine("Both nodes' documents are the same: " + (para.Document == doc));

// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.ParagraphFormat.StyleName = "Heading 1";

// Now add the paragraph to the main text of the first section.
doc.FirstSection.Body.AppendChild(para);

// The paragraph node is now a child of the Body node.
Console.WriteLine("Paragraph has a parent node: " + (para.ParentNode != null));

See Also

Node Class | Aspose.Words Namespace


PreviousSibling Property

Aspose.Words

Node.PreviousSibling Property

Gets the node immediately preceding this node.

[Visual Basic]
Public ReadOnly Property PreviousSibling As Node
[C#]
public Node PreviousSibling {get;}

Remarks

If there is no preceding node, a null is returned.

Example

Demonstrates use of methods of Node and CompositeNode to remove a section before the last section in the document.

[C#]

// Document is a CompositeNode and LastChild returns the last child node in the Document node.
// Since the Document can contain only Section nodes, the last child is the last section.
Node lastSection = doc.LastChild;

// Each node knows its next and previous sibling nodes.
// Previous sibling of a section is a section before the specified section.
// If the node is the first child, PreviousSibling will return null.
Node sectionBeforeLast = lastSection.PreviousSibling;

if (sectionBeforeLast != null)
    doc.RemoveChild(sectionBeforeLast);

See Also

Node Class | Aspose.Words Namespace


Range Property

Aspose.Words

Node.Range Property

Returns a Range object that represents the portion of a document that is contained in this node.

[Visual Basic]
Public ReadOnly Property Range As Range
[C#]
public Range Range {get;}

Example

Shows how to delete all characters of a range.

[C#]

// Open Word document.
Document doc = new Document(MyDir + "Range.DeleteSection.doc");

// The document contains two sections. Each section has a paragraph of text.
Console.WriteLine(doc.GetText());

// Delete the first section from the document.
doc.Sections[0].Range.Delete();

// Check the first section was deleted by looking at the text of the whole document again.
Console.WriteLine(doc.GetText());

See Also

Node Class | Aspose.Words Namespace


Node Methods

The methods of the Node class are listed below. For a complete list of Node class members, see the Node Members topic.

Public Static (Shared) Methods

NodeTypeToString A utility method that converts a node type enum value into a user friendly string.

Public Instance Methods

Accept | Accepts a visitor.
Clone |
GetAncestor | Overloaded. Gets the first ancestor of the specified object type.
GetText | Gets the text of this node and of all its children.
NextPreOrder | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder | Gets the previous node according to the pre-order tree traversal algorithm.
Remove | Removes itself from the parent.
ToString | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Node Class | Aspose.Words Namespace


Node.Accept Method

Accepts a visitor.

[Visual Basic]
MustOverride Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public abstract bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

Node Class | Aspose.Words Namespace


Node.Clone Method

[Visual Basic]
Public Function Clone( _
ByVal isCloneChildren As Boolean _
) As Node
[C#]
public Node Clone(
bool isCloneChildren
);

Example

Shows how to clone composite nodes with and without their child nodes.

[C#]

// Create a new empty document.
Document doc = new Document();

// Add some text to the first paragraph
Paragraph para = doc.FirstSection.Body.FirstParagraph;
para.AppendChild(new Run(doc, "Some text"));

// Clone the paragraph and the child nodes.
Node cloneWithChildren = para.Clone(true);
// Only clone the paragraph and no child nodes.
Node cloneWithoutChildren = para.Clone(false);

See Also

Node Class | Aspose.Words Namespace


GetAncestor Method

Aspose.Words

Node.GetAncestor Method

Gets the first ancestor of the specified NodeType.

Overload List

Gets the first ancestor of the specified NodeType.

public CompositeNode GetAncestor(NodeType);

Gets the first ancestor of the specified object type.

public CompositeNode GetAncestor(Type);

See Also

Node Class | Aspose.Words Namespace


Node.GetAncestor Method (NodeType)

Gets the first ancestor of the specified NodeType.

[Visual Basic]
Overloads Public Function GetAncestor( _
ByVal ancestorType As NodeType _
) As CompositeNode
[C#]
public CompositeNode GetAncestor(
NodeType ancestorType
);

Parameters

ancestorType
The node type of the ancestor to retrieve.

Return Value

The ancestor of the specified type or null if no ancestor of this type was found.

Example

Shows how to find out if a table contains another table or if the table itself is nested inside another table.

[C#]

Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true).OfType<Table>())
    {
        // First lets find if any cells in the table have tables themselves as children.
        int count = GetChildTableCount(table);
        Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

        // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
        int tableDepth = GetNestedDepthOfTable(table);

        if (tableDepth > 0)
            Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex,
                tableDepth);
        else
            Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);

        tableIndex++;
    }
}

/// <summary>
/// Calculates what level a table is nested inside other tables.
/// <returns>
/// An integer containing the level the table is nested at.
/// 0 = Table is not nested inside any other table
/// 1 = Table is nested within one parent table
/// 2 = Table is nested within two parent tables etc..</returns>
/// </summary>
private static int GetNestedDepthOfTable(Table table)
{
    int depth = 0;

    NodeType type = table.NodeType;
    // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Node parent = table.GetAncestor(type);

    while (parent != null)
    {
        // Every time we find a table a level up we increase the depth counter and then try to find an
        // ancestor of type table from the parent.
        depth++;
        parent = parent.GetAncestor(type);
    }

    return depth;
}

/// <summary>
/// Determines if a table contains any immediate child table within its cells.
/// Does not recursively traverse through those tables to check for further tables.
/// <returns>Returns true if at least one child cell contains a table.
/// Returns false if no cells in the table contains a table.</returns>
/// </summary>
private static int GetChildTableCount(Table table)
{
    int tableCount = 0;
    // Iterate through all child rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells.OfType<Cell>())
        {
            // Retrieve the collection of child tables of this cell
            TableCollection childTables = Cell.Tables;

            // If this cell has a table as a child then return true
            if (childTables.Count > 0)
                tableCount++;
        }
    }

    // No cell contains a table
    return tableCount;
}

See Also

Node Class | Aspose.Words Namespace | Node.GetAncestor Overload List


Node.GetAncestor Method (Type)

Gets the first ancestor of the specified object type.

[Visual Basic]
Overloads Public Function GetAncestor( _
ByVal ancestorType As Type _
) As CompositeNode
[C#]
public CompositeNode GetAncestor(
Type ancestorType
);

Parameters

ancestorType
The object type of the ancestor to retrieve.

Return Value

The ancestor of the specified type or null if no ancestor of this type was found.

Remarks

The ancestor type matches if it is equal to ancestorType or derived from ancestorType.

See Also

Node Class | Aspose.Words Namespace | Node.GetAncestor Overload List


Node.GetText Method

Gets the text of this node and of all its children.

[Visual Basic]
Overridable Public Function GetText() As String
[C#]
public virtual string GetText();

Remarks

The returned string includes all control and special characters as described in ControlChar.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Node Class | Aspose.Words Namespace


Node.NextPreOrder Method

Gets next node according to the pre-order tree traversal algorithm.

[Visual Basic]
Public Function NextPreOrder( _
ByVal rootNode As Node _
) As Node
[C#]
public Node NextPreOrder(
Node rootNode
);

Parameters

rootNode
The top node (limit) of traversal.

Return Value

Next node in pre-order order. Null if reached the rootNode.

Example

Shows how to delete all images from a document using pre-order tree traversal.

[C#]

Node curNode = doc;
while (curNode != null)
{
    Node nextNode = curNode.NextPreOrder(doc);

    if (curNode.NodeType.Equals(NodeType.Shape))
    {
        Shape shape = (Shape) curNode;

        // Several shape types can have an image including image shapes and OLE objects.
        if (shape.HasImage)
            shape.Remove();
    }

    curNode = nextNode;
}

See Also

Node Class | Aspose.Words Namespace


Node.NodeTypeToString Method

A utility method that converts a node type enum value into a user friendly string.

[Visual Basic]
Public Shared Function NodeTypeToString( _
ByVal nodeType As NodeType _
) As String
[C#]
public static string NodeTypeToString(
NodeType nodeType
);

Example

Shows how to enumerate immediate child nodes of a composite node using NextSibling. In this example we enumerate all paragraphs of a section body.

[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Loop starting from the first child until we reach null.
for (Node node = body.FirstChild; node != null; node = node.NextSibling)
{
    // Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType));
}
Shows how to efficiently visit all direct and indirect children of a composite node.
[C#]

public void RecurseAllNodes()
{
    // Open a document.
    Document doc = new Document(MyDir + "Node.RecurseAllNodes.doc");

    // Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc);
}

/// <summary>
/// A simple function that will walk through all children of a specified node recursively
/// and print the type of each node to the screen.
/// </summary>
public void TraverseAllNodes(CompositeNode parentNode)
{
    // This is the most efficient way to loop through immediate children of a node.
    for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
    {
        // Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType));

        // Recurse into the node if it is a composite node.
        if (childNode.IsComposite)
            TraverseAllNodes((CompositeNode) childNode);
    }
}

See Also

Node Class | Aspose.Words Namespace


Node.PreviousPreOrder Method

Gets the previous node according to the pre-order tree traversal algorithm.

[Visual Basic]
Public Function PreviousPreOrder( _
ByVal rootNode As Node _
) As Node
[C#]
public Node PreviousPreOrder(
Node rootNode
);

Parameters

rootNode
The top node (limit) of traversal.

Return Value

Previous node in pre-order order. Null if reached the rootNode.

See Also

Node Class | Aspose.Words Namespace


Node.Remove Method

Removes itself from the parent.

[Visual Basic]
Public Sub Remove()
[C#]
public void Remove();

Example

Shows how to delete all images from a document.

[C#]

// Here we get all shapes from the document node, but you can do this for any smaller
// node too, for example delete shapes from a single section or a paragraph.
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

// We cannot delete shape nodes while we enumerate through the collection.
// One solution is to add nodes that we want to delete to a temporary array and delete afterwards.
ArrayList shapesToDelete = new ArrayList();
foreach (Shape shape in shapes.OfType<Shape>())
{
    // Several shape types can have an image including image shapes and OLE objects.
    if (shape.HasImage)
        shapesToDelete.Add(shape);
}

// Now we can delete shapes.
foreach (Shape shape in shapesToDelete)
    shape.Remove();
Shows how to remove all nodes of a specific type from a composite node. In this example we remove tables from a section body.
[C#]

// Get the section that we want to work on.
Section section = doc.Sections[0];
Body body = section.Body;

// Select the first child node in the body.
Node curNode = body.FirstChild;

while (curNode != null)
{
    // Save the pointer to the next sibling node because if the current
    // node is removed from the parent in the next step, we will have
    // no way of finding the next node to continue the loop.
    Node nextNode = curNode.NextSibling;

    // A section body can contain Paragraph and Table nodes.
    // If the node is a Table, remove it from the parent.
    if (curNode.NodeType.Equals(NodeType.Table))
        curNode.Remove();

    // Continue going through child nodes until null (no more siblings) is reached.
    curNode = nextNode;
}

See Also

Node Class | Aspose.Words Namespace


ToString Method

Aspose.Words

Node.ToString Method

Exports the content of the node into a string in the specified format.

Overload List

Exports the content of the node into a string in the specified format.

public string ToString(SaveFormat);

Exports the content of the node into a string using the specified save options.

public string ToString(SaveOptions);

See Also

Node Class | Aspose.Words Namespace


Node.ToString Method (SaveFormat)

Exports the content of the node into a string in the specified format.

[Visual Basic]
Overloads Public Function ToString( _
ByVal saveFormat As SaveFormat _
) As String
[C#]
public string ToString(
SaveFormat saveFormat
);

Return Value

The content of the node in the specified format.

Example

Exports the content of a node to String in HTML format using default options.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Extract the last paragraph in the document to convert to HTML.
Node node = doc.LastSection.Body.LastParagraph;

// When ToString is called using the SaveFormat overload then conversion is executed using default save options.
// When saving to HTML using default options the following settings are set:
//   ExportImagesAsBase64 = true
//   CssStyleSheetType = CssStyleSheetType.Inline
//   ExportFontResources = false
String nodeAsHtml = node.ToString(SaveFormat.Html);
Shows the difference between calling the GetText and ToString methods on a node.
[C#]

Document doc = new Document();

// Enter a dummy field into the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField("MERGEFIELD Field");

// GetText will retrieve all field codes and special characters
Console.WriteLine("GetText() Result: " + doc.GetText());

// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
Console.WriteLine("ToString() Result: " + doc.ToString(SaveFormat.Text));
Shows how to extract the label of each paragraph in a list as a value or a String.
[C#]

Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
doc.UpdateListLabels();
int listParaCount = 1;

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
    // which start at three and ends at six.
    if (paragraph.ListFormat.IsListItem)
    {
        Console.WriteLine("Paragraph #{0}", listParaCount);

        // This is the text we get when actually getting when we output this node to text format.
        // The list labels are not included in this text output. Trim any paragraph formatting characters.
        String paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
        Console.WriteLine("Exported Text: " + paragraphText);

        ListLabel label = paragraph.ListLabel;
        // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
        // will tell us what position it is on that particular level.
        Console.WriteLine("Numerical Id: " + label.LabelValue);

        // Combine them together to include the list label with the text in the output.
        Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

        listParaCount++;
    }
}

See Also

Node Class | Aspose.Words Namespace | Node.ToString Overload List


Node.ToString Method (SaveOptions)

Exports the content of the node into a string using the specified save options.

[Visual Basic]
Overloads Public Function ToString( _
ByVal saveOptions As SaveOptions _
) As String
[C#]
public string ToString(
SaveOptions saveOptions
);

Parameters

saveOptions
Specifies the options that control how the node is saved.

Return Value

The content of the node in the specified format.

Example

Exports the content of a node to String in HTML format using custom specified options.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Extract the last paragraph in the document to convert to HTML.
Node node = doc.LastSection.Body.LastParagraph;

// Create an instance of HtmlSaveOptions and set a few options.
HtmlSaveOptions saveOptions = new HtmlSaveOptions
{
    ExportHeadersFootersMode = ExportHeadersFootersMode.PerSection,
    ExportRelativeFontSize = true
};

// Convert the document to HTML and return as a String. Pass the instance of HtmlSaveOptions to
// to use the specified options during the conversion.
String nodeAsHtml = node.ToString(saveOptions);

See Also

Node Class | Aspose.Words Namespace | Node.ToString Overload List


NodeChangingAction Enumeration

Specifies the type of node change.

[Visual Basic]
Public Enum NodeChangingAction
[C#]
public enum NodeChangingAction

Remarks

Members

Member Name | Description | Value
Insert | A node is being inserted in the tree. | 0
Remove | A node is being removed from the tree. | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | NodeChangingArgs | Action


NodeChangingArgs Class

Provides data for methods of the INodeChangingCallback interface.

For a list of all members of this type, see NodeChangingArgs Members.

System.Object
Aspose.Words.NodeChangingArgs

[Visual Basic]
Public Class NodeChangingArgs
[C#]
public class NodeChangingArgs

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

NodeChangingArgs Members | Aspose.Words Namespace | DocumentBase | INodeChangingCallback | NodeChangingAction


NodeChangingArgs Members

NodeChangingArgs overview

Public Instance Properties

Action | Gets a value indicating what type of node change event is occurring.
NewParent | Gets the node's parent that will be set after the operation completes.
Node | Gets the Node that is being added or removed.
OldParent | Gets the node's parent before the operation began.

See Also

NodeChangingArgs Class | Aspose.Words Namespace | DocumentBase | INodeChangingCallback | NodeChangingAction


NodeChangingArgs Properties

The properties of the NodeChangingArgs class are listed below. For a complete list of NodeChangingArgs class members, see the NodeChangingArgs Members topic.

Public Instance Properties

Action | Gets a value indicating what type of node change event is occurring.
NewParent | Gets the node's parent that will be set after the operation completes.
Node | Gets the Node that is being added or removed.
OldParent | Gets the node's parent before the operation began.

See Also

NodeChangingArgs Class | Aspose.Words Namespace | DocumentBase | INodeChangingCallback | NodeChangingAction


Action Property

Aspose.Words

NodeChangingArgs.Action Property

Gets a value indicating what type of node change event is occurring.

[Visual Basic]
Public ReadOnly Property Action As NodeChangingAction
[C#]
public NodeChangingAction Action {get;}

See Also

NodeChangingArgs Class | Aspose.Words Namespace


NewParent Property

Aspose.Words

NodeChangingArgs.NewParent Property

Gets the node's parent that will be set after the operation completes.

[Visual Basic]
Public ReadOnly Property NewParent As Node
[C#]
public Node NewParent {get;}

See Also

NodeChangingArgs Class | Aspose.Words Namespace


Node Property

Aspose.Words

NodeChangingArgs.Node Property

Gets the Node that is being added or removed.

[Visual Basic]
Public ReadOnly Property Node As Node
[C#]
public Node Node {get;}

Example

Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.

[C#]

public void TestNodeChangingInDocument()
{
    // Create a blank document object
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = new HandleNodeChangingFontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(ArtifactsDir + "Document.FontChanger.doc");

    // Check that the inserted content has the correct formatting
    Run run = (Run) doc.GetChild(NodeType.Run, 0, true);
    Assert.AreEqual(24.0, run.Font.Size);
    Assert.AreEqual("Arial", run.Font.Name);
}

public class HandleNodeChangingFontChanger : INodeChangingCallback
{
    // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        // Change the font of inserted text contained in the Run nodes.
        if (args.Node.NodeType == NodeType.Run)
        {
            Aspose.Words.Font font = ((Run) args.Node).Font;
            font.Size = 24;
            font.Name = "Arial";
        }
    }

    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
        // Do Nothing
    }

    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
        // Do Nothing
    }
}

See Also

NodeChangingArgs Class | Aspose.Words Namespace


OldParent Property

Aspose.Words

NodeChangingArgs.OldParent Property

Gets the node's parent before the operation began.

[Visual Basic]
Public ReadOnly Property OldParent As Node
[C#]
public Node OldParent {get;}

See Also

NodeChangingArgs Class | Aspose.Words Namespace


NodeCollection Class

Represents a collection of nodes of a specific type.

For a list of all members of this type, see NodeCollection Members.

System.Object
Aspose.Words.NodeCollection
Derived types

[Visual Basic]
Public Class NodeCollection
Implements IEnumerable`1([Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class NodeCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

NodeCollection does not own the nodes it contains, rather, is just a selection of nodes of the specified type, but the nodes are stored in the tree under their respective parent nodes.

NodeCollection supports indexed access, iteration and provides add and remove methods.

The NodeCollection collection is "live", i.e. changes to the children of the node object that it was created from are immediately reflected in the nodes returned by the NodeCollection properties and methods.

NodeCollection is returned by GetChildNodes and also serves as a base class for typed node collections such as SectionCollection, ParagraphCollection etc.

NodeCollection can be "flat" and contain only immediate children of the node it was created from, or it can be "deep" and contain all descendant children.

Example

Shows how to replace all textboxes with images.

[C#]

Document doc = new Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

// This gets a live collection of all shape nodes in the document.
NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

// Since we will be adding/removing nodes, it is better to copy all collection
// into a fixed size array, otherwise iterator will be invalidated.
Node[] shapes = shapeCollection.ToArray();

foreach (Shape shape in shapes.OfType<Shape>())
{
    // Filter out all shapes that we don't need.
    if (shape.ShapeType.Equals(ShapeType.TextBox))
    {
        // Create a new shape that will replace the existing shape.
        Shape image = new Shape(doc, ShapeType.Image);

        // Load the image into the new shape.
        image.ImageData.SetImage(ImageDir + "Hammer.wmf");

        // Make new shape's position to match the old shape.
        image.Left = shape.Left;
        image.Top = shape.Top;
        image.Width = shape.Width;
        image.Height = shape.Height;
        image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
        image.RelativeVerticalPosition = shape.RelativeVerticalPosition;
        image.HorizontalAlignment = shape.HorizontalAlignment;
        image.VerticalAlignment = shape.VerticalAlignment;
        image.WrapType = shape.WrapType;
        image.WrapSide = shape.WrapSide;

        // Insert new shape after the old shape and remove the old shape.
        shape.ParentNode.InsertAfter(image, shape);
        shape.Remove();
    }
}

doc.Save(ArtifactsDir + "Shape.ReplaceTextboxesWithImages.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

NodeCollection Members | Aspose.Words Namespace


NodeCollection Members

NodeCollection overview

Public Instance Properties

Count | Gets the number of nodes in the collection.
Item | Retrieves a node at the given index.

Public Instance Methods

Add | Adds a node to the end of the collection.
Clear | Removes all nodes from this collection and from the document.
Contains | Determines whether a node is in the collection.
GetEnumerator |
IndexOf | Returns the zero-based index of the specified node.
Insert | Inserts a node into the collection at the specified index.
Remove | Removes the node from the collection and from the document.
RemoveAt | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all nodes from the collection to a new array of nodes.

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection Properties

The properties of the NodeCollection class are listed below. For a complete list of NodeCollection class members, see the NodeCollection Members topic.

Public Instance Properties

Count | Gets the number of nodes in the collection.
Item | Retrieves a node at the given index.

See Also

NodeCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

NodeCollection.Count Property

Gets the number of nodes in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to enumerate immediate children of a CompositeNode using indexed access.

[C#]

NodeCollection children = paragraph.ChildNodes;
for (int i = 0; i < children.Count; i++)
{
    Node child = children[i];

    // Paragraph may contain children of various types such as runs, shapes and so on.
    if (child.NodeType.Equals(NodeType.Run))
    {
        // Say we found the node that we want, do something useful.
        Run run = (Run) child;
        Console.WriteLine(run.Text);
    }
}
Shows how to find out if a table contains another table or if the table itself is nested inside another table.
[C#]

Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true).OfType<Table>())
    {
        // First lets find if any cells in the table have tables themselves as children.
        int count = GetChildTableCount(table);
        Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

        // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
        int tableDepth = GetNestedDepthOfTable(table);

        if (tableDepth > 0)
            Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex,
                tableDepth);
        else
            Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);

        tableIndex++;
    }
}

/// <summary>
/// Calculates what level a table is nested inside other tables.
/// <returns>
/// An integer containing the level the table is nested at.
/// 0 = Table is not nested inside any other table
/// 1 = Table is nested within one parent table
/// 2 = Table is nested within two parent tables etc..</returns>
/// </summary>
private static int GetNestedDepthOfTable(Table table)
{
    int depth = 0;

    NodeType type = table.NodeType;
    // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Node parent = table.GetAncestor(type);

    while (parent != null)
    {
        // Every time we find a table a level up we increase the depth counter and then try to find an
        // ancestor of type table from the parent.
        depth++;
        parent = parent.GetAncestor(type);
    }

    return depth;
}

/// <summary>
/// Determines if a table contains any immediate child table within its cells.
/// Does not recursively traverse through those tables to check for further tables.
/// <returns>Returns true if at least one child cell contains a table.
/// Returns false if no cells in the table contains a table.</returns>
/// </summary>
private static int GetChildTableCount(Table table)
{
    int tableCount = 0;
    // Iterate through all child rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells.OfType<Cell>())
        {
            // Retrieve the collection of child tables of this cell
            TableCollection childTables = Cell.Tables;

            // If this cell has a table as a child then return true
            if (childTables.Count > 0)
                tableCount++;
        }
    }

    // No cell contains a table
    return tableCount;
}

See Also

NodeCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

NodeCollection.Item Property

Retrieves a node at the given index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Node
[C#]
public Node this[
int index
] {get;}

Parameters

index
An index into the collection of nodes.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to enumerate immediate children of a CompositeNode using indexed access.

[C#]

NodeCollection children = paragraph.ChildNodes;
for (int i = 0; i < children.Count; i++)
{
    Node child = children[i];

    // Paragraph may contain children of various types such as runs, shapes and so on.
    if (child.NodeType.Equals(NodeType.Run))
    {
        // Say we found the node that we want, do something useful.
        Run run = (Run) child;
        Console.WriteLine(run.Text);
    }
}

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection Methods

The methods of the NodeCollection class are listed below. For a complete list of NodeCollection class members, see the NodeCollection Members topic.

Public Instance Methods

Add | Adds a node to the end of the collection.
Clear | Removes all nodes from this collection and from the document.
Contains | Determines whether a node is in the collection.
GetEnumerator |
IndexOf | Returns the zero-based index of the specified node.
Insert | Inserts a node into the collection at the specified index.
Remove | Removes the node from the collection and from the document.
RemoveAt | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all nodes from the collection to a new array of nodes.

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.Add Method

Adds a node to the end of the collection.

[Visual Basic]
Public Sub Add( _
ByVal node As Node _
)
[C#]
public void Add(
Node node
);

Parameters

node
The node to be added to the end of the collection.

Remarks

The node is inserted as a child into the node object from which the collection was created.

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use ImportNode to import the node to the current document. The imported node can then be inserted into the current document.

Exceptions

Exception Type | Condition
NotSupportedException | The NodeCollection is a "deep" collection.

Example

Shows how to add a section to the end of the document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Section sectionToAdd = new Section(doc);
doc.Sections.Add(sectionToAdd);

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.Clear Method

Removes all nodes from this collection and from the document.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to remove all sections from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.Sections.Clear();

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.Contains Method

Determines whether a node is in the collection.

[Visual Basic]
Public Function Contains( _
ByVal node As Node _
) As Boolean
[C#]
public bool Contains(
Node node
);

Parameters

node
The node to locate.

Return Value

True if item is found in the collection; otherwise, false.

Remarks

This method performs a linear search; therefore, the average execution time is proportional to Count.

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.GetEnumerator Method

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Node) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Node> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.IndexOf Method

Returns the zero-based index of the specified node.

[Visual Basic]
Public Function IndexOf( _
ByVal node As Node _
) As Integer
[C#]
public int IndexOf(
Node node
);

Parameters

node
The node to locate.

Return Value

The zero-based index of the node within the collection, if found; otherwise, -1.

Remarks

This method performs a linear search; therefore, the average execution time is proportional to Count.

Example

Retrieves the index of a table in the document.

[C#]

NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
int tableIndex = allTables.IndexOf(table);
Shows how to iterate through all tables in the document and display the content from each cell.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.Insert Method

Inserts a node into the collection at the specified index.

[Visual Basic]
Public Sub Insert( _
ByVal index As Integer, _
ByVal node As Node _
)
[C#]
public void Insert(
int index,
Node node
);

Parameters

index
The zero-based index of the node. Negative indexes are allowed and indicate access from the back of the list. For example -1 means the last node, -2 means the second before last and so on.
node
The node to insert.

Remarks

The node is inserted as a child into the node object from which the collection was created.

If the index is equal to or greater than Count, the node is added at the end of the collection.

If the index is negative and its absolute value is greater than Count, the node is added at the end of the collection.

If the newChild is already in the tree, it is first removed.

If the node being inserted was created from another document, you should use ImportNode to import the node to the current document. The imported node can then be inserted into the current document.

Exceptions

Exception Type | Condition
NotSupportedException | The NodeCollection is a "deep" collection.

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.Remove Method

Removes the node from the collection and from the document.

[Visual Basic]
Public Sub Remove( _
ByVal node As Node _
)
[C#]
public void Remove(
Node node
);

Parameters

node
The node to remove.

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.RemoveAt Method

Removes the node at the specified index from the collection and from the document.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the node. Negative indexes are allowed and indicate access from the back of the list. For example -1 means the last node, -2 means the second before last and so on.

Example

Shows how to add/remove sections in a document.

[C#]

// Open the document.
Document doc = new Document(MyDir + "Section.AddRemove.doc");

// This shows what is in the document originally. The document has two sections.
Console.WriteLine(doc.GetText());

// Delete the first section from the document
doc.Sections.RemoveAt(0);

// Duplicate the last section and append the copy to the end of the document.
int lastSectionIdx = doc.Sections.Count - 1;
Section newSection = doc.Sections[lastSectionIdx].Clone();
doc.Sections.Add(newSection);

// Check what the document contains after we changed it.
Console.WriteLine(doc.GetText());

See Also

NodeCollection Class | Aspose.Words Namespace


NodeCollection.ToArray Method

Copies all nodes from the collection to a new array of nodes.

[Visual Basic]
Public Function ToArray() As Node()
[C#]
public Node[] ToArray();

Return Value

An array of nodes.

Remarks

You should not be adding/removing nodes while iterating over a collection of nodes because it invalidates the iterator and requires refreshes for live collections.

To be able to add/remove nodes during iteration, use this method to copy nodes into a fixed-size array and then iterate over the array.

Example

Shows how to replace all textboxes with images.

[C#]

Document doc = new Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

// This gets a live collection of all shape nodes in the document.
NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

// Since we will be adding/removing nodes, it is better to copy all collection
// into a fixed size array, otherwise iterator will be invalidated.
Node[] shapes = shapeCollection.ToArray();

foreach (Shape shape in shapes.OfType<Shape>())
{
    // Filter out all shapes that we don't need.
    if (shape.ShapeType.Equals(ShapeType.TextBox))
    {
        // Create a new shape that will replace the existing shape.
        Shape image = new Shape(doc, ShapeType.Image);

        // Load the image into the new shape.
        image.ImageData.SetImage(ImageDir + "Hammer.wmf");

        // Make new shape's position to match the old shape.
        image.Left = shape.Left;
        image.Top = shape.Top;
        image.Width = shape.Width;
        image.Height = shape.Height;
        image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
        image.RelativeVerticalPosition = shape.RelativeVerticalPosition;
        image.HorizontalAlignment = shape.HorizontalAlignment;
        image.VerticalAlignment = shape.VerticalAlignment;
        image.WrapType = shape.WrapType;
        image.WrapSide = shape.WrapSide;

        // Insert new shape after the old shape and remove the old shape.
        shape.ParentNode.InsertAfter(image, shape);
        shape.Remove();
    }
}

doc.Save(ArtifactsDir + "Shape.ReplaceTextboxesWithImages.doc");

See Also

NodeCollection Class | Aspose.Words Namespace


NodeImporter Class

Allows to efficiently perform repeated import of nodes from one document to another.

For a list of all members of this type, see NodeImporter Members.

System.Object
Aspose.Words.NodeImporter

[Visual Basic]
Public Class NodeImporter
[C#]
public class NodeImporter

Remarks

Aspose.Words provides functionality for easy copying and moving fragments between Microsoft Word documents. This is known as "importing nodes". Before you can insert a fragment from one document into another, you need to "import" it. Importing creates a deep clone of the original node, ready to be inserted into the destination document.

The simplest way to import a node is to use the ImportNode method provided by the DocumentBase object.

However, when you need to import nodes from one document to another multiple times, it is better to use the NodeImporter class. The NodeImporter class allows to minimize the number of styles and lists created in the destination document.

Copying or moving fragments from one Microsoft Word document to another presents a number of technical challenges for Aspose.Words. In a Word document, styles and list formatting are stored centrally, separately from the text of the document. The paragraphs and runs of text merely reference the styles by internal unique identifiers.

The challenges arise from the fact that styles and lists are different in different documents. For example, to copy a paragraph formatted with the Heading 1 style from one document to another, a number of things must be taken into account: decide whether to copy the Heading 1 style from the source document to the destination document, clone the paragraph, update the cloned paragraph so it refers to the correct Heading 1 style in the destination document. If the style had to be copied, all the styles that it references (based on style and next paragraph style) should be analyzed and possibly copied too and so on. Similar issues exist when copying bulleted or numbered paragraphs because Microsoft Word stores list definitions separately from text.

The NodeImporter class is like a context, that holds the "translation tables" during the import. It correctly translates between styles and lists in the source and destination documents.

Example

This is a method that inserts contents of one document at a specified location in another document.

[C#]

/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
    // Make sure that the node is either a paragraph or table.
    if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
        (!insertAfterNode.NodeType.Equals(NodeType.Table)))
        throw new ArgumentException("The destination node should be either a paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;

    // This object will be translating styles and lists during the import.
    NodeImporter importer =
        new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

    // Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections.OfType<Section>())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.NodeType.Equals(NodeType.Paragraph))
            {
                Paragraph para = (Paragraph) srcNode;
                if (para.IsEndOfSection && !para.HasChildNodes)
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

NodeImporter Members | Aspose.Words Namespace | Document | ImportNode


NodeImporter Members

NodeImporter overview

Public Instance Constructors

NodeImporter Overloaded. Initializes a new instance of the NodeImporter class.

Public Instance Methods

ImportNode Imports a node from one document into another.

See Also

NodeImporter Class | Aspose.Words Namespace | Document | ImportNode


NodeImporter Constructor

Initializes a new instance of the NodeImporter class.

Overload List

Initializes a new instance of the NodeImporter class.

public NodeImporter(DocumentBase,DocumentBase,ImportFormatMode);

Initializes a new instance of the NodeImporter class.

public NodeImporter(DocumentBase,DocumentBase,ImportFormatMode,ImportFormatOptions);

See Also

NodeImporter Class | Aspose.Words Namespace


NodeImporter Constructor (DocumentBase, DocumentBase, ImportFormatMode)

Initializes a new instance of the NodeImporter class.

[Visual Basic]
Overloads Public Sub New( _
ByVal srcDoc As DocumentBase, _
ByVal dstDoc As DocumentBase, _
ByVal importFormatMode As ImportFormatMode _
)
[C#]
public NodeImporter(
DocumentBase srcDoc,
DocumentBase dstDoc,
ImportFormatMode importFormatMode
);

Parameters

srcDoc
The source document.
dstDoc
The destination document that will be the owner of imported nodes.
importFormatMode
Specifies how to merge style formatting that clashes.

Example

This is a method that inserts contents of one document at a specified location in another document.

[C#]

/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
    // Make sure that the node is either a paragraph or table.
    if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
        (!insertAfterNode.NodeType.Equals(NodeType.Table)))
        throw new ArgumentException("The destination node should be either a paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;

    // This object will be translating styles and lists during the import.
    NodeImporter importer =
        new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

    // Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections.OfType<Section>())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.NodeType.Equals(NodeType.Paragraph))
            {
                Paragraph para = (Paragraph) srcNode;
                if (para.IsEndOfSection && !para.HasChildNodes)
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

See Also

NodeImporter Class | Aspose.Words Namespace | NodeImporter Constructor Overload List


NodeImporter Constructor (DocumentBase, DocumentBase, ImportFormatMode, ImportFormatOptions)

Initializes a new instance of the NodeImporter class.

[Visual Basic]
Overloads Public Sub New( _
ByVal srcDoc As DocumentBase, _
ByVal dstDoc As DocumentBase, _
ByVal importFormatMode As ImportFormatMode, _
ByVal importFormatOptions As ImportFormatOptions _
)
[C#]
public NodeImporter(
DocumentBase srcDoc,
DocumentBase dstDoc,
ImportFormatMode importFormatMode,
ImportFormatOptions importFormatOptions
);

Parameters

srcDoc
The source document.
dstDoc
The destination document that will be the owner of imported nodes.
importFormatMode
Specifies how to merge style formatting that clashes.
importFormatOptions
Specifies various options to format imported node.

Example

Shows how the numbering will be imported when it clashes in source and destination documents.

[C#]

Document dstDoc = new Document(MyDir + "DocumentBuilder.KeepSourceNumbering.DestinationDocument.docx");
Document srcDoc = new Document(MyDir + "DocumentBuilder.KeepSourceNumbering.SourceDocument.docx");

ImportFormatOptions importFormatOptions = new ImportFormatOptions();
// Keep source list formatting when importing numbered paragraphs
importFormatOptions.KeepSourceNumbering = true;

NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting, importFormatOptions);

ParagraphCollection srcParas = srcDoc.FirstSection.Body.Paragraphs;
foreach (Node node in srcParas)
{
    Paragraph srcPara = (Paragraph) node;
    Node importedNode = importer.ImportNode(srcPara, true);
    dstDoc.FirstSection.Body.AppendChild(importedNode);
}

dstDoc.Save(ArtifactsDir + "DocumentBuilder.KeepSourceNumbering.ResultDocument.docx");

See Also

NodeImporter Class | Aspose.Words Namespace | NodeImporter Constructor Overload List


NodeImporter Methods

The methods of the NodeImporter class are listed below. For a complete list of NodeImporter class members, see the NodeImporter Members topic.

Public Instance Methods

ImportNode Imports a node from one document into another.

See Also

NodeImporter Class | Aspose.Words Namespace | Document | ImportNode


NodeImporter.ImportNode Method

Imports a node from one document into another.

[Visual Basic]
Public Function ImportNode( _
ByVal srcNode As Node, _
ByVal isImportChildren As Boolean _
) As Node
[C#]
public Node ImportNode(
Node srcNode,
bool isImportChildren
);

Parameters

srcNode
The node to import.
isImportChildren
True to import all child nodes recursively; otherwise, false.

Return Value

The cloned, imported node. The node belongs to the destination document, but has no parent.

Remarks

Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using InsertBefore or InsertAfter.

If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

Example

This is a method that inserts contents of one document at a specified location in another document.

[C#]

/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
    // Make sure that the node is either a paragraph or table.
    if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
        (!insertAfterNode.NodeType.Equals(NodeType.Table)))
        throw new ArgumentException("The destination node should be either a paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;

    // This object will be translating styles and lists during the import.
    NodeImporter importer =
        new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

    // Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections.OfType<Section>())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.NodeType.Equals(NodeType.Paragraph))
            {
                Paragraph para = (Paragraph) srcNode;
                if (para.IsEndOfSection && !para.HasChildNodes)
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

See Also

NodeImporter Class | Aspose.Words Namespace


NodeList Class

Represents a collection of nodes matching an XPath query executed using the SelectNodes method.

For a list of all members of this type, see NodeList Members.

System.Object
Aspose.Words.NodeList

[Visual Basic]
Public Class NodeList
Implements IEnumerable`1([Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class NodeList : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

NodeList is returned by SelectNodes and contains a collection of nodes matching the XPath query.

NodeList supports indexed access and iteration.

Note Treat the NodeList collection as a "snapshot" collection. NodeList starts as a "live" collection because the nodes are not actually retrieved when the XPath query is run. The nodes are only retrieved upon access and at this time the node and all nodes that precede it are cached forming a "snapshot" collection.

Example

Finds all hyperlinks in a Word document and changes their URL and display name.

[C#]

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Fields;
using NUnit.Framework;

namespace ApiExamples
{
    /// <summary>
    /// Shows how to replace hyperlinks in a Word document.
    /// </summary>
    public class ExReplaceHyperlinks : ApiExampleBase
    {
        /// <summary>
        /// Finds all hyperlinks in a Word document and changes their URL and display name.
        /// </summary>
        public void ReplaceHyperlinks()
        {
            // Specify your document name here.
            Document doc = new Document(MyDir + "ReplaceHyperlinks.doc");

            // Hyperlinks in a Word documents are fields, select all field start nodes so we can find the hyperlinks.
            NodeList fieldStarts = doc.SelectNodes("//FieldStart");
            foreach (FieldStart fieldStart in fieldStarts.OfType<FieldStart>())
            {
                if (fieldStart.FieldType.Equals(FieldType.FieldHyperlink))
                {
                    // The field is a hyperlink field, use the "facade" class to help to deal with the field.
                    Hyperlink hyperlink = new Hyperlink(fieldStart);

                    // Some hyperlinks can be local (links to bookmarks inside the document), ignore these.
                    if (hyperlink.IsLocal)
                        continue;

                    // The Hyperlink class allows to set the target URL and the display name
                    // of the link easily by setting the properties.
                    hyperlink.Target = NewUrl;
                    hyperlink.Name = NewName;
                }
            }

            doc.Save(ArtifactsDir + "ReplaceHyperlinks.doc");
        }

        private const String NewUrl = @"http://www.aspose.com";
        private const String NewName = "Aspose - The .NET & Java Component Publisher";
    }

    /// <summary>
    /// This "facade" class makes it easier to work with a hyperlink field in a Word document.
    ///
    /// A hyperlink is represented by a HYPERLINK field in a Word document. A field in Aspose.Words
    /// consists of several nodes and it might be difficult to work with all those nodes directly.
    /// Note this is a simple implementation and will work only if the hyperlink code and name
    /// each consist of one Run only.
    ///
    /// [FieldStart][Run - field code][FieldSeparator][Run - field result][FieldEnd]
    ///
    /// The field code contains a String in one of these formats:
    /// HYPERLINK "url"
    /// HYPERLINK \l "bookmark name"
    ///
    /// The field result contains text that is displayed to the user.
    /// </summary>
    internal class Hyperlink
    {
        internal Hyperlink(FieldStart fieldStart)
        {
            if (fieldStart == null)
                throw new ArgumentNullException("fieldStart");
            if (!fieldStart.FieldType.Equals(FieldType.FieldHyperlink))
                throw new ArgumentException("Field start type must be FieldHyperlink.");

            mFieldStart = fieldStart;

            // Find the field separator node.
            mFieldSeparator = FindNextSibling(mFieldStart, NodeType.FieldSeparator);
            if (mFieldSeparator == null)
                throw new InvalidOperationException("Cannot find field separator.");

            // Find the field end node. Normally field end will always be found, but in the example document
            // there happens to be a paragraph break included in the hyperlink and this puts the field end
            // in the next paragraph. It will be much more complicated to handle fields which span several
            // paragraphs correctly, but in this case allowing field end to be null is enough for our purposes.
            mFieldEnd = FindNextSibling(mFieldSeparator, NodeType.FieldEnd);

            // Field code looks something like [ HYPERLINK "http:\\www.myurl.com" ], but it can consist of several runs.
            String fieldCode = GetTextSameParent(mFieldStart.NextSibling, mFieldSeparator);
            Match match = gRegex.Match(fieldCode.Trim());
            mIsLocal = (match.Groups[1].Length > 0); //The link is local if \l is present in the field code.
            mTarget = match.Groups[2].Value;
        }

        /// <summary>
        /// Gets or sets the display name of the hyperlink.
        /// </summary>
        internal String Name
        {
            get { return GetTextSameParent(mFieldSeparator, mFieldEnd); }
            set
            {
                // Hyperlink display name is stored in the field result which is a Run
                // node between field separator and field end.
                Run fieldResult = (Run) mFieldSeparator.NextSibling;
                fieldResult.Text = value;

                // But sometimes the field result can consist of more than one run, delete these runs.
                RemoveSameParent(fieldResult.NextSibling, mFieldEnd);
            }
        }

        /// <summary>
        /// Gets or sets the target url or bookmark name of the hyperlink.
        /// </summary>
        internal String Target
        {
            get
            {
                return mTarget;
            }
            set
            {
                mTarget = value;
                UpdateFieldCode();
            }
        }

        /// <summary>
        /// True if the hyperlinks target is a bookmark inside the document. False if the hyperlink is a url.
        /// </summary>
        internal bool IsLocal
        {
            get { return mIsLocal; }
            set
            {
                mIsLocal = value;
                UpdateFieldCode();
            }
        }

        private void UpdateFieldCode()
        {
            // Field code is stored in a Run node between field start and field separator.
            Run fieldCode = (Run) mFieldStart.NextSibling;
            fieldCode.Text = String.Format("HYPERLINK {0}\"{1}\"", ((mIsLocal) ? "\\l " : ""), mTarget);

            // But sometimes the field code can consist of more than one run, delete these runs.
            RemoveSameParent(fieldCode.NextSibling, mFieldSeparator);
        }

        /// <summary>
        /// Goes through siblings starting from the start node until it finds a node of the specified type or null.
        /// </summary>
        private static Node FindNextSibling(Node startNode, NodeType nodeType)
        {
            for (Node node = startNode; node != null; node = node.NextSibling)
            {
                if (node.NodeType.Equals(nodeType))
                    return node;
            }

            return null;
        }

        /// <summary>
        /// Retrieves text from start up to but not including the end node.
        /// </summary>
        private static String GetTextSameParent(Node startNode, Node endNode)
        {
            if ((endNode != null) && (startNode.ParentNode != endNode.ParentNode))
                throw new ArgumentException("Start and end nodes are expected to have the same parent.");

            StringBuilder builder = new StringBuilder();
            for (Node child = startNode; !child.Equals(endNode); child = child.NextSibling)
                builder.Append(child.GetText());

            return builder.ToString();
        }

        /// <summary>
        /// Removes nodes from start up to but not including the end node.
        /// Start and end are assumed to have the same parent.
        /// </summary>
        private static void RemoveSameParent(Node startNode, Node endNode)
        {
            if ((endNode != null) && (startNode.ParentNode != endNode.ParentNode))
                throw new ArgumentException("Start and end nodes are expected to have the same parent.");

            Node curChild = startNode;
            while ((curChild != null) && (curChild != endNode))
            {
                Node nextChild = curChild.NextSibling;
                curChild.Remove();
                curChild = nextChild;
            }
        }

        private readonly Node mFieldStart;
        private readonly Node mFieldSeparator;
        private readonly Node mFieldEnd;
        private bool mIsLocal;
        private String mTarget;

        /// <summary>
        /// RK I am notoriously bad at regexes. It seems I don't understand their way of thinking.
        /// </summary>
        private static readonly Regex gRegex = new Regex(
            "\\S+" + // one or more non spaces HYPERLINK or other word in other languages
            "\\s+" + // one or more spaces
            "(?:\"\"\\s+)?" + // non capturing optional "" and one or more spaces, found in one of the customers files.
            "(\\\\l\\s+)?" + // optional \l flag followed by one or more spaces
            "\"" + // one apostrophe
            "([^\"]+)" + // one or more chars except apostrophe (hyperlink target)
            "\"" // one closing apostrophe
        );
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

NodeList Members | Aspose.Words Namespace


NodeList Members

NodeList overview

Public Instance Properties

Count | Gets the number of nodes in the list.
Item | Retrieves a node at the given index.

Public Instance Methods

GetEnumerator | Provides a simple "foreach" style iteration over the collection of nodes.
ToArray | Copies all nodes from the collection to a new array of nodes.

See Also

NodeList Class | Aspose.Words Namespace


NodeList Properties

The properties of the NodeList class are listed below. For a complete list of NodeList class members, see the NodeList Members topic.

Public Instance Properties

Count | Gets the number of nodes in the list.
Item | Retrieves a node at the given index.

See Also

NodeList Class | Aspose.Words Namespace


Count Property

Aspose.Words

NodeList.Count Property

Gets the number of nodes in the list.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

NodeList Class | Aspose.Words Namespace


Item Property

Aspose.Words

NodeList.Item Property

Retrieves a node at the given index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Node
[C#]
public Node this[
int index
] {get;}

Parameters

index
An index into the list of nodes.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

NodeList Class | Aspose.Words Namespace


NodeList Methods

The methods of the NodeList class are listed below. For a complete list of NodeList class members, see the NodeList Members topic.

Public Instance Methods

GetEnumerator | Provides a simple "foreach" style iteration over the collection of nodes.
ToArray | Copies all nodes from the collection to a new array of nodes.

See Also

NodeList Class | Aspose.Words Namespace


NodeList.GetEnumerator Method

Provides a simple "foreach" style iteration over the collection of nodes.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Node) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Node> GetEnumerator();

Return Value

An IEnumerator.

Implements

IEnumerable`1.GetEnumerator

See Also

NodeList Class | Aspose.Words Namespace


NodeList.ToArray Method

Copies all nodes from the collection to a new array of nodes.

[Visual Basic]
Public Function ToArray() As Node()
[C#]
public Node[] ToArray();

Return Value

An array of nodes.

Remarks

You should not be adding/removing nodes while iterating over a collection of nodes because it invalidates the iterator and requires refreshes for live collections.

To be able to add/remove nodes during iteration, use this method to copy nodes into a fixed-size array and then iterate over the array.

See Also

NodeList Class | Aspose.Words Namespace


NodeType Enumeration

Specifies the type of a Word document node.

[Visual Basic]
Public Enum NodeType
[C#]
public enum NodeType

Example

The following example shows how to use the NodeType enumeration.

[C#]

Document doc = new Document();

// Returns NodeType.Document
NodeType type = doc.NodeType;

Members

Member Name | Description | Value
Any | Indicates all node types. Allows to select all children. | 0
Document | A Document object that, as the root of the document tree, provides access to the entire Word document. A Document node can have Section nodes. | 1
Section | A Section object that corresponds to one section in a Word document. A Section node can have Body and HeaderFooter nodes. | 2
Body | A Body object that contains the main text of a section (main text story). A Body node can have Paragraph and Table nodes. | 3
HeaderFooter | A HeaderFooter object that contains text of a particular header or footer inside a section. A HeaderFooter node can have Paragraph and Table nodes. | 4
Table | A Table object that represents a table in a Word document. A Table node can have Row nodes. | 5
Row | A row of a table. A Row node can have Cell nodes. | 6
Cell | A cell of a table row. A Cell node can have Paragraph and Table nodes. | 7
Paragraph | A paragraph of text. A Paragraph node is a container for inline level elements Run, FieldStart, FieldSeparator, FieldEnd, FormField, Shape, GroupShape, Footnote, Comment, SpecialChar, as well as BookmarkStart and BookmarkEnd. | 8
BookmarkStart | A beginning of a bookmark marker. | 9
BookmarkEnd | An end of a bookmark marker. | 10
EditableRangeStart | A beginning of an editable range. | 11
EditableRangeEnd | An end of an editable range. | 12
MoveFromRangeStart | A beginning of an MoveFrom range. | 13
MoveFromRangeEnd | An end of an MoveFrom range. | 14
MoveToRangeStart | A beginning of an MoveTo range. | 15
MoveToRangeEnd | An end of an MoveTo range. | 16
GroupShape | A group of shapes, images, OLE objects or other group shapes. A GroupShape node can contain other Shape and GroupShape nodes. | 17
Shape | A drawing object, such as an OfficeArt shape, image or an OLE object. A Shape node can contain Paragraph and Table nodes. | 18
Comment | A comment in a Word document. A Comment node can have Paragraph and Table nodes. | 19
Footnote | A footnote or endnote in a Word document. A Footnote node can have Paragraph and Table nodes. | 20
Run | A run of text. | 21
FieldStart | A special character that designates the start of a Word field. | 22
FieldSeparator | A special character that separates the field code from the field result. | 23
FieldEnd | A special character that designates the end of a Word field. | 24
FormField | A form field. | 25
SpecialChar | A special character that is not one of the more specific special character types. | 26
SmartTag | A smart tag around one or more inline structures (runs, images, fields,etc.) within a paragraph | 27
StructuredDocumentTag | Allows to define customer-specific information and its means of presentation. | 28
GlossaryDocument | A glossary document within the main document. | 29
BuildingBlock | A building block within a glossary document (e.g. glossary document entry). | 30
CommentRangeStart | A marker node that represents the start of a commented range. | 31
CommentRangeEnd | A marker node that represents the end of a commented range. | 32
OfficeMath | An Office Math object. Can be equation, function, matrix or one of other mathematical objects. Can be a collection of mathematical object and also can contain some non-mathematical objects such as runs of text. | 33
SubDocument | A subdocument node which is a link to another document. | 34
System | Reserved for internal use by Aspose.Words. | 35
Null | Reserved for internal use by Aspose.Words. | 36

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


NumberStyle Enumeration

Specifies the number style for a list, footnotes and endnotes, page numbers.

[Visual Basic]
Public Enum NumberStyle
[C#]
public enum NumberStyle

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

Members

Member Name | Description | Value
Arabic | Arabic numbering (1, 2, 3, ...) | 0
UppercaseRoman | Upper case Roman (I, II, III, ...) | 1
LowercaseRoman | Lower case Roman (i, ii, iii, ...) | 2
UppercaseLetter | Upper case Letter (A, B, C, ...) | 3
LowercaseLetter | Lower case letter (a, b, c, ...) | 4
Ordinal | Ordinal (1st, 2nd, 3rd, ...) | 5
Number | Numbered (One, Two, Three, ...) | 6
OrdinalText | Ordinal (text) (First, Second, Third, ...) | 7
Hex | Hexadecimal: 8, 9, A, B, C, D, E, F, 10, 11, 12 | 8
ChicagoManual | Chicago Manual of Style: *, †, † | 9
Kanji | Ideograph-digital | 10
KanjiDigit | Japanese counting | 11
AiueoHalfWidth | Aiueo | 12
IrohaHalfWidth | Iroha | 13
ArabicFullWidth | Full-width Arabic: 1, 2, 3, 4 | 14
ArabicHalfWidth | Half-width Arabic: 1, 2, 3, 4 | 15
KanjiTraditional | Japanese legal | 16
KanjiTraditional2 | Japanese digital ten thousand | 17
NumberInCircle | Enclosed circles | 18
DecimalFullWidth | Decimal full width: 1, 2, 3, 4 | 19
Aiueo | Aiueo full width | 20
Iroha | Iroha full width | 21
LeadingZero | Leading Zero (01, 02,..., 09, 10, 11,..., 99, 100, 101,...) | 22
Bullet | Bullet (check the character code in the text) | 23
Ganada | Korean Ganada | 24
Chosung | Korea Chosung | 25
GB1 | Enclosed full stop | 26
GB2 | Enclosed parenthesis | 27
GB3 | Enclosed circle Chinese | 28
GB4 | Ideograph enclosed circle | 29
Zodiac1 | Ideograph traditional | 30
Zodiac2 | Ideograph Zodiac | 31
Zodiac3 | Ideograph Zodiac traditional | 32
TradChinNum1 | Taiwanese counting | 33
TradChinNum2 | Ideograph legal traditional | 34
TradChinNum3 | Taiwanese counting thousand | 35
TradChinNum4 | Taiwanese digital | 36
SimpChinNum1 | Chinese counting | 37
SimpChinNum2 | Chinese legal simplified | 38
SimpChinNum3 | Chinese counting thousand | 39
SimpChinNum4 | Chinese (not implemented) | 40
HanjaRead | Korean digital | 41
HanjaReadDigit | Korean counting | 42
Hangul | Korea legal | 43
Hanja | Korea digital2 | 44
Hebrew1 | Hebrew-1 | 45
Arabic1 | Arabic alpha | 46
Hebrew2 | Hebrew-2 | 47
Arabic2 | Arabic abjad | 48
HindiLetter1 | Hindi vowels | 49
HindiLetter2 | Hindi consonants | 50
HindiArabic | Hindi numbers | 51
HindiCardinalText | Hindi descriptive (cardinals) | 52
ThaiLetter | Thai letters | 53
ThaiArabic | Thai numbers | 54
ThaiCardinalText | Thai descriptive (cardinals) | 55
VietCardinalText | Vietnamese descriptive (cardinals) | 56
NumberInDash | Page number format: - 1 -, - 2 -, - 3 -, - 4 - | 57
LowercaseRussian | Lowercase Russian alphabet | 58
UppercaseRussian | Uppercase Russian alphabet | 59
None | No bullet or number. | 255
Custom | Custom number format. It is supported by DOCX format only. | 65280

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Orientation Enumeration

Specifies page orientation.

[Visual Basic]
Public Enum Orientation
[C#]
public enum Orientation

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

Members

Member Name | Description | Value
Portrait | Portrait page orientation (narrow and tall). | 1
Landscape | Landscape page orientation (wide and short). | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


OutlineLevel Enumeration

Specifies the outline level of a paragraph in the document.

[Visual Basic]
Public Enum OutlineLevel
[C#]
public enum OutlineLevel

Members

Member Name | Description | Value
Level1 | The paragraph is at the outline level 1 (topmost level). | 0
Level2 | The paragraph is at the outline level 2. | 1
Level3 | The paragraph is at the outline level 3. | 2
Level4 | The paragraph is at the outline level 4. | 3
Level5 | The paragraph is at the outline level 5. | 4
Level6 | The paragraph is at the outline level 6. | 5
Level7 | The paragraph is at the outline level 7. | 6
Level8 | The paragraph is at the outline level 8. | 7
Level9 | The paragraph is at the outline level 9. | 8
BodyText | The paragraph is at the level of the main text. | 9

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


PageBorderAppliesTo Enumeration

Specifies which pages the page border is printed on.

[Visual Basic]
Public Enum PageBorderAppliesTo
[C#]
public enum PageBorderAppliesTo

Remarks

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");

Members

Member Name | Description | Value
AllPages | Page border is shown on all pages of the section. | 0
FirstPage | Page border is shown on the first page of the section only. | 1
OtherPages | Page border is shown on all pages except the first page of the section. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | PageSetup | BorderAppliesTo


PageBorderDistanceFrom Enumeration

Specifies the positioning of the page border relative to the page margin.

[Visual Basic]
Public Enum PageBorderDistanceFrom
[C#]
public enum PageBorderDistanceFrom

Remarks

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");

Members

Member Name | Description | Value
Text | Border position is measured from the page margin. | 0
PageEdge | Border position is measured from the page edge. | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | PageSetup | BorderDistanceFrom


PageSetup Class

Represents the page setup properties of a section.

For a list of all members of this type, see PageSetup Members.

System.Object
Aspose.Words.PageSetup

[Visual Basic]
Public Class PageSetup
[C#]
public class PageSetup

Remarks

PageSetup object contains all the page setup attributes of a section (left margin, bottom margin, paper size, and so on) as properties.

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PageSetup Members | Aspose.Words Namespace


PageSetup Members

PageSetup overview

Public Instance Properties

Bidi | Specifies that this section contains bidirectional (complex scripts) text.
BorderAlwaysInFront | Specifies where the page border is positioned relative to intersecting texts and objects.
BorderAppliesTo | Specifies which pages the page border is printed on.
BorderDistanceFrom | Gets or sets a value that indicates whether the specified page border is measured from the edge of the page or from the text it surrounds.
Borders | Gets a collection of the page borders.
BorderSurroundsFooter | Specifies whether the page border includes or excludes the footer.
BorderSurroundsHeader | Specifies whether the page border includes or excludes the header.
BottomMargin | Returns or sets the distance (in points) between the bottom edge of the page and the bottom boundary of the body text.
CharactersPerLine | Gets or sets the number of characters per line in the document grid.
DifferentFirstPageHeaderFooter | True if a different header or footer is used on the first page.
EndnoteOptions | Provides options that control numbering and positioning of endnotes in this section.
FirstPageTray | Gets or sets the paper tray (bin) to use for the first page of a section. The value is implementation (printer) specific.
FooterDistance | Returns or sets the distance (in points) between the footer and the bottom of the page.
FootnoteOptions | Provides options that control numbering and positioning of footnotes in this section.
Gutter | Gets or sets the amount of extra space added to the margin for document binding.
HeaderDistance | Returns or sets the distance (in points) between the header and the top of the page.
LayoutMode | Gets or sets the layout mode of this section.
LeftMargin | Returns or sets the distance (in points) between the left edge of the page and the left boundary of the body text.
LineNumberCountBy | Returns or sets the numeric increment for line numbers.
LineNumberDistanceFromText | Gets or sets distance between the right edge of line numbers and the left edge of the document.
LineNumberRestartMode | Gets or sets the way line numbering runs that is, whether it starts over at the beginning of a new page or section or runs continuously.
LinesPerPage | Gets or sets the number of lines per page in the document grid.
LineStartingNumber | Gets or sets the starting line number.
MultiplePages | For multiple page documents, gets or sets how a document is printed or rendered so that it can be bound as a booklet.
OddAndEvenPagesHeaderFooter | True if the document has different headers and footers for odd-numbered and even-numbered pages.
Orientation | Returns or sets the orientation of the page.
OtherPagesTray | Gets or sets the paper tray (bin) to be used for all but the first page of a section. The value is implementation (printer) specific.
PageHeight | Returns or sets the height of the page in points.
PageNumberStyle | Gets or sets the page number format.
PageStartingNumber | Gets or sets the starting page number of the section.
PageWidth | Returns or sets the width of the page in points.
PaperSize | Returns or sets the paper size.
RestartPageNumbering | True if page numbering restarts at the beginning of the section.
RightMargin | Returns or sets the distance (in points) between the right edge of the page and the right boundary of the body text.
RtlGutter | Gets or sets whether Microsoft Word uses gutters for the section based on a right-to-left language or a left-to-right language.
SectionStart | Returns or sets the type of section break for the specified object.
SheetsPerBooklet | Returns or sets the number of pages to be included in each booklet.
SuppressEndnotes | True if endnotes are printed at the end of the next section that doesn't suppress endnotes. Suppressed endnotes are printed before the endnotes in that section.
TextColumns | Returns a collection that represents the set of text columns.
TextOrientation | Allows to specify TextOrientation for the whole page. Default value is Horizontal
TopMargin | Returns or sets the distance (in points) between the top edge of the page and the top boundary of the body text.
VerticalAlignment | Returns or sets the vertical alignment of text on each page in a document or section.

Public Instance Methods

ClearFormatting Resets page setup to default paper size, margins and orientation.

See Also

PageSetup Class | Aspose.Words Namespace


PageSetup Properties

The properties of the PageSetup class are listed below. For a complete list of PageSetup class members, see the PageSetup Members topic.

Public Instance Properties

Bidi | Specifies that this section contains bidirectional (complex scripts) text.
BorderAlwaysInFront | Specifies where the page border is positioned relative to intersecting texts and objects.
BorderAppliesTo | Specifies which pages the page border is printed on.
BorderDistanceFrom | Gets or sets a value that indicates whether the specified page border is measured from the edge of the page or from the text it surrounds.
Borders | Gets a collection of the page borders.
BorderSurroundsFooter | Specifies whether the page border includes or excludes the footer.
BorderSurroundsHeader | Specifies whether the page border includes or excludes the header.
BottomMargin | Returns or sets the distance (in points) between the bottom edge of the page and the bottom boundary of the body text.
CharactersPerLine | Gets or sets the number of characters per line in the document grid.
DifferentFirstPageHeaderFooter | True if a different header or footer is used on the first page.
EndnoteOptions | Provides options that control numbering and positioning of endnotes in this section.
FirstPageTray | Gets or sets the paper tray (bin) to use for the first page of a section. The value is implementation (printer) specific.
FooterDistance | Returns or sets the distance (in points) between the footer and the bottom of the page.
FootnoteOptions | Provides options that control numbering and positioning of footnotes in this section.
Gutter | Gets or sets the amount of extra space added to the margin for document binding.
HeaderDistance | Returns or sets the distance (in points) between the header and the top of the page.
LayoutMode | Gets or sets the layout mode of this section.
LeftMargin | Returns or sets the distance (in points) between the left edge of the page and the left boundary of the body text.
LineNumberCountBy | Returns or sets the numeric increment for line numbers.
LineNumberDistanceFromText | Gets or sets distance between the right edge of line numbers and the left edge of the document.
LineNumberRestartMode | Gets or sets the way line numbering runs that is, whether it starts over at the beginning of a new page or section or runs continuously.
LinesPerPage | Gets or sets the number of lines per page in the document grid.
LineStartingNumber | Gets or sets the starting line number.
MultiplePages | For multiple page documents, gets or sets how a document is printed or rendered so that it can be bound as a booklet.
OddAndEvenPagesHeaderFooter | True if the document has different headers and footers for odd-numbered and even-numbered pages.
Orientation | Returns or sets the orientation of the page.
OtherPagesTray | Gets or sets the paper tray (bin) to be used for all but the first page of a section. The value is implementation (printer) specific.
PageHeight | Returns or sets the height of the page in points.
PageNumberStyle | Gets or sets the page number format.
PageStartingNumber | Gets or sets the starting page number of the section.
PageWidth | Returns or sets the width of the page in points.
PaperSize | Returns or sets the paper size.
RestartPageNumbering | True if page numbering restarts at the beginning of the section.
RightMargin | Returns or sets the distance (in points) between the right edge of the page and the right boundary of the body text.
RtlGutter | Gets or sets whether Microsoft Word uses gutters for the section based on a right-to-left language or a left-to-right language.
SectionStart | Returns or sets the type of section break for the specified object.
SheetsPerBooklet | Returns or sets the number of pages to be included in each booklet.
SuppressEndnotes | True if endnotes are printed at the end of the next section that doesn't suppress endnotes. Suppressed endnotes are printed before the endnotes in that section.
TextColumns | Returns a collection that represents the set of text columns.
TextOrientation | Allows to specify TextOrientation for the whole page. Default value is Horizontal
TopMargin | Returns or sets the distance (in points) between the top edge of the page and the top boundary of the body text.
VerticalAlignment | Returns or sets the vertical alignment of text on each page in a document or section.

See Also

PageSetup Class | Aspose.Words Namespace


Bidi Property

Aspose.Words

PageSetup.Bidi Property

Specifies that this section contains bidirectional (complex scripts) text.

[Visual Basic]
Public Property Bidi As Boolean
[C#]
public bool Bidi {get; set;}

Remarks

When true, the columns in this section are laid out from right to left.

Example

Shows how to change the order of columns.

[C#]

Document doc = new Document();

PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.TextColumns.SetCount(3);

DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Write("Column 2.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Write("Column 3.");

// Reverse the order of the columns
pageSetup.Bidi = true;

doc.Save(ArtifactsDir + "PageSetup.Bidi.docx");

See Also

PageSetup Class | Aspose.Words Namespace


BorderAlwaysInFront Property

Aspose.Words

PageSetup.BorderAlwaysInFront Property

Specifies where the page border is positioned relative to intersecting texts and objects.

[Visual Basic]
Public Property BorderAlwaysInFront As Boolean
[C#]
public bool BorderAlwaysInFront {get; set;}

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");

See Also

PageSetup Class | Aspose.Words Namespace


BorderAppliesTo Property

Aspose.Words

PageSetup.BorderAppliesTo Property

Specifies which pages the page border is printed on.

[Visual Basic]
Public Property BorderAppliesTo As PageBorderAppliesTo
[C#]
public PageBorderAppliesTo BorderAppliesTo {get; set;}

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");

See Also

PageSetup Class | Aspose.Words Namespace


BorderDistanceFrom Property

Aspose.Words

PageSetup.BorderDistanceFrom Property

Gets or sets a value that indicates whether the specified page border is measured from the edge of the page or from the text it surrounds.

[Visual Basic]
Public Property BorderDistanceFrom As PageBorderDistanceFrom
[C#]
public PageBorderDistanceFrom BorderDistanceFrom {get; set;}

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");

See Also

PageSetup Class | Aspose.Words Namespace


Borders Property

Aspose.Words

PageSetup.Borders Property

Gets a collection of the page borders.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

Example

Creates a fancy looking green wavy page border with a shadow.

[C#]

Document doc = new Document();
PageSetup ps = doc.Sections[0].PageSetup;

ps.Borders.LineStyle = LineStyle.DoubleWave;
ps.Borders.LineWidth = 2;
ps.Borders.Color = Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(ArtifactsDir + "PageSetup.PageBorders.doc");

See Also

PageSetup Class | Aspose.Words Namespace


BorderSurroundsFooter Property

Aspose.Words

PageSetup.BorderSurroundsFooter Property

Specifies whether the page border includes or excludes the footer.

[Visual Basic]
Public Property BorderSurroundsFooter As Boolean
[C#]
public bool BorderSurroundsFooter {get; set;}

Remarks

Note, changing this property affects all sections in the document.

Example

Shows how to apply a border to the page and header/footer.

[C#]

Document doc = new Document();

// Insert header and footer text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header");
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("Footer");
builder.MoveToDocumentEnd();

// Insert a page border and set the color and line style
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.Borders.LineStyle = LineStyle.Double;
pageSetup.Borders.Color = Color.Blue;

// By default, page borders don't surround headers and footers
// We can change that by setting these flags
pageSetup.BorderSurroundsFooter = true;
pageSetup.BorderSurroundsHeader = true;

doc.Save(ArtifactsDir + "PageSetup.BorderSurrounds.docx");

See Also

PageSetup Class | Aspose.Words Namespace


BorderSurroundsHeader Property

Aspose.Words

PageSetup.BorderSurroundsHeader Property

Specifies whether the page border includes or excludes the header.

[Visual Basic]
Public Property BorderSurroundsHeader As Boolean
[C#]
public bool BorderSurroundsHeader {get; set;}

Remarks

Note, changing this property affects all sections in the document.

Example

Shows how to apply a border to the page and header/footer.

[C#]

Document doc = new Document();

// Insert header and footer text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header");
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("Footer");
builder.MoveToDocumentEnd();

// Insert a page border and set the color and line style
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.Borders.LineStyle = LineStyle.Double;
pageSetup.Borders.Color = Color.Blue;

// By default, page borders don't surround headers and footers
// We can change that by setting these flags
pageSetup.BorderSurroundsFooter = true;
pageSetup.BorderSurroundsHeader = true;

doc.Save(ArtifactsDir + "PageSetup.BorderSurrounds.docx");

See Also

PageSetup Class | Aspose.Words Namespace


BottomMargin Property

Aspose.Words

PageSetup.BottomMargin Property

Returns or sets the distance (in points) between the bottom edge of the page and the bottom boundary of the body text.

[Visual Basic]
Public Property BottomMargin As Double
[C#]
public double BottomMargin {get; set;}

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

PageSetup Class | Aspose.Words Namespace


CharactersPerLine Property

Aspose.Words

PageSetup.CharactersPerLine Property

Gets or sets the number of characters per line in the document grid.

[Visual Basic]
Public Property CharactersPerLine As Integer
[C#]
public int CharactersPerLine {get; set;}

Remarks

Minimum value of the property is 1. Maximum value depends on page width and font size of the Normal style. Minimum character pitch is 90 percent of the font size. For example, maximum number of characters per line of a Letter page with one-inch margins is 43.

By default, the property has a value, on which character pitch equals to font size of the Normal style.

Example

Creates headers and footers different for first, even and odd pages using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.DifferentFirstPageHeaderFooter = true;
ps.OddAndEvenPagesHeaderFooter = true;
ps.LayoutMode = SectionLayoutMode.LineGrid;
ps.CharactersPerLine = 1;
ps.LinesPerPage = 1;

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Writeln("First page header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Writeln("Even pages header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Odd pages header.");

// Move back to the main story of the first section.
builder.MoveToSection(0);
builder.Writeln("Text page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 3.");

builder.Document.Save(ArtifactsDir + "PageSetup.DifferentHeaders.doc");

See Also

PageSetup Class | Aspose.Words Namespace


DifferentFirstPageHeaderFooter Property

Aspose.Words

PageSetup.DifferentFirstPageHeaderFooter Property

True if a different header or footer is used on the first page.

[Visual Basic]
Public Property DifferentFirstPageHeaderFooter As Boolean
[C#]
public bool DifferentFirstPageHeaderFooter {get; set;}

Example

Creates headers and footers different for first, even and odd pages using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.DifferentFirstPageHeaderFooter = true;
ps.OddAndEvenPagesHeaderFooter = true;
ps.LayoutMode = SectionLayoutMode.LineGrid;
ps.CharactersPerLine = 1;
ps.LinesPerPage = 1;

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Writeln("First page header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Writeln("Even pages header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Odd pages header.");

// Move back to the main story of the first section.
builder.MoveToSection(0);
builder.Writeln("Text page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 3.");

builder.Document.Save(ArtifactsDir + "PageSetup.DifferentHeaders.doc");
Creates headers and footers in a document using DocumentBuilder.
[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");

See Also

PageSetup Class | Aspose.Words Namespace


EndnoteOptions Property

Aspose.Words

PageSetup.EndnoteOptions Property

Provides options that control numbering and positioning of endnotes in this section.

[Visual Basic]
Public ReadOnly Property EndnoteOptions As EndnoteOptions
[C#]
public EndnoteOptions EndnoteOptions {get;}

Example

Shows how to set options for endnotes in current section

[C#]

Document doc = new Document();

PageSetup pageSetup = doc.Sections[0].PageSetup;

pageSetup.EndnoteOptions.Position = EndnotePosition.EndOfSection;
pageSetup.EndnoteOptions.NumberStyle = NumberStyle.Bullet;
pageSetup.EndnoteOptions.StartNumber = 1;
pageSetup.EndnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;

See Also

PageSetup Class | Aspose.Words Namespace


FirstPageTray Property

Aspose.Words

PageSetup.FirstPageTray Property

Gets or sets the paper tray (bin) to use for the first page of a section. The value is implementation (printer) specific.

[Visual Basic]
Public Property FirstPageTray As Integer
[C#]
public int FirstPageTray {get; set;}

Example

Changes all sections in a document to use the default paper tray of the selected printer.

[C#]

Document doc = new Document();

// Find the printer that will be used for printing this document. In this case it is the default printer.
// You can define a specific printer using PrinterName.
PrinterSettings settings = new PrinterSettings();

// The paper tray value stored in documents is completely printer specific. This means
// The code below resets all page tray values to use the current printers default tray.
// You can enumerate PrinterSettings.PaperSources to find the other valid paper tray values of the selected printer.
foreach (Section section in doc.Sections.OfType<Section>())
{
    section.PageSetup.FirstPageTray = settings.DefaultPageSettings.PaperSource.RawKind;
    section.PageSetup.OtherPagesTray = settings.DefaultPageSettings.PaperSource.RawKind;
}
Shows how to set up printing using different printer trays for different paper sizes.
[C#]

Document doc = new Document();

// Choose the default printer to be used for printing this document.
PrinterSettings settings = new PrinterSettings();

// This is the tray we will use for A4 paper size. This is the first tray in the paper sources collection.
int printerTrayForA4 = settings.PaperSources[0].RawKind;
// The is the tray we will use for Letter paper size. This is the second tray in the paper sources collection.
int printerTrayForLetter = settings.PaperSources[1].RawKind;

// Set the page tray used for each section based off the paper size used in the section.
foreach (Section section in doc.Sections.OfType<Section>())
{
    if (section.PageSetup.PaperSize == Aspose.Words.PaperSize.Letter)
    {
        section.PageSetup.FirstPageTray = printerTrayForLetter;
        section.PageSetup.OtherPagesTray = printerTrayForLetter;
    }
    else if (section.PageSetup.PaperSize == Aspose.Words.PaperSize.A4)
    {
        section.PageSetup.FirstPageTray = printerTrayForA4;
        section.PageSetup.OtherPagesTray = printerTrayForA4;
    }
}

See Also

PageSetup Class | Aspose.Words Namespace


FooterDistance Property

Aspose.Words

PageSetup.FooterDistance Property

Returns or sets the distance (in points) between the footer and the bottom of the page.

[Visual Basic]
Public Property FooterDistance As Double
[C#]
public double FooterDistance {get; set;}

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

PageSetup Class | Aspose.Words Namespace


FootnoteOptions Property

Aspose.Words

PageSetup.FootnoteOptions Property

Provides options that control numbering and positioning of footnotes in this section.

[Visual Basic]
Public ReadOnly Property FootnoteOptions As FootnoteOptions
[C#]
public FootnoteOptions FootnoteOptions {get;}

Example

Shows how to set options for footnotes in current section

[C#]

Document doc = new Document();

PageSetup pageSetup = doc.Sections[0].PageSetup;

pageSetup.FootnoteOptions.Position = FootnotePosition.BottomOfPage;
pageSetup.FootnoteOptions.NumberStyle = NumberStyle.Bullet;
pageSetup.FootnoteOptions.StartNumber = 1;
pageSetup.FootnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;
pageSetup.FootnoteOptions.Columns = 0;

See Also

PageSetup Class | Aspose.Words Namespace


Gutter Property

Aspose.Words

PageSetup.Gutter Property

Gets or sets the amount of extra space added to the margin for document binding.

[Visual Basic]
Public Property Gutter As Double
[C#]
public double Gutter {get; set;}

Example

Shows how to set gutter margins.

[C#]

Document doc = new Document();

// Insert text spanning several pages
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < 6; i++)
{
    builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
    builder.InsertBreak(BreakType.PageBreak);
}

// We can access the gutter margin in the section's page options,
// which is a margin which is added to the page margin at one side of the page
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.Gutter = 100.0;

// If our text is LTR, the gutter will appear on the left side of the page
// Setting this flag will move it to the right side
pageSetup.RtlGutter = true;

// Mirroring the margins will make the gutter alternate in position from page to page
pageSetup.MultiplePages = MultiplePagesType.MirrorMargins;

doc.Save(ArtifactsDir + "PageSetup.Gutter.docx");

See Also

PageSetup Class | Aspose.Words Namespace


HeaderDistance Property

Aspose.Words

PageSetup.HeaderDistance Property

Returns or sets the distance (in points) between the header and the top of the page.

[Visual Basic]
Public Property HeaderDistance As Double
[C#]
public double HeaderDistance {get; set;}

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LayoutMode Property

Aspose.Words

PageSetup.LayoutMode Property

Gets or sets the layout mode of this section.

[Visual Basic]
Public Property LayoutMode As SectionLayoutMode
[C#]
public SectionLayoutMode LayoutMode {get; set;}

Example

Creates headers and footers different for first, even and odd pages using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.DifferentFirstPageHeaderFooter = true;
ps.OddAndEvenPagesHeaderFooter = true;
ps.LayoutMode = SectionLayoutMode.LineGrid;
ps.CharactersPerLine = 1;
ps.LinesPerPage = 1;

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Writeln("First page header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Writeln("Even pages header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Odd pages header.");

// Move back to the main story of the first section.
builder.MoveToSection(0);
builder.Writeln("Text page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 3.");

builder.Document.Save(ArtifactsDir + "PageSetup.DifferentHeaders.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LeftMargin Property

Aspose.Words

PageSetup.LeftMargin Property

Returns or sets the distance (in points) between the left edge of the page and the left boundary of the body text.

[Visual Basic]
Public Property LeftMargin As Double
[C#]
public double LeftMargin {get; set;}

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LineNumberCountBy Property

Aspose.Words

PageSetup.LineNumberCountBy Property

Returns or sets the numeric increment for line numbers.

[Visual Basic]
Public Property LineNumberCountBy As Integer
[C#]
public int LineNumberCountBy {get; set;}

Example

Turns on Microsoft Word line numbering for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.LineStartingNumber = 1;
ps.LineNumberCountBy = 5;
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage;
ps.LineNumberDistanceFromText = 50.0d;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(ArtifactsDir + "PageSetup.LineNumbers.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LineNumberDistanceFromText Property

Aspose.Words

PageSetup.LineNumberDistanceFromText Property

Gets or sets distance between the right edge of line numbers and the left edge of the document.

[Visual Basic]
Public Property LineNumberDistanceFromText As Double
[C#]
public double LineNumberDistanceFromText {get; set;}

Remarks

Set this property to zero for automatic distance between the line numbers and text of the document.

Example

Turns on Microsoft Word line numbering for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.LineStartingNumber = 1;
ps.LineNumberCountBy = 5;
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage;
ps.LineNumberDistanceFromText = 50.0d;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(ArtifactsDir + "PageSetup.LineNumbers.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LineNumberRestartMode Property

Aspose.Words

PageSetup.LineNumberRestartMode Property

Gets or sets the way line numbering runs that is, whether it starts over at the beginning of a new page or section or runs continuously.

[Visual Basic]
Public Property LineNumberRestartMode As LineNumberRestartMode
[C#]
public LineNumberRestartMode LineNumberRestartMode {get; set;}

Example

Turns on Microsoft Word line numbering for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.LineStartingNumber = 1;
ps.LineNumberCountBy = 5;
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage;
ps.LineNumberDistanceFromText = 50.0d;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(ArtifactsDir + "PageSetup.LineNumbers.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LinesPerPage Property

Aspose.Words

PageSetup.LinesPerPage Property

Gets or sets the number of lines per page in the document grid.

[Visual Basic]
Public Property LinesPerPage As Integer
[C#]
public int LinesPerPage {get; set;}

Remarks

Minimum value of the property is 1. Maximum value depends on page height and font size of the Normal style. Minimum line pitch is 136 percent of the font size. For example, maximum number of lines per page of a Letter page with one-inch margins is 39.

By default, the property has a value, on which line pitch is in 1.5 times greater than font size of the Normal style.

Example

Creates headers and footers different for first, even and odd pages using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.DifferentFirstPageHeaderFooter = true;
ps.OddAndEvenPagesHeaderFooter = true;
ps.LayoutMode = SectionLayoutMode.LineGrid;
ps.CharactersPerLine = 1;
ps.LinesPerPage = 1;

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Writeln("First page header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Writeln("Even pages header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Odd pages header.");

// Move back to the main story of the first section.
builder.MoveToSection(0);
builder.Writeln("Text page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 3.");

builder.Document.Save(ArtifactsDir + "PageSetup.DifferentHeaders.doc");

See Also

PageSetup Class | Aspose.Words Namespace


LineStartingNumber Property

Aspose.Words

PageSetup.LineStartingNumber Property

Gets or sets the starting line number.

[Visual Basic]
Public Property LineStartingNumber As Integer
[C#]
public int LineStartingNumber {get; set;}

Example

Turns on Microsoft Word line numbering for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.LineStartingNumber = 1;
ps.LineNumberCountBy = 5;
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage;
ps.LineNumberDistanceFromText = 50.0d;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(ArtifactsDir + "PageSetup.LineNumbers.doc");

See Also

PageSetup Class | Aspose.Words Namespace


MultiplePages Property

Aspose.Words

PageSetup.MultiplePages Property

For multiple page documents, gets or sets how a document is printed or rendered so that it can be bound as a booklet.

[Visual Basic]
Public Property MultiplePages As MultiplePagesType
[C#]
public MultiplePagesType MultiplePages {get; set;}

Example

Shows how to set gutter margins.

[C#]

Document doc = new Document();

// Insert text spanning several pages
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < 6; i++)
{
    builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
    builder.InsertBreak(BreakType.PageBreak);
}

// We can access the gutter margin in the section's page options,
// which is a margin which is added to the page margin at one side of the page
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.Gutter = 100.0;

// If our text is LTR, the gutter will appear on the left side of the page
// Setting this flag will move it to the right side
pageSetup.RtlGutter = true;

// Mirroring the margins will make the gutter alternate in position from page to page
pageSetup.MultiplePages = MultiplePagesType.MirrorMargins;

doc.Save(ArtifactsDir + "PageSetup.Gutter.docx");

See Also

PageSetup Class | Aspose.Words Namespace


OddAndEvenPagesHeaderFooter Property

Aspose.Words

PageSetup.OddAndEvenPagesHeaderFooter Property

True if the document has different headers and footers for odd-numbered and even-numbered pages.

[Visual Basic]
Public Property OddAndEvenPagesHeaderFooter As Boolean
[C#]
public bool OddAndEvenPagesHeaderFooter {get; set;}

Remarks

Note, changing this property affects all sections in the document.

Example

Creates headers and footers different for first, even and odd pages using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.DifferentFirstPageHeaderFooter = true;
ps.OddAndEvenPagesHeaderFooter = true;
ps.LayoutMode = SectionLayoutMode.LineGrid;
ps.CharactersPerLine = 1;
ps.LinesPerPage = 1;

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Writeln("First page header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Writeln("Even pages header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Odd pages header.");

// Move back to the main story of the first section.
builder.MoveToSection(0);
builder.Writeln("Text page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 3.");

builder.Document.Save(ArtifactsDir + "PageSetup.DifferentHeaders.doc");
Creates headers and footers in a document using DocumentBuilder.
[C#]

// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;

// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");

// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");

doc.Save(ArtifactsDir + "DocumentBuilder.HeadersAndFooters.doc");

See Also

PageSetup Class | Aspose.Words Namespace


Orientation Property

Aspose.Words

PageSetup.Orientation Property

Returns or sets the orientation of the page.

[Visual Basic]
Public Property Orientation As Orientation
[C#]
public Orientation Orientation {get; set;}

Remarks

Changing Orientation swaps PageWidth and PageHeight.

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");
Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.
[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

See Also

PageSetup Class | Aspose.Words Namespace


OtherPagesTray Property

Aspose.Words

PageSetup.OtherPagesTray Property

Gets or sets the paper tray (bin) to be used for all but the first page of a section. The value is implementation (printer) specific.

[Visual Basic]
Public Property OtherPagesTray As Integer
[C#]
public int OtherPagesTray {get; set;}

Example

Changes all sections in a document to use the default paper tray of the selected printer.

[C#]

Document doc = new Document();

// Find the printer that will be used for printing this document. In this case it is the default printer.
// You can define a specific printer using PrinterName.
PrinterSettings settings = new PrinterSettings();

// The paper tray value stored in documents is completely printer specific. This means
// The code below resets all page tray values to use the current printers default tray.
// You can enumerate PrinterSettings.PaperSources to find the other valid paper tray values of the selected printer.
foreach (Section section in doc.Sections.OfType<Section>())
{
    section.PageSetup.FirstPageTray = settings.DefaultPageSettings.PaperSource.RawKind;
    section.PageSetup.OtherPagesTray = settings.DefaultPageSettings.PaperSource.RawKind;
}
Shows how to set up printing using different printer trays for different paper sizes.
[C#]

Document doc = new Document();

// Choose the default printer to be used for printing this document.
PrinterSettings settings = new PrinterSettings();

// This is the tray we will use for A4 paper size. This is the first tray in the paper sources collection.
int printerTrayForA4 = settings.PaperSources[0].RawKind;
// The is the tray we will use for Letter paper size. This is the second tray in the paper sources collection.
int printerTrayForLetter = settings.PaperSources[1].RawKind;

// Set the page tray used for each section based off the paper size used in the section.
foreach (Section section in doc.Sections.OfType<Section>())
{
    if (section.PageSetup.PaperSize == Aspose.Words.PaperSize.Letter)
    {
        section.PageSetup.FirstPageTray = printerTrayForLetter;
        section.PageSetup.OtherPagesTray = printerTrayForLetter;
    }
    else if (section.PageSetup.PaperSize == Aspose.Words.PaperSize.A4)
    {
        section.PageSetup.FirstPageTray = printerTrayForA4;
        section.PageSetup.OtherPagesTray = printerTrayForA4;
    }
}

See Also

PageSetup Class | Aspose.Words Namespace


PageHeight Property

Aspose.Words

PageSetup.PageHeight Property

Returns or sets the height of the page in points.

[Visual Basic]
Public Property PageHeight As Double
[C#]
public double PageHeight {get; set;}

Example

Inserts a watermark image into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");

See Also

PageSetup Class | Aspose.Words Namespace


PageNumberStyle Property

Aspose.Words

PageSetup.PageNumberStyle Property

Gets or sets the page number format.

[Visual Basic]
Public Property PageNumberStyle As NumberStyle
[C#]
public NumberStyle PageNumberStyle {get; set;}

Example

Shows how to control page numbering per section.

[C#]

// This document has two sections, but no page numbers yet.
Document doc = new Document(MyDir + "PageSetup.PageNumbering.doc");

// Use document builder to create a header with a page number field for the first section.
// The page number will look like "Page V".
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToSection(0);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Page ");
builder.InsertField("PAGE", "");

// Set first section page numbering.
Section section = doc.Sections[0];
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageStartingNumber = 5;
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman;

// Create a header for the section.
// The page number will look like " - 10 - ".
builder.MoveToSection(1);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write(" - ");
builder.InsertField("PAGE", "");
builder.Write(" - ");

// Set second section page numbering.
section = doc.Sections[1];
section.PageSetup.PageStartingNumber = 10;
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageNumberStyle = NumberStyle.Arabic;

doc.Save(ArtifactsDir + "PageSetup.PageNumbering.doc");

See Also

PageSetup Class | Aspose.Words Namespace


PageStartingNumber Property

Aspose.Words

PageSetup.PageStartingNumber Property

Gets or sets the starting page number of the section.

[Visual Basic]
Public Property PageStartingNumber As Integer
[C#]
public int PageStartingNumber {get; set;}

Remarks

The RestartPageNumbering property, if set to false, will override the PageStartingNumber property so that page numbering can continue from the previous section.

Example

Shows how to control page numbering per section.

[C#]

// This document has two sections, but no page numbers yet.
Document doc = new Document(MyDir + "PageSetup.PageNumbering.doc");

// Use document builder to create a header with a page number field for the first section.
// The page number will look like "Page V".
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToSection(0);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Page ");
builder.InsertField("PAGE", "");

// Set first section page numbering.
Section section = doc.Sections[0];
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageStartingNumber = 5;
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman;

// Create a header for the section.
// The page number will look like " - 10 - ".
builder.MoveToSection(1);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write(" - ");
builder.InsertField("PAGE", "");
builder.Write(" - ");

// Set second section page numbering.
section = doc.Sections[1];
section.PageSetup.PageStartingNumber = 10;
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageNumberStyle = NumberStyle.Arabic;

doc.Save(ArtifactsDir + "PageSetup.PageNumbering.doc");

See Also

PageSetup Class | Aspose.Words Namespace


PageWidth Property

Aspose.Words

PageSetup.PageWidth Property

Returns or sets the width of the page in points.

[Visual Basic]
Public Property PageWidth As Double
[C#]
public double PageWidth {get; set;}

Example

Inserts a watermark image into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");
Shows how to insert a floating image and specify its position and size.
[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

PageSetup Class | Aspose.Words Namespace


PaperSize Property

Aspose.Words

PageSetup.PaperSize Property

Returns or sets the paper size.

[Visual Basic]
Public Property PaperSize As PaperSize
[C#]
public PaperSize PaperSize {get; set;}

Remarks

Setting this property updates PageWidth and PageHeight values. Setting this value to Custom does not change existing values.

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

PageSetup Class | Aspose.Words Namespace


RestartPageNumbering Property

Aspose.Words

PageSetup.RestartPageNumbering Property

True if page numbering restarts at the beginning of the section.

[Visual Basic]
Public Property RestartPageNumbering As Boolean
[C#]
public bool RestartPageNumbering {get; set;}

Remarks

If set to false, the RestartPageNumbering property will override the PageStartingNumber property so that page numbering can continue from the previous section.

Example

Shows how to control page numbering per section.

[C#]

// This document has two sections, but no page numbers yet.
Document doc = new Document(MyDir + "PageSetup.PageNumbering.doc");

// Use document builder to create a header with a page number field for the first section.
// The page number will look like "Page V".
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToSection(0);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Page ");
builder.InsertField("PAGE", "");

// Set first section page numbering.
Section section = doc.Sections[0];
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageStartingNumber = 5;
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman;

// Create a header for the section.
// The page number will look like " - 10 - ".
builder.MoveToSection(1);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write(" - ");
builder.InsertField("PAGE", "");
builder.Write(" - ");

// Set second section page numbering.
section = doc.Sections[1];
section.PageSetup.PageStartingNumber = 10;
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageNumberStyle = NumberStyle.Arabic;

doc.Save(ArtifactsDir + "PageSetup.PageNumbering.doc");

See Also

PageSetup Class | Aspose.Words Namespace


RightMargin Property

Aspose.Words

PageSetup.RightMargin Property

Returns or sets the distance (in points) between the right edge of the page and the right boundary of the body text.

[Visual Basic]
Public Property RightMargin As Double
[C#]
public double RightMargin {get; set;}

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

PageSetup Class | Aspose.Words Namespace


RtlGutter Property

Aspose.Words

PageSetup.RtlGutter Property

Gets or sets whether Microsoft Word uses gutters for the section based on a right-to-left language or a left-to-right language.

[Visual Basic]
Public Property RtlGutter As Boolean
[C#]
public bool RtlGutter {get; set;}

Example

Shows how to set gutter margins.

[C#]

Document doc = new Document();

// Insert text spanning several pages
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < 6; i++)
{
    builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
    builder.InsertBreak(BreakType.PageBreak);
}

// We can access the gutter margin in the section's page options,
// which is a margin which is added to the page margin at one side of the page
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.Gutter = 100.0;

// If our text is LTR, the gutter will appear on the left side of the page
// Setting this flag will move it to the right side
pageSetup.RtlGutter = true;

// Mirroring the margins will make the gutter alternate in position from page to page
pageSetup.MultiplePages = MultiplePagesType.MirrorMargins;

doc.Save(ArtifactsDir + "PageSetup.Gutter.docx");

See Also

PageSetup Class | Aspose.Words Namespace


SectionStart Property

Aspose.Words

PageSetup.SectionStart Property

Returns or sets the type of section break for the specified object.

[Visual Basic]
Public Property SectionStart As SectionStart
[C#]
public SectionStart SectionStart {get; set;}

Example

Specifies how the section starts, from a new page, on the same page or other.

[C#]

Document doc = new Document();
doc.Sections[0].PageSetup.SectionStart = Aspose.Words.SectionStart.Continuous;
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

PageSetup Class | Aspose.Words Namespace


SheetsPerBooklet Property

Aspose.Words

PageSetup.SheetsPerBooklet Property

Returns or sets the number of pages to be included in each booklet.

[Visual Basic]
Public Property SheetsPerBooklet As Integer
[C#]
public int SheetsPerBooklet {get; set;}

Example

Shows how to create a booklet.

[C#]

Document doc = new Document();

// Use a document builder to create 16 pages of content that will be compiled in a booklet
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("My Booklet:");

for (int i = 0; i < 15; i++)
{
    builder.InsertBreak(BreakType.PageBreak);
    builder.Write($"Booklet face #{i}");
}

// Set the number of sheets that will be used by the printer to create the booklet
// After being printed on both sides, the sheets can be stacked and folded down the centre
// The contents that we placed in such a way that they will be in order once the booklet is folded
// We can only specify the number of sheets in multiples of 4
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.MultiplePages = MultiplePagesType.BookFoldPrinting;
pageSetup.SheetsPerBooklet = 4;

doc.Save(ArtifactsDir + "PageSetup.Booklet.docx");

See Also

PageSetup Class | Aspose.Words Namespace


SuppressEndnotes Property

Aspose.Words

PageSetup.SuppressEndnotes Property

True if endnotes are printed at the end of the next section that doesn't suppress endnotes. Suppressed endnotes are printed before the endnotes in that section.

[Visual Basic]
Public Property SuppressEndnotes As Boolean
[C#]
public bool SuppressEndnotes {get; set;}

Example

Shows how to store endnotes at the end of each section instead of the document and manipulate their positions.

[C#]

public void SuppressEndnotes()
{
    // Create a new document and make it empty
    Document doc = new Document();
    doc.RemoveAllChildren();

    // Normally endnotes are all stored at the end of a document, but this option lets us store them at the end of each section
    doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;

    // Create 3 new sections, each having a paragraph and an endnote at the end
    InsertSection(doc, "Section 1", "Endnote 1, will stay in section 1");
    InsertSection(doc, "Section 2", "Endnote 2, will be pushed down to section 3");
    InsertSection(doc, "Section 3", "Endnote 3, will stay in section 3");

    // Each section contains its own page setup object
    // Setting this value will push this section's endnotes down to the next section
    PageSetup pageSetup = doc.Sections[1].PageSetup;
    pageSetup.SuppressEndnotes = true;

    doc.Save(ArtifactsDir + "PageSetup.SuppressEndnotes.docx");
}

/// <summary>
/// Add a section to the end of a document, give it a body and a paragraph, then add text and an endnote to that paragraph
/// </summary>
private void InsertSection(Document doc, string sectionBodyText, string endnoteText)
{
    Section section = new Section(doc);

    doc.AppendChild(section);

    Body body = new Body(doc);
    section.AppendChild(body);

    Assert.AreEqual(section, body.ParentNode);

    Paragraph para = new Paragraph(doc);
    body.AppendChild(para);

    Assert.AreEqual(body, para.ParentNode);

    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.MoveTo(para);
    builder.Write(sectionBodyText);
    builder.InsertFootnote(FootnoteType.Endnote, endnoteText);
}

See Also

PageSetup Class | Aspose.Words Namespace


TextColumns Property

Aspose.Words

PageSetup.TextColumns Property

Returns a collection that represents the set of text columns.

[Visual Basic]
Public ReadOnly Property TextColumns As TextColumnCollection
[C#]
public TextColumnCollection TextColumns {get;}

Example

Creates multiple evenly spaced columns in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Make spacing between columns wider.
columns.Spacing = 100;
// This creates two columns of equal width.
columns.SetCount(2);

builder.Writeln("Text in column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Text in column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsSameWidth.doc");

See Also

PageSetup Class | Aspose.Words Namespace


TextOrientation Property

Aspose.Words

PageSetup.TextOrientation Property

Allows to specify TextOrientation for the whole page. Default value is Horizontal

[Visual Basic]
Public Property TextOrientation As TextOrientation
[C#]
public TextOrientation TextOrientation {get; set;}

Remarks

This property is only supported for MS Word native formats DOCX, WML, RTF and DOC.

Example

Shows how to set text orientation.

[C#]

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello world!");

// Setting this value will rotate the section's text 90 degrees to the right
PageSetup pageSetup = doc.Sections[0].PageSetup;
pageSetup.TextOrientation = Aspose.Words.TextOrientation.Upward;

doc.Save(ArtifactsDir + "PageSetup.TextOrientation.docx");

See Also

PageSetup Class | Aspose.Words Namespace


TopMargin Property

Aspose.Words

PageSetup.TopMargin Property

Returns or sets the distance (in points) between the top edge of the page and the top boundary of the body text.

[Visual Basic]
Public Property TopMargin As Double
[C#]
public double TopMargin {get; set;}

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");

See Also

PageSetup Class | Aspose.Words Namespace


VerticalAlignment Property

Aspose.Words

PageSetup.VerticalAlignment Property

Returns or sets the vertical alignment of text on each page in a document or section.

[Visual Basic]
Public Property VerticalAlignment As PageVerticalAlignment
[C#]
public PageVerticalAlignment VerticalAlignment {get; set;}

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

See Also

PageSetup Class | Aspose.Words Namespace


PageSetup Methods

The methods of the PageSetup class are listed below. For a complete list of PageSetup class members, see the PageSetup Members topic.

Public Instance Methods

ClearFormatting Resets page setup to default paper size, margins and orientation.

See Also

PageSetup Class | Aspose.Words Namespace


PageSetup.ClearFormatting Method

Resets page setup to default paper size, margins and orientation.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

See Also

PageSetup Class | Aspose.Words Namespace


PageVerticalAlignment Enumeration

Specifies vertical justification of text on each page.

[Visual Basic]
Public Enum PageVerticalAlignment
[C#]
public enum PageVerticalAlignment

Remarks

Example

Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Modify the first section in the document.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("Section 1, landscape oriented and text vertically centered.");

// Start a new section and reset its formatting to defaults.
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.PageSetup.ClearFormatting();
builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");

builder.Document.Save(ArtifactsDir + "PageSetup.ClearFormatting.doc");

Members

Member Name | Description | Value
Bottom | Text is aligned at the bottom of the page. | 3
Center | Text is aligned in the middle of the page. | 1
Justify | Text is spread to fill the page. | 2
Top | Text is aligned at the top of the page. | 0

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | PageSetup | VerticalAlignment


PaperSize Enumeration

Specifies paper size.

[Visual Basic]
Public Enum PaperSize
[C#]
public enum PaperSize

Example

Specifies paper size, orientation, margins and other settings for a section.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.PaperSize = Aspose.Words.PaperSize.Legal;
ps.Orientation = Orientation.Landscape;
ps.TopMargin = ConvertUtil.InchToPoint(1.0);
ps.BottomMargin = ConvertUtil.InchToPoint(1.0);
ps.LeftMargin = ConvertUtil.InchToPoint(1.5);
ps.RightMargin = ConvertUtil.InchToPoint(1.5);
ps.HeaderDistance = ConvertUtil.InchToPoint(0.2);
ps.FooterDistance = ConvertUtil.InchToPoint(0.2);

builder.Writeln("Hello world.");

builder.Document.Save(ArtifactsDir + "PageSetup.PageMargins.doc");
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Members

Member Name | Description | Value
A3 | 297 x 420 mm. | 0
A4 | 210 x 297 mm. | 1
A5 | 148 x 210 mm. | 2
B4 | 250 x 353 mm. | 3
B5 | 176 x 250 mm. | 4
Executive | 7.25 x 10.5 inches. | 5
Folio | 8 x 13 inches. | 6
Ledger | 11 x 17 inches. | 7
Legal | 8.5 x 14 inches. | 8
Letter | 8.5 x 11 inches. | 9
EnvelopeDL | 110 x 220 mm. | 10
Quarto | 8 x 10 inches. | 11
Statement | 8.5 x 5.5 inches. | 12
Tabloid | 11 x 17 inches. | 13
Paper10x14 | 10 x 14 inches. | 14
Paper11x17 | 11 x 17 inches. | 15
Custom | Custom paper size. | 16

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Paragraph Class

Represents a paragraph of text.

For a list of all members of this type, see Paragraph Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Paragraph

[Visual Basic]
Public Class Paragraph
Inherits CompositeNode
[C#]
public class Paragraph : CompositeNode

Remarks

Paragraph is a block-level node and can be a child of classes derived from Story or InlineStory.

Paragraph can contain any number of inline-level nodes and bookmarks.

The complete list of child nodes that can occur inside a paragraph consists of BookmarkStart, BookmarkEnd, FieldStart, FieldSeparator, FieldEnd, FormField, Comment, Footnote, Run, SpecialChar, Shape, GroupShape, SmartTag.

A valid paragraph in Microsoft Word always ends with a paragraph break character and a minimal valid paragraph consists just of a paragraph break. The Paragraph class automatically appends the appropriate paragraph break character at the end and this character is not part of the child nodes of the Paragraph, therefore a Paragraph can be empty.

Do not include the end of paragraph ControlChar.ParagraphBreak or end of cell ControlChar.Cell characters inside the text of the paragraph as it might make the paragraph invalid when the document is opened in Microsoft Word.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Paragraph Members | Aspose.Words Namespace


Paragraph Members

Paragraph overview

Public Instance Constructors

Paragraph Constructor Initializes a new instance of the Paragraph class.

Public Instance Properties

BreakIsStyleSeparator | True if this paragraph break is a Style Separator. A style separator allows one paragraph to consist of parts that have different paragraph styles.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FrameFormat | Provides access to the paragraph formatting properties.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsEndOfCell | True if this paragraph is the last paragraph in a Cell; false otherwise.
IsEndOfDocument | True if this paragraph is the last paragraph in the last section of the document.
IsEndOfHeaderFooter | True if this paragraph is the last paragraph in the HeaderFooter (main text story) of a Section; false otherwise.
IsEndOfSection | True if this paragraph is the last paragraph in the Body (main text story) of a Section; false otherwise.
IsFormatRevision | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInCell | True if this paragraph is an immediate child of Cell; false otherwise.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsListItem | True when the paragraph is an item in a bulleted or numbered list in original revision.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
ListFormat | Provides access to the list formatting properties of the paragraph.
ListLabel | Gets a ListLabel object that provides access to list numbering value and formatting for this paragraph.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Paragraph.
ParagraphBreakFont | Provides access to the font formatting of the paragraph break character.
ParagraphFormat | Provides access to the paragraph formatting properties.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentSection | Retrieves the parent Section of the paragraph.
ParentStory | Retrieves the parent section-level story that can be Body or HeaderFooter.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Runs | Provides access to the typed collection of pieces of text inside the paragraph.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendField | Overloaded. Appends a Word field to this paragraph.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEffectiveTabStops | Returns array of all tab stops applied to this paragraph, including applied indirectly by styles or lists.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText | Gets the text of this paragraph including the end of paragraph character.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
InsertField | Overloaded. Inserts a Word field into this paragraph.
JoinRunsWithSameFormatting | Joins runs with the same formatting in the paragraph.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph Constructor

Initializes a new instance of the Paragraph class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Paragraph(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Paragraph is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Paragraph to the document use InsertAfter or InsertBefore on the story where you want the paragraph inserted.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph Properties

The properties of the Paragraph class are listed below. For a complete list of Paragraph class members, see the Paragraph Members topic.

Public Instance Properties

BreakIsStyleSeparator | True if this paragraph break is a Style Separator. A style separator allows one paragraph to consist of parts that have different paragraph styles.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FrameFormat | Provides access to the paragraph formatting properties.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsEndOfCell | True if this paragraph is the last paragraph in a Cell; false otherwise.
IsEndOfDocument | True if this paragraph is the last paragraph in the last section of the document.
IsEndOfHeaderFooter | True if this paragraph is the last paragraph in the HeaderFooter (main text story) of a Section; false otherwise.
IsEndOfSection | True if this paragraph is the last paragraph in the Body (main text story) of a Section; false otherwise.
IsFormatRevision | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInCell | True if this paragraph is an immediate child of Cell; false otherwise.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsListItem | True when the paragraph is an item in a bulleted or numbered list in original revision.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
ListFormat | Provides access to the list formatting properties of the paragraph.
ListLabel | Gets a ListLabel object that provides access to list numbering value and formatting for this paragraph.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Paragraph.
ParagraphBreakFont | Provides access to the font formatting of the paragraph break character.
ParagraphFormat | Provides access to the paragraph formatting properties.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentSection | Retrieves the parent Section of the paragraph.
ParentStory | Retrieves the parent section-level story that can be Body or HeaderFooter.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Runs | Provides access to the typed collection of pieces of text inside the paragraph.

See Also

Paragraph Class | Aspose.Words Namespace


BreakIsStyleSeparator Property

Aspose.Words

Paragraph.BreakIsStyleSeparator Property

True if this paragraph break is a Style Separator. A style separator allows one paragraph to consist of parts that have different paragraph styles.

[Visual Basic]
Public ReadOnly Property BreakIsStyleSeparator As Boolean
[C#]
public bool BreakIsStyleSeparator {get;}

Example

Shows how to check if paragraph break is a Style Separator

[C#]

Document doc = new Document(MyDir + "Paragraph.BreakIsStyleSeparator.docx");

Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
if (paragraph.BreakIsStyleSeparator)
{
    // Do something ...
}

See Also

Paragraph Class | Aspose.Words Namespace


FrameFormat Property

Aspose.Words

Paragraph.FrameFormat Property

Provides access to the paragraph formatting properties.

[Visual Basic]
Public ReadOnly Property FrameFormat As FrameFormat
[C#]
public FrameFormat FrameFormat {get;}

Example

Shows how to get information about formatting properties of paragraph as frame.

[C#]

Document doc = new Document(MyDir + "Paragraph.Frame.docx");

ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

foreach (Paragraph paragraph in paragraphs.OfType<Paragraph>())
{
    if (paragraph.FrameFormat.IsFrame)
    {
        Console.WriteLine("Width: " + paragraph.FrameFormat.Width);
        Console.WriteLine("Height: " + paragraph.FrameFormat.Height);
        Console.WriteLine("HeightRule: " + paragraph.FrameFormat.HeightRule);
        Console.WriteLine("HorizontalAlignment: " + paragraph.FrameFormat.HorizontalAlignment);
        Console.WriteLine("VerticalAlignment: " + paragraph.FrameFormat.VerticalAlignment);
        Console.WriteLine("HorizontalPosition: " + paragraph.FrameFormat.HorizontalPosition);
        Console.WriteLine("RelativeHorizontalPosition: " +
                          paragraph.FrameFormat.RelativeHorizontalPosition);
        Console.WriteLine("HorizontalDistanceFromText: " +
                          paragraph.FrameFormat.HorizontalDistanceFromText);
        Console.WriteLine("VerticalPosition: " + paragraph.FrameFormat.VerticalPosition);
        Console.WriteLine("RelativeVerticalPosition: " + paragraph.FrameFormat.RelativeVerticalPosition);
        Console.WriteLine("VerticalDistanceFromText: " + paragraph.FrameFormat.VerticalDistanceFromText);
    }
}

See Also

Paragraph Class | Aspose.Words Namespace


IsDeleteRevision Property

Aspose.Words

Paragraph.IsDeleteRevision Property

Returns true if this object was deleted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsDeleteRevision As Boolean
[C#]
public bool IsDeleteRevision {get;}

See Also

Paragraph Class | Aspose.Words Namespace


IsEndOfCell Property

Aspose.Words

Paragraph.IsEndOfCell Property

True if this paragraph is the last paragraph in a Cell; false otherwise.

[Visual Basic]
Public ReadOnly Property IsEndOfCell As Boolean
[C#]
public bool IsEndOfCell {get;}

Example

Shows how to set a table to stay together on the same page.

[C#]

// To keep a table from breaking across a page we need to enable KeepWithNext
// for every paragraph in the table except for the last paragraphs in the last
// row of the table.
foreach (Cell cell in table.GetChildNodes(NodeType.Cell, true).OfType<Cell>())
foreach (Paragraph para in cell.Paragraphs.OfType<Paragraph>())
    if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
        para.ParagraphFormat.KeepWithNext = true;

See Also

Paragraph Class | Aspose.Words Namespace


IsEndOfDocument Property

Aspose.Words

Paragraph.IsEndOfDocument Property

True if this paragraph is the last paragraph in the last section of the document.

[Visual Basic]
Public ReadOnly Property IsEndOfDocument As Boolean
[C#]
public bool IsEndOfDocument {get;}

See Also

Paragraph Class | Aspose.Words Namespace


IsEndOfHeaderFooter Property

Aspose.Words

Paragraph.IsEndOfHeaderFooter Property

True if this paragraph is the last paragraph in the HeaderFooter (main text story) of a Section; false otherwise.

[Visual Basic]
Public ReadOnly Property IsEndOfHeaderFooter As Boolean
[C#]
public bool IsEndOfHeaderFooter {get;}

See Also

Paragraph Class | Aspose.Words Namespace


IsEndOfSection Property

Aspose.Words

Paragraph.IsEndOfSection Property

True if this paragraph is the last paragraph in the Body (main text story) of a Section; false otherwise.

[Visual Basic]
Public ReadOnly Property IsEndOfSection As Boolean
[C#]
public bool IsEndOfSection {get;}

Example

This is a method that inserts contents of one document at a specified location in another document.

[C#]

/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
    // Make sure that the node is either a paragraph or table.
    if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
        (!insertAfterNode.NodeType.Equals(NodeType.Table)))
        throw new ArgumentException("The destination node should be either a paragraph or table.");

    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;

    // This object will be translating styles and lists during the import.
    NodeImporter importer =
        new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

    // Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections.OfType<Section>())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.NodeType.Equals(NodeType.Paragraph))
            {
                Paragraph para = (Paragraph) srcNode;
                if (para.IsEndOfSection && !para.HasChildNodes)
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }
}

See Also

Paragraph Class | Aspose.Words Namespace


IsFormatRevision Property

Aspose.Words

Paragraph.IsFormatRevision Property

Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsFormatRevision As Boolean
[C#]
public bool IsFormatRevision {get;}

Example

Shows how to get information about whether this object was formatted in Microsoft Word while change tracking was enabled

[C#]

Document doc = new Document(MyDir + "Paragraph.IsFormatRevision.docx");

Paragraph firstParagraph = DocumentHelper.GetParagraph(doc, 0);
Assert.IsTrue(firstParagraph.IsFormatRevision);

See Also

Paragraph Class | Aspose.Words Namespace


IsInCell Property

Aspose.Words

Paragraph.IsInCell Property

True if this paragraph is an immediate child of Cell; false otherwise.

[Visual Basic]
Public ReadOnly Property IsInCell As Boolean
[C#]
public bool IsInCell {get;}

See Also

Paragraph Class | Aspose.Words Namespace


IsInsertRevision Property

Aspose.Words

Paragraph.IsInsertRevision Property

Returns true if this object was inserted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsInsertRevision As Boolean
[C#]
public bool IsInsertRevision {get;}

See Also

Paragraph Class | Aspose.Words Namespace


IsListItem Property

Aspose.Words

Paragraph.IsListItem Property

True when the paragraph is an item in a bulleted or numbered list in original revision.

[Visual Basic]
Public ReadOnly Property IsListItem As Boolean
[C#]
public bool IsListItem {get;}

See Also

Paragraph Class | Aspose.Words Namespace


IsMoveFromRevision Property

Aspose.Words

Paragraph.IsMoveFromRevision Property

Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveFromRevision As Boolean
[C#]
public bool IsMoveFromRevision {get;}

Example

Shows how to get paragraph that was moved (deleted/inserted) in Microsoft Word while change tracking was enabled.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");
ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

// There are two sets of move revisions in this document
// One moves a small part of a paragraph, while the other moves a whole paragraph
// Paragraph.IsMoveFromRevision/IsMoveToRevision will only be true if a whole paragraph is moved, as in the latter case
for (int i = 0; i < paragraphs.Count; i++)
{
    if (paragraphs[i].IsMoveFromRevision)
        Console.WriteLine("The paragraph {0} has been moved (deleted).", i);
    if (paragraphs[i].IsMoveToRevision)
        Console.WriteLine("The paragraph {0} has been moved (inserted).", i);
}

See Also

Paragraph Class | Aspose.Words Namespace


IsMoveToRevision Property

Aspose.Words

Paragraph.IsMoveToRevision Property

Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveToRevision As Boolean
[C#]
public bool IsMoveToRevision {get;}

Example

Shows how to get paragraph that was moved (deleted/inserted) in Microsoft Word while change tracking was enabled.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");
ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;

// There are two sets of move revisions in this document
// One moves a small part of a paragraph, while the other moves a whole paragraph
// Paragraph.IsMoveFromRevision/IsMoveToRevision will only be true if a whole paragraph is moved, as in the latter case
for (int i = 0; i < paragraphs.Count; i++)
{
    if (paragraphs[i].IsMoveFromRevision)
        Console.WriteLine("The paragraph {0} has been moved (deleted).", i);
    if (paragraphs[i].IsMoveToRevision)
        Console.WriteLine("The paragraph {0} has been moved (inserted).", i);
}

See Also

Paragraph Class | Aspose.Words Namespace


ListFormat Property

Aspose.Words

Paragraph.ListFormat Property

Provides access to the list formatting properties of the paragraph.

[Visual Basic]
Public ReadOnly Property ListFormat As ListFormat
[C#]
public ListFormat ListFormat {get;}

Example

Removes bullets and numbering from all paragraphs in the main text of a section.

[C#]

Body body = doc.FirstSection.Body;

foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
    paragraph.ListFormat.RemoveNumbers();
Applies list formatting of an existing list to a collection of paragraphs.
[C#]

Body body = doc.FirstSection.Body;
List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
Creates new list formatting and applies it to a collection of paragraphs.
[C#]

List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

Body body = doc.FirstSection.Body;
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 1;
}
Finds and outputs all paragraphs in a document that are bulleted or numbered.
[C#]

NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph para in paras.OfType<Paragraph>())
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}",
            para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}

See Also

Paragraph Class | Aspose.Words Namespace


ListLabel Property

Aspose.Words

Paragraph.ListLabel Property

Gets a ListLabel object that provides access to list numbering value and formatting for this paragraph.

[Visual Basic]
Public ReadOnly Property ListLabel As ListLabel
[C#]
public ListLabel ListLabel {get;}

Example

Shows how to extract the label of each paragraph in a list as a value or a String.

[C#]

Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
doc.UpdateListLabels();
int listParaCount = 1;

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
    // which start at three and ends at six.
    if (paragraph.ListFormat.IsListItem)
    {
        Console.WriteLine("Paragraph #{0}", listParaCount);

        // This is the text we get when actually getting when we output this node to text format.
        // The list labels are not included in this text output. Trim any paragraph formatting characters.
        String paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
        Console.WriteLine("Exported Text: " + paragraphText);

        ListLabel label = paragraph.ListLabel;
        // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
        // will tell us what position it is on that particular level.
        Console.WriteLine("Numerical Id: " + label.LabelValue);

        // Combine them together to include the list label with the text in the output.
        Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

        listParaCount++;
    }
}

See Also

Paragraph Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Paragraph.NodeType Property

Returns NodeType.Paragraph.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Paragraph Class | Aspose.Words Namespace


ParagraphBreakFont Property

Aspose.Words

Paragraph.ParagraphBreakFont Property

Provides access to the font formatting of the paragraph break character.

[Visual Basic]
Public ReadOnly Property ParagraphBreakFont As Font
[C#]
public Font ParagraphBreakFont {get;}

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

Paragraph Class | Aspose.Words Namespace


ParagraphFormat Property

Aspose.Words

Paragraph.ParagraphFormat Property

Provides access to the paragraph formatting properties.

[Visual Basic]
Public ReadOnly Property ParagraphFormat As ParagraphFormat
[C#]
public ParagraphFormat ParagraphFormat {get;}

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Paragraph Class | Aspose.Words Namespace


ParentSection Property

Aspose.Words

Paragraph.ParentSection Property

Retrieves the parent Section of the paragraph.

[Visual Basic]
Public ReadOnly Property ParentSection As Section
[C#]
public Section ParentSection {get;}

See Also

Paragraph Class | Aspose.Words Namespace


ParentStory Property

Aspose.Words

Paragraph.ParentStory Property

Retrieves the parent section-level story that can be Body or HeaderFooter.

[Visual Basic]
Public ReadOnly Property ParentStory As Story
[C#]
public Story ParentStory {get;}

See Also

Paragraph Class | Aspose.Words Namespace


Runs Property

Aspose.Words

Paragraph.Runs Property

Provides access to the typed collection of pieces of text inside the paragraph.

[Visual Basic]
Public ReadOnly Property Runs As RunCollection
[C#]
public RunCollection Runs {get;}

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph Methods

The methods of the Paragraph class are listed below. For a complete list of Paragraph class members, see the Paragraph Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendField | Overloaded. Appends a Word field to this paragraph.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEffectiveTabStops | Returns array of all tab stops applied to this paragraph, including applied indirectly by styles or lists.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText | Gets the text of this paragraph including the end of paragraph character.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
InsertField | Overloaded. Inserts a Word field into this paragraph.
JoinRunsWithSameFormatting | Joins runs with the same formatting in the paragraph.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitParagraphStart, then calls Accept for all child nodes of the paragraph and calls DocumentVisitor.VisitParagraphEnd at the end.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

Paragraph Class | Aspose.Words Namespace


AppendField Method

Aspose.Words

Paragraph.AppendField Method

Appends a Word field to this paragraph.

Overload List

Appends a field to this paragraph.

public Field AppendField(FieldType,bool);

Appends a field to this paragraph.

public Field AppendField(string);

Appends a field to this paragraph.

public Field AppendField(string,string);

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph.AppendField Method (FieldType, Boolean)

Appends a field to this paragraph.

[Visual Basic]
Overloads Public Function AppendField( _
ByVal fieldType As FieldType, _
ByVal updateField As Boolean _
) As Field
[C#]
public Field AppendField(
FieldType fieldType,
bool updateField
);

Parameters

fieldType
The type of the field to append.
updateField
Specifies whether to update the field immediately.

Return Value

A Field object that represents the appended field.

See Also

Paragraph Class | Aspose.Words Namespace | Paragraph.AppendField Overload List


Paragraph.AppendField Method (String)

Appends a field to this paragraph.

[Visual Basic]
Overloads Public Function AppendField( _
ByVal fieldCode As String _
) As Field
[C#]
public Field AppendField(
string fieldCode
);

Parameters

fieldCode
The field code to append (without curly braces).

Return Value

A Field object that represents the appended field.

See Also

Paragraph Class | Aspose.Words Namespace | Paragraph.AppendField Overload List


Paragraph.AppendField Method (String, String)

Appends a field to this paragraph.

[Visual Basic]
Overloads Public Function AppendField( _
ByVal fieldCode As String, _
ByVal fieldValue As String _
) As Field
[C#]
public Field AppendField(
string fieldCode,
string fieldValue
);

Parameters

fieldCode
The field code to append (without curly braces).
fieldValue
The field value to append. Pass null for fields that do not have a value.

Return Value

A Field object that represents the appended field.

See Also

Paragraph Class | Aspose.Words Namespace | Paragraph.AppendField Overload List


Paragraph.GetEffectiveTabStops Method

Returns array of all tab stops applied to this paragraph, including applied indirectly by styles or lists.

[Visual Basic]
Public Function GetEffectiveTabStops() As TabStop()
[C#]
public TabStop[] GetEffectiveTabStops();

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph.GetText Method

Gets the text of this paragraph including the end of paragraph character.

[Visual Basic]
Overrides Public Function GetText() As String
[C#]
public override string GetText();

Remarks

The text of all child nodes is concatenated and the end of paragraph character is appended as follows:

  • If the paragraph is the last paragraph of Body, then ControlChar.SectionBreak (\x000c) is appended.
  • If the paragraph is the last paragraph of Cell, then ControlChar.Cell (\x0007) is appended.
  • For all other paragraphs ControlChar.ParagraphBreak (\r) is appended.

The returned string includes all control and special characters as described in ControlChar.

See Also

Paragraph Class | Aspose.Words Namespace


InsertField Method

Aspose.Words

Paragraph.InsertField Method

Inserts a Word field into this paragraph.

Overload List

Inserts a field into this paragraph.

public Field InsertField(FieldType,bool,Node,bool);

Inserts a field into this paragraph.

public Field InsertField(string,Node,bool);

Inserts a field into this paragraph.

public Field InsertField(string,string,Node,bool);

See Also

Paragraph Class | Aspose.Words Namespace


Paragraph.InsertField Method (FieldType, Boolean, Node, Boolean)

Inserts a field into this paragraph.

[Visual Basic]
Overloads Public Function InsertField( _
ByVal fieldType As FieldType, _
ByVal updateField As Boolean, _
ByVal refNode As Node, _
ByVal isAfter As Boolean _
) As Field
[C#]
public Field InsertField(
FieldType fieldType,
bool updateField,
Node refNode,
bool isAfter
);

Parameters

fieldType
The type of the field to insert.
updateField
Specifies whether to update the field immediately.
refNode
Reference node inside this paragraph (if refNode is null, then appends to the end of the paragraph).
isAfter
Whether to insert the field after or before reference node.

Return Value

A Field object that represents the inserted field.

Example

Shows how to insert field using several methods: "field code", "field code and field value", "field code and field value after a run of text"

[C#]

Document doc = new Document();

// Get the first paragraph of the document
Paragraph para = doc.FirstSection.Body.FirstParagraph;

// Inserting field using field code
// Note: All methods support inserting field after some node. Just set "true" in the "isAfter" parameter
para.InsertField(" AUTHOR ", null, false);

// Using field type
// Note:
// 1. For inserting field using field type, you can choose, update field before or after you open the document ("updateField" parameter)
// 2. For other methods it's works automatically
para.InsertField(FieldType.FieldAuthor, false, null, true);

// Using field code and field value
para.InsertField(" AUTHOR ", "Test Field Value", null, false);

// Add a run of text
Run run = new Run(doc) { Text = " Hello World!" };
para.AppendChild(run);

// Using field code and field value before a run of text
// Note: For inserting field before/after a run of text you can use all methods above, just add ref on your text ("refNode" parameter)
para.InsertField(" AUTHOR ", "Test Field Value", run, false);

See Also

Paragraph Class | Aspose.Words Namespace | Paragraph.InsertField Overload List


Paragraph.InsertField Method (String, Node, Boolean)

Inserts a field into this paragraph.

[Visual Basic]
Overloads Public Function InsertField( _
ByVal fieldCode As String, _
ByVal refNode As Node, _
ByVal isAfter As Boolean _
) As Field
[C#]
public Field InsertField(
string fieldCode,
Node refNode,
bool isAfter
);

Parameters

fieldCode
The field code to insert (without curly braces).
refNode
Reference node inside this paragraph (if refNode is null, then appends to the end of the paragraph).
isAfter
Whether to insert the field after or before reference node.

Return Value

A Field object that represents the inserted field.

Example

Shows how to insert field using several methods: "field code", "field code and field value", "field code and field value after a run of text"

[C#]

Document doc = new Document();

// Get the first paragraph of the document
Paragraph para = doc.FirstSection.Body.FirstParagraph;

// Inserting field using field code
// Note: All methods support inserting field after some node. Just set "true" in the "isAfter" parameter
para.InsertField(" AUTHOR ", null, false);

// Using field type
// Note:
// 1. For inserting field using field type, you can choose, update field before or after you open the document ("updateField" parameter)
// 2. For other methods it's works automatically
para.InsertField(FieldType.FieldAuthor, false, null, true);

// Using field code and field value
para.InsertField(" AUTHOR ", "Test Field Value", null, false);

// Add a run of text
Run run = new Run(doc) { Text = " Hello World!" };
para.AppendChild(run);

// Using field code and field value before a run of text
// Note: For inserting field before/after a run of text you can use all methods above, just add ref on your text ("refNode" parameter)
para.InsertField(" AUTHOR ", "Test Field Value", run, false);

See Also

Paragraph Class | Aspose.Words Namespace | Paragraph.InsertField Overload List


Paragraph.InsertField Method (String, String, Node, Boolean)

Inserts a field into this paragraph.

[Visual Basic]
Overloads Public Function InsertField( _
ByVal fieldCode As String, _
ByVal fieldValue As String, _
ByVal refNode As Node, _
ByVal isAfter As Boolean _
) As Field
[C#]
public Field InsertField(
string fieldCode,
string fieldValue,
Node refNode,
bool isAfter
);

Parameters

fieldCode
The field code to insert (without curly braces).
fieldValue
The field value to insert. Pass null for fields that do not have a value.
refNode
Reference node inside this paragraph (if refNode is null, then appends to the end of the paragraph).
isAfter
Whether to insert the field after or before reference node.

Return Value

A Field object that represents the inserted field.

Example

Shows how to insert field using several methods: "field code", "field code and field value", "field code and field value after a run of text"

[C#]

Document doc = new Document();

// Get the first paragraph of the document
Paragraph para = doc.FirstSection.Body.FirstParagraph;

// Inserting field using field code
// Note: All methods support inserting field after some node. Just set "true" in the "isAfter" parameter
para.InsertField(" AUTHOR ", null, false);

// Using field type
// Note:
// 1. For inserting field using field type, you can choose, update field before or after you open the document ("updateField" parameter)
// 2. For other methods it's works automatically
para.InsertField(FieldType.FieldAuthor, false, null, true);

// Using field code and field value
para.InsertField(" AUTHOR ", "Test Field Value", null, false);

// Add a run of text
Run run = new Run(doc) { Text = " Hello World!" };
para.AppendChild(run);

// Using field code and field value before a run of text
// Note: For inserting field before/after a run of text you can use all methods above, just add ref on your text ("refNode" parameter)
para.InsertField(" AUTHOR ", "Test Field Value", run, false);

See Also

Paragraph Class | Aspose.Words Namespace | Paragraph.InsertField Overload List


Paragraph.JoinRunsWithSameFormatting Method

Joins runs with the same formatting in the paragraph.

[Visual Basic]
Public Function JoinRunsWithSameFormatting() As Integer
[C#]
public int JoinRunsWithSameFormatting();

Return Value

Number of joins performed. When N adjacent runs are being joined they count as N - 1 joins.

See Also

Paragraph Class | Aspose.Words Namespace


ParagraphAlignment Enumeration

Specifies text alignment in a paragraph.

[Visual Basic]
Public Enum ParagraphAlignment
[C#]
public enum ParagraphAlignment

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Members

Member Name | Description | Value
Left | Text is aligned to the left. | 0
Center | Text is centered horizontally. | 1
Right | Text is aligned to the right. | 2
Justify | Text is aligned to both left and right. | 3
Distributed | Text is evenly distributed. | 4
ArabicMediumKashida | Arabic only. Kashida length for text is extended to a medium length determined by the consumer. | 5
ArabicHighKashida | Arabic only. Kashida length for text is extended to its widest possible length. | 7
ArabicLowKashida | Arabic only. Kashida length for text is extended to a slightly longer length. | 8
ThaiDistributed | Thai only. Text is justified with an optimization for Thai. | 9

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


ParagraphCollection Class

Provides typed access to a collection of Paragraph nodes.

For a list of all members of this type, see ParagraphCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.ParagraphCollection

[Visual Basic]
Public Class ParagraphCollection
Inherits NodeCollection
[C#]
public class ParagraphCollection : NodeCollection

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ParagraphCollection Members | Aspose.Words Namespace


ParagraphCollection Members

ParagraphCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Paragraph at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all paragraphs from the collection to a new array of paragraphs.

See Also

ParagraphCollection Class | Aspose.Words Namespace


ParagraphCollection Properties

The properties of the ParagraphCollection class are listed below. For a complete list of ParagraphCollection class members, see the ParagraphCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Paragraph at the given index.

See Also

ParagraphCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

ParagraphCollection.Item Property

Retrieves a Paragraph at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Paragraph
[C#]
new public Paragraph this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

ParagraphCollection Class | Aspose.Words Namespace


ParagraphCollection Methods

The methods of the ParagraphCollection class are listed below. For a complete list of ParagraphCollection class members, see the ParagraphCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all paragraphs from the collection to a new array of paragraphs.

See Also

ParagraphCollection Class | Aspose.Words Namespace


ParagraphCollection.ToArray Method

Copies all paragraphs from the collection to a new array of paragraphs.

[Visual Basic]
Public Function ToArray() As Paragraph()
[C#]
new public Paragraph[] ToArray();

Return Value

An array of paragraphs.

Example

Demonstrates typed implementations of ToArray on classes derived from NodeCollection.

[C#]

// You can use ToArray to return a typed array of nodes.
Paragraph[] paras = doc.FirstSection.Body.Paragraphs.ToArray();
Demonstrates an example breakage of the node collection enumerator.
[C#]

DocumentBuilder builder = new DocumentBuilder();
builder.Writeln("The first paragraph");
builder.Writeln("The second paragraph");
builder.Writeln("The third paragraph");
builder.Writeln("The fourth paragraph");

// This causes unexpected behavior, the fourth paragraph in the collection is not visited.
foreach (Paragraph para in builder.Document.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true)
    .OfType<Paragraph>())
{
    if (para.Range.Text.Contains("third"))
    {
        para.PreviousSibling.Remove();
        para.Remove();
    }
}
Demonstrates how to use "hot remove" to remove a node during enumeration.
[C#]

DocumentBuilder builder = new DocumentBuilder();
builder.Writeln("The first paragraph");
builder.Writeln("The second paragraph");
builder.Writeln("The third paragraph");
builder.Writeln("The fourth paragraph");

// Hot remove allows a node to be removed from a live collection and have the enumeration continue.
foreach (Paragraph para in builder.Document.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true)
    .OfType<Paragraph>())
{
    if (para.Range.Text.Contains("third"))
    {
        // Enumeration will continue even after this node is removed.
        para.Remove();
    }
}

See Also

ParagraphCollection Class | Aspose.Words Namespace


ParagraphFormat Class

Represents all the formatting for a paragraph.

For a list of all members of this type, see ParagraphFormat Members.

System.Object
Aspose.Words.ParagraphFormat

[Visual Basic]
Public Class ParagraphFormat
[C#]
public class ParagraphFormat

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ParagraphFormat Members | Aspose.Words Namespace


ParagraphFormat Members

ParagraphFormat overview

Public Instance Properties

AddSpaceBetweenFarEastAndAlpha | Gets or sets a flag indicating whether inter-character spacing is automatically adjusted between regions of Latin text and regions of East Asian text in the current paragraph.
AddSpaceBetweenFarEastAndDigit | Gets or sets a flag indicating whether inter-character spacing is automatically adjusted between regions of numbers and regions of East Asian text in the current paragraph.
Alignment | Gets or sets text alignment for the paragraph.
Bidi | Gets or sets whether this is a right-to-left paragraph.
Borders | Gets collection of borders of the paragraph.
DropCapPosition | Gets or sets the position for a drop cap text.
FarEastLineBreakControl | Gets or sets a flag indicating whether East Asian line-breaking rules are applied to the current paragraph.
FirstLineIndent | Gets or sets the value (in points) for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.
HangingPunctuation | Gets or sets a flag indicating whether hanging punctuation is enabled for the current paragraph.
IsHeading | True when the paragraph style is one of the built-in Heading styles.
IsListItem | True when the paragraph is an item in a bulleted or numbered list.
KeepTogether | True if all lines in the paragraph are to remain on the same page.
KeepWithNext | True if the paragraph is to remains on the same page as the paragraph that follows it.
LeftIndent | Gets or sets the value (in points) that represents the left indent for paragraph.
LineSpacing | Gets or sets the line spacing (in points) for the paragraph.
LineSpacingRule | Gets or sets the line spacing for the paragraph.
LinesToDrop | Gets or sets the number of lines of the paragraph text used to calculate the drop cap height.
NoSpaceBetweenParagraphsOfSameStyle | When true, SpaceBefore and SpaceAfter will be ignored between the paragraphs of the same style.
OutlineLevel | Specifies the outline level of the paragraph in the document.
PageBreakBefore | True if a page break is forced before the paragraph.
RightIndent | Gets or sets the value (in points) that represents the right indent for paragraph.
Shading | Returns a Shading object that refers to the shading formatting for the paragraph.
SpaceAfter | Gets or sets the amount of spacing (in points) after the paragraph.
SpaceAfterAuto | True if the amount of spacing after the paragraph is set automatically.
SpaceBefore | Gets or sets the amount of spacing (in points) before the paragraph.
SpaceBeforeAuto | True if the amount of spacing before the paragraph is set automatically.
Style | Gets or sets the paragraph style applied to this formatting.
StyleIdentifier | Gets or sets the locale independent style identifier of the paragraph style applied to this formatting.
StyleName | Gets or sets the name of the paragraph style applied to this formatting.
SuppressAutoHyphens | Specifies whether the current paragraph should be exempted from any hyphenation which is applied in the document settings.
SuppressLineNumbers | Specifies whether the current paragraph's lines should be exempted from line numbering which is applied in the parent section.
TabStops | Gets the collection of custom tab stops defined for this object.
WidowControl | True if the first and last lines in the paragraph are to remain on the same page as the rest of the paragraph.
WordWrap | If this property is false, Latin text in the middle of a word can be wrapped for the current paragraph. Otherwise Latin text is wrapped by whole words.

Public Instance Methods

ClearFormatting Resets to default paragraph formatting.

See Also

ParagraphFormat Class | Aspose.Words Namespace


ParagraphFormat Properties

The properties of the ParagraphFormat class are listed below. For a complete list of ParagraphFormat class members, see the ParagraphFormat Members topic.

Public Instance Properties

AddSpaceBetweenFarEastAndAlpha | Gets or sets a flag indicating whether inter-character spacing is automatically adjusted between regions of Latin text and regions of East Asian text in the current paragraph.
AddSpaceBetweenFarEastAndDigit | Gets or sets a flag indicating whether inter-character spacing is automatically adjusted between regions of numbers and regions of East Asian text in the current paragraph.
Alignment | Gets or sets text alignment for the paragraph.
Bidi | Gets or sets whether this is a right-to-left paragraph.
Borders | Gets collection of borders of the paragraph.
DropCapPosition | Gets or sets the position for a drop cap text.
FarEastLineBreakControl | Gets or sets a flag indicating whether East Asian line-breaking rules are applied to the current paragraph.
FirstLineIndent | Gets or sets the value (in points) for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.
HangingPunctuation | Gets or sets a flag indicating whether hanging punctuation is enabled for the current paragraph.
IsHeading | True when the paragraph style is one of the built-in Heading styles.
IsListItem | True when the paragraph is an item in a bulleted or numbered list.
KeepTogether | True if all lines in the paragraph are to remain on the same page.
KeepWithNext | True if the paragraph is to remains on the same page as the paragraph that follows it.
LeftIndent | Gets or sets the value (in points) that represents the left indent for paragraph.
LineSpacing | Gets or sets the line spacing (in points) for the paragraph.
LineSpacingRule | Gets or sets the line spacing for the paragraph.
LinesToDrop | Gets or sets the number of lines of the paragraph text used to calculate the drop cap height.
NoSpaceBetweenParagraphsOfSameStyle | When true, SpaceBefore and SpaceAfter will be ignored between the paragraphs of the same style.
OutlineLevel | Specifies the outline level of the paragraph in the document.
PageBreakBefore | True if a page break is forced before the paragraph.
RightIndent | Gets or sets the value (in points) that represents the right indent for paragraph.
Shading | Returns a Shading object that refers to the shading formatting for the paragraph.
SpaceAfter | Gets or sets the amount of spacing (in points) after the paragraph.
SpaceAfterAuto | True if the amount of spacing after the paragraph is set automatically.
SpaceBefore | Gets or sets the amount of spacing (in points) before the paragraph.
SpaceBeforeAuto | True if the amount of spacing before the paragraph is set automatically.
Style | Gets or sets the paragraph style applied to this formatting.
StyleIdentifier | Gets or sets the locale independent style identifier of the paragraph style applied to this formatting.
StyleName | Gets or sets the name of the paragraph style applied to this formatting.
SuppressAutoHyphens | Specifies whether the current paragraph should be exempted from any hyphenation which is applied in the document settings.
SuppressLineNumbers | Specifies whether the current paragraph's lines should be exempted from line numbering which is applied in the parent section.
TabStops | Gets the collection of custom tab stops defined for this object.
WidowControl | True if the first and last lines in the paragraph are to remain on the same page as the rest of the paragraph.
WordWrap | If this property is false, Latin text in the middle of a word can be wrapped for the current paragraph. Otherwise Latin text is wrapped by whole words.

See Also

ParagraphFormat Class | Aspose.Words Namespace


AddSpaceBetweenFarEastAndAlpha Property

Aspose.Words

ParagraphFormat.AddSpaceBetweenFarEastAndAlpha Property

Gets or sets a flag indicating whether inter-character spacing is automatically adjusted between regions of Latin text and regions of East Asian text in the current paragraph.

[Visual Basic]
Public Property AddSpaceBetweenFarEastAndAlpha As Boolean
[C#]
public bool AddSpaceBetweenFarEastAndAlpha {get; set;}

Example

Shows how to insert a paragraph into the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


AddSpaceBetweenFarEastAndDigit Property

Aspose.Words

ParagraphFormat.AddSpaceBetweenFarEastAndDigit Property

Gets or sets a flag indicating whether inter-character spacing is automatically adjusted between regions of numbers and regions of East Asian text in the current paragraph.

[Visual Basic]
Public Property AddSpaceBetweenFarEastAndDigit As Boolean
[C#]
public bool AddSpaceBetweenFarEastAndDigit {get; set;}

Example

Shows how to insert a paragraph into the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


Alignment Property

Aspose.Words

ParagraphFormat.Alignment Property

Gets or sets text alignment for the paragraph.

[Visual Basic]
Public Property Alignment As ParagraphAlignment
[C#]
public ParagraphAlignment Alignment {get; set;}

Example

Shows how to insert a paragraph into the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

ParagraphFormat Class | Aspose.Words Namespace


Bidi Property

Aspose.Words

ParagraphFormat.Bidi Property

Gets or sets whether this is a right-to-left paragraph.

[Visual Basic]
Public Property Bidi As Boolean
[C#]
public bool Bidi {get; set;}

Remarks

When true, the runs and other inline objects in this paragraph are laid out right to left.

See Also

ParagraphFormat Class | Aspose.Words Namespace


Borders Property

Aspose.Words

ParagraphFormat.Borders Property

Gets collection of borders of the paragraph.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

Example

Inserts a paragraph with a top border.

[C#]

DocumentBuilder builder = new DocumentBuilder();

Border topBorder = builder.ParagraphFormat.Borders[BorderType.Top];
topBorder.Color = Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");

See Also

ParagraphFormat Class | Aspose.Words Namespace


DropCapPosition Property

Aspose.Words

ParagraphFormat.DropCapPosition Property

Gets or sets the position for a drop cap text.

[Visual Basic]
Public Property DropCapPosition As DropCapPosition
[C#]
public DropCapPosition DropCapPosition {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


FarEastLineBreakControl Property

Aspose.Words

ParagraphFormat.FarEastLineBreakControl Property

Gets or sets a flag indicating whether East Asian line-breaking rules are applied to the current paragraph.

[Visual Basic]
Public Property FarEastLineBreakControl As Boolean
[C#]
public bool FarEastLineBreakControl {get; set;}

Example

Shows how to set special properties for Asian typography.

[C#]

Document doc = new Document(MyDir + "Document.docx");

ParagraphFormat format = doc.FirstSection.Body.Paragraphs[0].ParagraphFormat;
format.FarEastLineBreakControl = true;
format.WordWrap = false;
format.HangingPunctuation = true;

doc.Save(ArtifactsDir + "Paragraph.AsianTypographyProperties.docx");

See Also

ParagraphFormat Class | Aspose.Words Namespace


FirstLineIndent Property

Aspose.Words

ParagraphFormat.FirstLineIndent Property

Gets or sets the value (in points) for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent.

[Visual Basic]
Public Property FirstLineIndent As Double
[C#]
public double FirstLineIndent {get; set;}

Example

Shows how to insert a paragraph into the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


HangingPunctuation Property

Aspose.Words

ParagraphFormat.HangingPunctuation Property

Gets or sets a flag indicating whether hanging punctuation is enabled for the current paragraph.

[Visual Basic]
Public Property HangingPunctuation As Boolean
[C#]
public bool HangingPunctuation {get; set;}

Example

Shows how to set special properties for Asian typography.

[C#]

Document doc = new Document(MyDir + "Document.docx");

ParagraphFormat format = doc.FirstSection.Body.Paragraphs[0].ParagraphFormat;
format.FarEastLineBreakControl = true;
format.WordWrap = false;
format.HangingPunctuation = true;

doc.Save(ArtifactsDir + "Paragraph.AsianTypographyProperties.docx");

See Also

ParagraphFormat Class | Aspose.Words Namespace


IsHeading Property

Aspose.Words

ParagraphFormat.IsHeading Property

True when the paragraph style is one of the built-in Heading styles.

[Visual Basic]
Public ReadOnly Property IsHeading As Boolean
[C#]
public bool IsHeading {get;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


IsListItem Property

Aspose.Words

ParagraphFormat.IsListItem Property

True when the paragraph is an item in a bulleted or numbered list.

[Visual Basic]
Public ReadOnly Property IsListItem As Boolean
[C#]
public bool IsListItem {get;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


KeepTogether Property

Aspose.Words

ParagraphFormat.KeepTogether Property

True if all lines in the paragraph are to remain on the same page.

[Visual Basic]
Public Property KeepTogether As Boolean
[C#]
public bool KeepTogether {get; set;}

Example

Shows how to insert a paragraph into the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Aspose.Words.Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


KeepWithNext Property

Aspose.Words

ParagraphFormat.KeepWithNext Property

True if the paragraph is to remains on the same page as the paragraph that follows it.

[Visual Basic]
Public Property KeepWithNext As Boolean
[C#]
public bool KeepWithNext {get; set;}

Example

Shows how to set a table to stay together on the same page.

[C#]

// To keep a table from breaking across a page we need to enable KeepWithNext
// for every paragraph in the table except for the last paragraphs in the last
// row of the table.
foreach (Cell cell in table.GetChildNodes(NodeType.Cell, true).OfType<Cell>())
foreach (Paragraph para in cell.Paragraphs.OfType<Paragraph>())
    if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
        para.ParagraphFormat.KeepWithNext = true;

See Also

ParagraphFormat Class | Aspose.Words Namespace


LeftIndent Property

Aspose.Words

ParagraphFormat.LeftIndent Property

Gets or sets the value (in points) that represents the left indent for paragraph.

[Visual Basic]
Public Property LeftIndent As Double
[C#]
public double LeftIndent {get; set;}

Example

Shows how to set paragraph formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.LeftIndent = 50;
paragraphFormat.RightIndent = 50;
paragraphFormat.SpaceAfter = 25;

// Output text
builder.Writeln(
    "I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder.Writeln(
    "I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


LineSpacing Property

Aspose.Words

ParagraphFormat.LineSpacing Property

Gets or sets the line spacing (in points) for the paragraph.

[Visual Basic]
Public Property LineSpacing As Double
[C#]
public double LineSpacing {get; set;}

Remarks

When LineSpacingRule property is set to AtLeast, the line spacing can be greater than or equal to, but never less than the specified LineSpacing value.

When LineSpacingRule property is set to Exactly, the line spacing never changes from the specified LineSpacing value, even if a larger font is used within the paragraph.

See Also

ParagraphFormat Class | Aspose.Words Namespace


LineSpacingRule Property

Aspose.Words

ParagraphFormat.LineSpacingRule Property

Gets or sets the line spacing for the paragraph.

[Visual Basic]
Public Property LineSpacingRule As LineSpacingRule
[C#]
public LineSpacingRule LineSpacingRule {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


LinesToDrop Property

Aspose.Words

ParagraphFormat.LinesToDrop Property

Gets or sets the number of lines of the paragraph text used to calculate the drop cap height.

[Visual Basic]
Public Property LinesToDrop As Integer
[C#]
public int LinesToDrop {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


NoSpaceBetweenParagraphsOfSameStyle Property

Aspose.Words

ParagraphFormat.NoSpaceBetweenParagraphsOfSameStyle Property

When true, SpaceBefore and SpaceAfter will be ignored between the paragraphs of the same style.

[Visual Basic]
Public Property NoSpaceBetweenParagraphsOfSameStyle As Boolean
[C#]
public bool NoSpaceBetweenParagraphsOfSameStyle {get; set;}

Remarks

This setting only takes affect when applied to a paragraph style. If applied to a paragraph directly, it has no effect.

See Also

ParagraphFormat Class | Aspose.Words Namespace


OutlineLevel Property

Aspose.Words

ParagraphFormat.OutlineLevel Property

Specifies the outline level of the paragraph in the document.

[Visual Basic]
Public Property OutlineLevel As OutlineLevel
[C#]
public OutlineLevel OutlineLevel {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


PageBreakBefore Property

Aspose.Words

ParagraphFormat.PageBreakBefore Property

True if a page break is forced before the paragraph.

[Visual Basic]
Public Property PageBreakBefore As Boolean
[C#]
public bool PageBreakBefore {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


RightIndent Property

Aspose.Words

ParagraphFormat.RightIndent Property

Gets or sets the value (in points) that represents the right indent for paragraph.

[Visual Basic]
Public Property RightIndent As Double
[C#]
public double RightIndent {get; set;}

Example

Shows how to set paragraph formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.LeftIndent = 50;
paragraphFormat.RightIndent = 50;
paragraphFormat.SpaceAfter = 25;

// Output text
builder.Writeln(
    "I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder.Writeln(
    "I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


Shading Property

Aspose.Words

ParagraphFormat.Shading Property

Returns a Shading object that refers to the shading formatting for the paragraph.

[Visual Basic]
Public ReadOnly Property Shading As Shading
[C#]
public Shading Shading {get;}

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


SpaceAfter Property

Aspose.Words

ParagraphFormat.SpaceAfter Property

Gets or sets the amount of spacing (in points) after the paragraph.

[Visual Basic]
Public Property SpaceAfter As Double
[C#]
public double SpaceAfter {get; set;}

Remarks

Has no effect when SpaceAfterAuto is true.

Example

Shows how to set paragraph formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.LeftIndent = 50;
paragraphFormat.RightIndent = 50;
paragraphFormat.SpaceAfter = 25;

// Output text
builder.Writeln(
    "I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder.Writeln(
    "I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");

See Also

ParagraphFormat Class | Aspose.Words Namespace


SpaceAfterAuto Property

Aspose.Words

ParagraphFormat.SpaceAfterAuto Property

True if the amount of spacing after the paragraph is set automatically.

[Visual Basic]
Public Property SpaceAfterAuto As Boolean
[C#]
public bool SpaceAfterAuto {get; set;}

Remarks

When set to true, overrides the effect of SpaceAfter.

When you set paragraph Space Before and Space After to Auto, Microsoft Word adds 14 points spacing between paragraphs automatically according to the following rules:

  • Normally, spacing is added after all paragraphs.
  • In a bulleted or numbered list, spacing is added only after the last item in the list. Spacing is not added between the list items.
  • In a nested bulleted or numbered list spacing is not added.
  • Spacing is normally added after a table.
  • Spacing is not added after a table if it is the last block in a table cell.
  • Spacing is not added after the last paragraph in a table cell.

See Also

ParagraphFormat Class | Aspose.Words Namespace


SpaceBefore Property

Aspose.Words

ParagraphFormat.SpaceBefore Property

Gets or sets the amount of spacing (in points) before the paragraph.

[Visual Basic]
Public Property SpaceBefore As Double
[C#]
public double SpaceBefore {get; set;}

Remarks

Has no effect when SpaceBeforeAuto is true.

See Also

ParagraphFormat Class | Aspose.Words Namespace


SpaceBeforeAuto Property

Aspose.Words

ParagraphFormat.SpaceBeforeAuto Property

True if the amount of spacing before the paragraph is set automatically.

[Visual Basic]
Public Property SpaceBeforeAuto As Boolean
[C#]
public bool SpaceBeforeAuto {get; set;}

Remarks

When set to true, overrides the effect of SpaceBefore.

When you set paragraph Space Before and Space After to Auto, Microsoft Word adds 14 points spacing between paragraphs automatically according to the following rules:

  • Normally, spacing is added after all paragraphs.
  • In a bulleted or numbered list, spacing is added only after the last item in the list. Spacing is not added between the list items.
  • In a nested bulleted or numbered list spacing is not added.
  • Spacing is normally added after a table.
  • Spacing is not added after a table if it is the last block in a table cell.
  • Spacing is not added after the last paragraph in a table cell.

See Also

ParagraphFormat Class | Aspose.Words Namespace


Style Property

Aspose.Words

ParagraphFormat.Style Property

Gets or sets the paragraph style applied to this formatting.

[Visual Basic]
Public Property Style As Style
[C#]
public Style Style {get; set;}

Example

Shows how to create and use a paragraph style with list formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

See Also

ParagraphFormat Class | Aspose.Words Namespace


StyleIdentifier Property

Aspose.Words

ParagraphFormat.StyleIdentifier Property

Gets or sets the locale independent style identifier of the paragraph style applied to this formatting.

[Visual Basic]
Public Property StyleIdentifier As StyleIdentifier
[C#]
public StyleIdentifier StyleIdentifier {get; set;}

Example

Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.

[C#]

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 2");
builder.Writeln("Heading 3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");

// Call the method below to update the TOC.
doc.UpdateFields();

See Also

ParagraphFormat Class | Aspose.Words Namespace


StyleName Property

Aspose.Words

ParagraphFormat.StyleName Property

Gets or sets the name of the paragraph style applied to this formatting.

[Visual Basic]
Public Property StyleName As String
[C#]
public string StyleName {get; set;}

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

ParagraphFormat Class | Aspose.Words Namespace


SuppressAutoHyphens Property

Aspose.Words

ParagraphFormat.SuppressAutoHyphens Property

Specifies whether the current paragraph should be exempted from any hyphenation which is applied in the document settings.

[Visual Basic]
Public Property SuppressAutoHyphens As Boolean
[C#]
public bool SuppressAutoHyphens {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


SuppressLineNumbers Property

Aspose.Words

ParagraphFormat.SuppressLineNumbers Property

Specifies whether the current paragraph's lines should be exempted from line numbering which is applied in the parent section.

[Visual Basic]
Public Property SuppressLineNumbers As Boolean
[C#]
public bool SuppressLineNumbers {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


TabStops Property

Aspose.Words

ParagraphFormat.TabStops Property

Gets the collection of custom tab stops defined for this object.

[Visual Basic]
Public ReadOnly Property TabStops As TabStopCollection
[C#]
public TabStopCollection TabStops {get;}

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

See Also

ParagraphFormat Class | Aspose.Words Namespace


WidowControl Property

Aspose.Words

ParagraphFormat.WidowControl Property

True if the first and last lines in the paragraph are to remain on the same page as the rest of the paragraph.

[Visual Basic]
Public Property WidowControl As Boolean
[C#]
public bool WidowControl {get; set;}

See Also

ParagraphFormat Class | Aspose.Words Namespace


WordWrap Property

Aspose.Words

ParagraphFormat.WordWrap Property

If this property is false, Latin text in the middle of a word can be wrapped for the current paragraph. Otherwise Latin text is wrapped by whole words.

[Visual Basic]
Public Property WordWrap As Boolean
[C#]
public bool WordWrap {get; set;}

Example

Shows how to set special properties for Asian typography.

[C#]

Document doc = new Document(MyDir + "Document.docx");

ParagraphFormat format = doc.FirstSection.Body.Paragraphs[0].ParagraphFormat;
format.FarEastLineBreakControl = true;
format.WordWrap = false;
format.HangingPunctuation = true;

doc.Save(ArtifactsDir + "Paragraph.AsianTypographyProperties.docx");

See Also

ParagraphFormat Class | Aspose.Words Namespace


ParagraphFormat Methods

The methods of the ParagraphFormat class are listed below. For a complete list of ParagraphFormat class members, see the ParagraphFormat Members topic.

Public Instance Methods

ClearFormatting Resets to default paragraph formatting.

See Also

ParagraphFormat Class | Aspose.Words Namespace


ParagraphFormat.ClearFormatting Method

Resets to default paragraph formatting.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Remarks

Default paragraph formatting is Normal style, left aligned, no indentation, no spacing, no borders and no shading.

See Also

ParagraphFormat Class | Aspose.Words Namespace


PlainTextDocument Class

Allows to extract plain-text representation of the document's content.

For a list of all members of this type, see PlainTextDocument Members.

System.Object
Aspose.Words.PlainTextDocument

[Visual Basic]
Public Class PlainTextDocument
[C#]
public class PlainTextDocument

Example

Show how to simply extract text from a document.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions { DetectNumberingWithWhitespaces = false };

PlainTextDocument plaintext = new PlainTextDocument(MyDir + "Bookmark.docx");

plaintext = new PlainTextDocument(MyDir + "Bookmark.docx", loadOptions);

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PlainTextDocument Members | Aspose.Words Namespace


PlainTextDocument Members

PlainTextDocument overview

Public Instance Constructors

PlainTextDocument Overloaded. Initializes a new instance of the PlainTextDocument class.

Public Instance Properties

BuiltInDocumentProperties | Gets BuiltInDocumentProperties of the document.
CustomDocumentProperties | Gets CustomDocumentProperties of the document.
Text | Gets textual content of the document concatenated as a string.

See Also

PlainTextDocument Class | Aspose.Words Namespace


PlainTextDocument Constructor

Creates a plain text document from a file. Automatically detects the file format.

Overload List

Creates a plain text document from a stream. Automatically detects the file format.

public PlainTextDocument(Stream);

Creates a plain text document from a stream. Allows to specify additional options such as an encryption password.

public PlainTextDocument(Stream,LoadOptions);

Creates a plain text document from a file. Automatically detects the file format.

public PlainTextDocument(string);

Creates a plain text document from a file. Allows to specify additional options such as an encryption password.

public PlainTextDocument(string,LoadOptions);

See Also

PlainTextDocument Class | Aspose.Words Namespace


PlainTextDocument Constructor (String)

Creates a plain text document from a file. Automatically detects the file format.

[Visual Basic]
Overloads Public Sub New( _
ByVal fileName As String _
)
[C#]
public PlainTextDocument(
string fileName
);

Parameters

fileName
Name of the file to extract the text from.

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentException | The name of the file cannot be null or empty string.

Example

Show how to simply extract text from a document.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions { DetectNumberingWithWhitespaces = false };

PlainTextDocument plaintext = new PlainTextDocument(MyDir + "Bookmark.docx");

plaintext = new PlainTextDocument(MyDir + "Bookmark.docx", loadOptions);

See Also

PlainTextDocument Class | Aspose.Words Namespace | PlainTextDocument Constructor Overload List


PlainTextDocument Constructor (String, LoadOptions)

Creates a plain text document from a file. Allows to specify additional options such as an encryption password.

[Visual Basic]
Overloads Public Sub New( _
ByVal fileName As String, _
ByVal loadOptions As LoadOptions _
)
[C#]
public PlainTextDocument(
string fileName,
LoadOptions loadOptions
);

Parameters

fileName
Name of the file to extract the text from.
loadOptions
Additional options to use when loading a document. Can be null.

Remarks

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentException | The name of the file cannot be null or empty string.

Example

Show how to simply extract text from a document.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions { DetectNumberingWithWhitespaces = false };

PlainTextDocument plaintext = new PlainTextDocument(MyDir + "Bookmark.docx");

plaintext = new PlainTextDocument(MyDir + "Bookmark.docx", loadOptions);

See Also

PlainTextDocument Class | Aspose.Words Namespace | PlainTextDocument Constructor Overload List


PlainTextDocument Constructor (Stream)

Creates a plain text document from a stream. Automatically detects the file format.

[Visual Basic]
Overloads Public Sub New( _
ByVal stream As Stream _
)
[C#]
public PlainTextDocument(
Stream stream
);

Parameters

stream
The stream where to extract the text from.

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentNullException | The stream cannot be null.
NotSupportedException | The stream does not support reading or seeking.
ObjectDisposedException | The stream is a disposed object.

Example

Show how to simply extract text from a stream.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions { DetectNumberingWithWhitespaces = false };

Stream stream = new FileStream(MyDir + "Bookmark.docx", FileMode.Open);

PlainTextDocument plaintext = new PlainTextDocument(stream);

plaintext = new PlainTextDocument(stream, loadOptions);

See Also

PlainTextDocument Class | Aspose.Words Namespace | PlainTextDocument Constructor Overload List


PlainTextDocument Constructor (Stream, LoadOptions)

Creates a plain text document from a stream. Allows to specify additional options such as an encryption password.

[Visual Basic]
Overloads Public Sub New( _
ByVal stream As Stream, _
ByVal loadOptions As LoadOptions _
)
[C#]
public PlainTextDocument(
Stream stream,
LoadOptions loadOptions
);

Parameters

stream
The stream where to extract the text from.
loadOptions
Additional options to use when loading a document. Can be null.

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Exceptions

Exception Type | Condition
UnsupportedFileFormatException | The document format is not recognized or not supported.
FileCorruptedException | The document appears to be corrupted and cannot be loaded.
Exception | There is a problem with the document and it should be reported to Aspose.Words developers.
IOException | There is an input/output exception.
IncorrectPasswordException | The document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentNullException | The stream cannot be null.
NotSupportedException | The stream does not support reading or seeking.
ObjectDisposedException | The stream is a disposed object.

Example

Show how to simply extract text from a stream.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions { DetectNumberingWithWhitespaces = false };

Stream stream = new FileStream(MyDir + "Bookmark.docx", FileMode.Open);

PlainTextDocument plaintext = new PlainTextDocument(stream);

plaintext = new PlainTextDocument(stream, loadOptions);

See Also

PlainTextDocument Class | Aspose.Words Namespace | PlainTextDocument Constructor Overload List


PlainTextDocument Properties

The properties of the PlainTextDocument class are listed below. For a complete list of PlainTextDocument class members, see the PlainTextDocument Members topic.

Public Instance Properties

BuiltInDocumentProperties | Gets BuiltInDocumentProperties of the document.
CustomDocumentProperties | Gets CustomDocumentProperties of the document.
Text | Gets textual content of the document concatenated as a string.

See Also

PlainTextDocument Class | Aspose.Words Namespace


BuiltInDocumentProperties Property

Aspose.Words

PlainTextDocument.BuiltInDocumentProperties Property

Gets BuiltInDocumentProperties of the document.

[Visual Basic]
Public ReadOnly Property BuiltInDocumentProperties As BuiltInDocumentProperties
[C#]
public BuiltInDocumentProperties BuiltInDocumentProperties {get;}

Example

Show how to get BuiltIn properties of plain text document.

[C#]

PlainTextDocument plaintext = new PlainTextDocument(MyDir + "Bookmark.docx");
BuiltInDocumentProperties builtInDocumentProperties = plaintext.BuiltInDocumentProperties;

See Also

PlainTextDocument Class | Aspose.Words Namespace


CustomDocumentProperties Property

Aspose.Words

PlainTextDocument.CustomDocumentProperties Property

Gets CustomDocumentProperties of the document.

[Visual Basic]
Public ReadOnly Property CustomDocumentProperties As CustomDocumentProperties
[C#]
public CustomDocumentProperties CustomDocumentProperties {get;}

Example

Show how to get custom properties of plain text document.

[C#]

PlainTextDocument plaintext = new PlainTextDocument(MyDir + "Bookmark.docx");
CustomDocumentProperties customDocumentProperties = plaintext.CustomDocumentProperties;

See Also

PlainTextDocument Class | Aspose.Words Namespace


Text Property

Aspose.Words

PlainTextDocument.Text Property

Gets textual content of the document concatenated as a string.

[Visual Basic]
Public ReadOnly Property Text As String
[C#]
public string Text {get;}

Example

Show how to simply extract text from a document.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions { DetectNumberingWithWhitespaces = false };

PlainTextDocument plaintext = new PlainTextDocument(MyDir + "Bookmark.docx");

plaintext = new PlainTextDocument(MyDir + "Bookmark.docx", loadOptions);

See Also

PlainTextDocument Class | Aspose.Words Namespace


ProtectionType Enumeration

Protection type for a document.

[Visual Basic]
Public Enum ProtectionType
[C#]
public enum ProtectionType

Example

Protects a section so only editing in form fields is possible.

[C#]

// Create a blank document
Document doc = new Document();

// Insert two sections with some text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Section 1. Unprotected.");
builder.InsertBreak(BreakType.SectionBreakContinuous);
builder.Writeln("Section 2. Protected.");

// Section protection only works when document protection is turned and only editing in form fields is allowed.
doc.Protect(ProtectionType.AllowOnlyFormFields);

// By default, all sections are protected, but we can selectively turn protection off.
doc.Sections[0].ProtectedForForms = false;

builder.Document.Save(ArtifactsDir + "Section.Protect.doc");

Members

Member Name | Description | Value
AllowOnlyComments | User can only modify comments in the document. | 1
AllowOnlyFormFields | User can only enter data in the form fields in the document. | 2
AllowOnlyRevisions | User can only add revision marks to the document. | 0
ReadOnly | No changes are allowed to the document. Available since Microsoft Word 2003. | 3
NoProtection | The document is not protected. | -1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Range Class

Represents a contiguous area in a document.

For a list of all members of this type, see Range Members.

System.Object
Aspose.Words.Range

[Visual Basic]
Public Class Range
[C#]
public class Range

Remarks

The document is represented by a tree of nodes and the nodes provide operations to work with the tree, but some operations are easier to perform if the document is treated as a contiguous sequence of text.

Range is a "facade" interface that provide methods that treat the document or portions of the document as "flat" text regardless of the fact that the document nodes are stored in a tree-like object model.

Range does not contain any text or nodes, it is merely a view or "window" over a fragment of a document.

Example

Shows how to get plain, unformatted text of a range.

[C#]

Document doc = new Document(MyDir + "Document.doc");
String text = doc.Range.Text;

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Range Members | Aspose.Words Namespace


Range Members

Range overview

Public Instance Properties

Bookmarks | Returns a Bookmarks collection that represents all bookmarks in the range.
Fields | Returns a Fields collection that represents all fields in the range.
FormFields | Returns a FormFields collection that represents all form fields in the range.
Text | Gets the text of the range.

Public Instance Methods

Delete | Deletes all characters of the range.
NormalizeFieldTypes | Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in this range so that they correspond to the field types contained in the field codes.
Replace | Overloaded. Replaces all occurrences of a character pattern specified by a regular expression with another string.
ToDocument | Constructs a new fully formed document that contains the range.
UnlinkFields | Unlinks fields in this range.
UpdateFields | Updates the values of document fields in this range.

See Also

Range Class | Aspose.Words Namespace


Range Properties

The properties of the Range class are listed below. For a complete list of Range class members, see the Range Members topic.

Public Instance Properties

Bookmarks | Returns a Bookmarks collection that represents all bookmarks in the range.
Fields | Returns a Fields collection that represents all fields in the range.
FormFields | Returns a FormFields collection that represents all form fields in the range.
Text | Gets the text of the range.

See Also

Range Class | Aspose.Words Namespace


Bookmarks Property

Aspose.Words

Range.Bookmarks Property

Returns a Bookmarks collection that represents all bookmarks in the range.

[Visual Basic]
Public ReadOnly Property Bookmarks As BookmarkCollection
[C#]
public BookmarkCollection Bookmarks {get;}

Example

Shows how to get or set bookmark name and text.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];

// Get the name and text of the bookmark.
string name = bookmark.Name;
string text = bookmark.Text;

// Set the name and text of the bookmark.
bookmark.Name = "RenamedBookmark";
bookmark.Text = "This is a new bookmarked text.";

See Also

Range Class | Aspose.Words Namespace


Fields Property

Aspose.Words

Range.Fields Property

Returns a Fields collection that represents all fields in the range.

[Visual Basic]
Public ReadOnly Property Fields As FieldCollection
[C#]
public FieldCollection Fields {get;}

See Also

Range Class | Aspose.Words Namespace


FormFields Property

Aspose.Words

Range.FormFields Property

Returns a FormFields collection that represents all form fields in the range.

[Visual Basic]
Public ReadOnly Property FormFields As FormFieldCollection
[C#]
public FormFieldCollection FormFields {get;}

Example

Shows how to get a collection of form fields.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");
FormFieldCollection formFields = doc.Range.FormFields;

See Also

Range Class | Aspose.Words Namespace


Text Property

Aspose.Words

Range.Text Property

Gets the text of the range.

[Visual Basic]
Public ReadOnly Property Text As String
[C#]
public string Text {get;}

Remarks

The returned string includes all control and special characters as described in ControlChar.

Example

Shows how to get plain, unformatted text of a range.

[C#]

Document doc = new Document(MyDir + "Document.doc");
String text = doc.Range.Text;

See Also

Range Class | Aspose.Words Namespace


Range Methods

The methods of the Range class are listed below. For a complete list of Range class members, see the Range Members topic.

Public Instance Methods

Delete | Deletes all characters of the range.
NormalizeFieldTypes | Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in this range so that they correspond to the field types contained in the field codes.
Replace | Overloaded. Replaces all occurrences of a character pattern specified by a regular expression with another string.
ToDocument | Constructs a new fully formed document that contains the range.
UnlinkFields | Unlinks fields in this range.
UpdateFields | Updates the values of document fields in this range.

See Also

Range Class | Aspose.Words Namespace


Range.Delete Method

Deletes all characters of the range.

[Visual Basic]
Public Sub Delete()
[C#]
public void Delete();

Example

Shows how to delete all characters of a range.

[C#]

// Open Word document.
Document doc = new Document(MyDir + "Range.DeleteSection.doc");

// The document contains two sections. Each section has a paragraph of text.
Console.WriteLine(doc.GetText());

// Delete the first section from the document.
doc.Sections[0].Range.Delete();

// Check the first section was deleted by looking at the text of the whole document again.
Console.WriteLine(doc.GetText());

See Also

Range Class | Aspose.Words Namespace


Range.NormalizeFieldTypes Method

Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in this range so that they correspond to the field types contained in the field codes.

[Visual Basic]
Public Sub NormalizeFieldTypes()
[C#]
public void NormalizeFieldTypes();

Remarks

Use this method after document changes that affect field types.

To change field type values in the whole document use NormalizeFieldTypes.

See Also

Range Class | Aspose.Words Namespace


Replace Method

Aspose.Words

Range.Replace Method

Replaces all occurrences of a character pattern specified by a regular expression with another string.

Overload List

Replaces all occurrences of a character pattern specified by a regular expression with another string.

public int Replace(string,string);

Replaces all occurrences of a character pattern specified by a regular expression with another string.

public int Replace(string,string,FindReplaceOptions);

Replaces all occurrences of a character pattern specified by a regular expression with another string.

public int Replace(Regex,string);

Replaces all occurrences of a character pattern specified by a regular expression with another string.

public int Replace(Regex,string,FindReplaceOptions);

See Also

Range Class | Aspose.Words Namespace


Range.Replace Method (String, String)

Replaces all occurrences of a character pattern specified by a regular expression with another string.

[Visual Basic]
Overloads Public Function Replace( _
ByVal pattern As String, _
ByVal replacement As String _
) As Integer
[C#]
public int Replace(
string pattern,
string replacement
);

Parameters

pattern
A string to be replaced.
replacement
A string to replace all occurrences of pattern.

Return Value

The number of replacements made.

Remarks

Used case-insensitive comparison.

Replaces the whole match captured by the regular expression.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:
  • &p - paragraph break
  • &b - section break
  • &m - page break
  • &l - manual line break
Use method Replace to have more flexible customization.

Example

See Also
Range Class | Aspose.Words Namespace | Range.Replace Overload List


Range.Replace Method (String, String, FindReplaceOptions)

Replaces all occurrences of a character pattern specified by a regular expression with another string.

[Visual Basic]
Overloads Public Function Replace( _
ByVal pattern As String, _
ByVal replacement As String, _
ByVal options As FindReplaceOptions _
) As Integer
[C#]
public int Replace(
string pattern,
string replacement,
FindReplaceOptions options
);

Parameters

pattern
A string to be replaced.
replacement
A string to replace all occurrences of pattern.
options
FindReplaceOptions object to specify additional options.

Return Value

The number of replacements made.

Remarks

Replaces the whole match captured by the regular expression.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:
  • &p - paragraph break
  • &b - section break
  • &m - page break
  • &l - manual line break
To leave any meta-character intact a parameter PreserveMetaCharacters should be set to true.

Example

      Shows how to replace text in the document footer.
[C#]

// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(MyDir + "HeaderFooter.ReplaceText.doc");

HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = false
};

footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options);

doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.doc");
Simple find and replace operation.
[C#]

// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test.
Console.WriteLine(doc.FirstSection.Body.Paragraphs[0].GetText());

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = false;
options.FindWholeWordsOnly = false;

// Replace the text in the document.
doc.Range.Replace("_CustomerName_", "James Bond", options);

// Save the modified document.
doc.Save(ArtifactsDir + "Range.ReplaceSimple.docx");
Shows how to replace all instances of String of text in a table and cell.
[C#]

Document doc = new Document(MyDir + "Table.SimpleTable.doc");

// Get the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = true;
options.FindWholeWordsOnly = true;

// Replace any instances of our String in the entire table.
table.Range.Replace("Carrots", "Eggs", options);
// Replace any instances of our String in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", options);

doc.Save(ArtifactsDir + "Table.ReplaceCellText.doc");
Show changes for headers and footers order
[C#]

Document doc = new Document(MyDir + "HeaderFooter.HeaderFooterOrder.docx");

            // Assert that we use special header and footer for the first page
            // The order for this: first header\footer, even header\footer, primary header\footer
            Section firstPageSection = doc.FirstSection;
            Assert.AreEqual(true, firstPageSection.PageSetup.DifferentFirstPageHeaderFooter);

            ReplaceLog logger = new ReplaceLog();
            FindReplaceOptions options = new FindReplaceOptions { ReplacingCallback = logger };

            doc.Range.Replace(new Regex("(header|footer)"), "", options);

            doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterOrder.docx");
#if __MOBILE__
            Assert.AreEqual("First header\nFirst footer\nSecond header\nSecond footer\nThird header\n" +
                            "Third footer\n", logger.Text);
#else
            Assert.AreEqual("First header\nFirst footer\nSecond header\nSecond footer\nThird header\n" +
                            "Third footer\n", logger.Text.Replace("\r", ""));
#endif
            // Prepare our string builder for assert results without "DifferentFirstPageHeaderFooter"
            logger.ClearText();

            // Remove special first page
            // The order for this: primary header, default header, primary footer, default footer, even header\footer
            firstPageSection.PageSetup.DifferentFirstPageHeaderFooter = false;

            doc.Range.Replace(new Regex("(header|footer)"), "", options);
#if __MOBILE__
            Assert.AreEqual("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\nSecond footer\n", logger.Text);
#else
            Assert.AreEqual("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\nSecond footer\n", logger.Text.Replace("\r", ""));
#endif
        }

        private class ReplaceLog : IReplacingCallback
        {
            public ReplaceAction Replacing(ReplacingArgs args)
            {
                _textBuilder.AppendLine(args.MatchNode.GetText());
                return ReplaceAction.Skip;
            }

            internal void ClearText()
            {
                _textBuilder.Clear();
            }

            internal string Text
            {
                get { return _textBuilder.ToString(); }
            }

            private readonly StringBuilder _textBuilder = new StringBuilder();
        }
See Also
Range Class | Aspose.Words Namespace | Range.Replace Overload List


Range.Replace Method (Regex, String)

Replaces all occurrences of a character pattern specified by a regular expression with another string.

[Visual Basic]
Overloads Public Function Replace( _
ByVal pattern As Regex, _
ByVal replacement As String _
) As Integer
[C#]
public int Replace(
Regex pattern,
string replacement
);

Parameters

pattern
A regular expression pattern used to find matches.
replacement
A string to replace all occurrences of pattern.

Return Value

The number of replacements made.

Remarks

Replaces the whole match captured by the regular expression.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:
  • &p - paragraph break
  • &b - section break
  • &m - page break
  • &l - manual line break
Use method Replace to have more flexible customization.

Example

See Also
Range Class | Aspose.Words Namespace | Range.Replace Overload List


Range.Replace Method (Regex, String, FindReplaceOptions)

Replaces all occurrences of a character pattern specified by a regular expression with another string.

[Visual Basic]
Overloads Public Function Replace( _
ByVal pattern As Regex, _
ByVal replacement As String, _
ByVal options As FindReplaceOptions _
) As Integer
[C#]
public int Replace(
Regex pattern,
string replacement,
FindReplaceOptions options
);

Parameters

pattern
A regular expression pattern used to find matches.
replacement
A string to replace all occurrences of pattern.
options
FindReplaceOptions object to specify additional options.

Return Value

The number of replacements made.

Remarks

Replaces the whole match captured by the regular expression.

Method is able to process breaks in both pattern and replacement strings.

You should use special meta-characters if you need to work with breaks:
  • &p - paragraph break
  • &b - section break
  • &m - page break
  • &l - manual line break
To leave any meta-character intact a parameter PreserveMetaCharacters should be set to true.

Example

      Shows how to replace all occurrences of words "sad" or "mad" to "bad".
[C#]

Document doc = new Document(MyDir + "Document.doc");

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = false;
options.FindWholeWordsOnly = false;

doc.Range.Replace(new Regex("[s|m]ad"), "bad", options);
Shows how to insert content of one document into another during a customized find and replace operation.
[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
Replaces text specified with regular expression with HTML.
[C#]

// Open the document.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);

    doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);

    // Save the modified document.
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
    {
        mOptions = options;
    }

    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document) args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }

    private readonly FindReplaceOptions mOptions;
}
See Also
Range Class | Aspose.Words Namespace | Range.Replace Overload List


Range.ToDocument Method

Constructs a new fully formed document that contains the range.

[Visual Basic]
Public Function ToDocument() As Document
[C#]
public Document ToDocument();

See Also

Range Class | Aspose.Words Namespace


Range.UnlinkFields Method

Unlinks fields in this range.

[Visual Basic]
Public Sub UnlinkFields()
[C#]
public void UnlinkFields();

Remarks

Replaces all the fields in this range with their most recent results.

To unlink fields in the whole document use UnlinkFields.

Example

Shows how to unlink all fields in range

[C#]

Document doc = new Document(MyDir + "Field.UnlinkFields.docx");

Section newSection = (Section)doc.Sections[0].Clone(true);
doc.Sections.Add(newSection);

doc.Sections[1].Range.UnlinkFields();

See Also

Range Class | Aspose.Words Namespace


Range.UpdateFields Method

Updates the values of document fields in this range.

[Visual Basic]
Public Sub UpdateFields()
[C#]
public void UpdateFields();

Remarks

When you open, modify and then save a document, Aspose.Words does not update fields automatically, it keeps them intact. Therefore, you would usually want to call this method before saving if you have modified the document programmatically and want to make sure the proper (calculated) field values appear in the saved document.

There is no need to update fields after executing a mail merge because mail merge is a kind of field update and automatically updates all fields in the document.

This method does not update all field types. For the detailed list of supported field types, see the Programmers Guide.

This method does not update fields that are related to the page layout algorithms (e.g. PAGE, PAGES, PAGEREF). The page layout-related fields are updated when you render a document or call UpdatePageLayout.

To update fields in the whole document use UpdateFields.

Example

Demonstrates how to update document fields in the body of the first section only.

[C#]

doc.FirstSection.Body.Range.UpdateFields();

See Also

Range Class | Aspose.Words Namespace


Revision Class

Represents a revision (tracked change) in a document node or style. Use RevisionType to check the type of this revision.

For a list of all members of this type, see Revision Members.

System.Object
Aspose.Words.Revision

[Visual Basic]
Public Class Revision
[C#]
public class Revision

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Revision Members | Aspose.Words Namespace


Revision Members

Revision overview

Public Instance Properties

Author | Gets or sets the author of this revision. Can not be empty string or null.
DateTime | Gets or sets the date/time of this revision.
Group | Gets the revision group. Returns null if the revision does not belong to any group.
ParentNode | Gets the immediate parent node (owner) of this revision. This property will work for any revision type other than StyleDefinitionChange.
ParentStyle | Gets the immediate parent style (owner) of this revision. This property will work for only for the StyleDefinitionChange revision type.
RevisionType | Gets the type of this revision.

Public Instance Methods

Accept | Accepts this revision.
Reject | Reject this revision.

See Also

Revision Class | Aspose.Words Namespace


Revision Properties

The properties of the Revision class are listed below. For a complete list of Revision class members, see the Revision Members topic.

Public Instance Properties

Author | Gets or sets the author of this revision. Can not be empty string or null.
DateTime | Gets or sets the date/time of this revision.
Group | Gets the revision group. Returns null if the revision does not belong to any group.
ParentNode | Gets the immediate parent node (owner) of this revision. This property will work for any revision type other than StyleDefinitionChange.
ParentStyle | Gets the immediate parent style (owner) of this revision. This property will work for only for the StyleDefinitionChange revision type.
RevisionType | Gets the type of this revision.

See Also

Revision Class | Aspose.Words Namespace


Author Property

Aspose.Words

Revision.Author Property

Gets or sets the author of this revision. Can not be empty string or null.

[Visual Basic]
Public Property Author As String
[C#]
public string Author {get; set;}

See Also

Revision Class | Aspose.Words Namespace


DateTime Property

Aspose.Words

Revision.DateTime Property

Gets or sets the date/time of this revision.

[Visual Basic]
Public Property DateTime As Date
[C#]
public DateTime DateTime {get; set;}

See Also

Revision Class | Aspose.Words Namespace


Group Property

Aspose.Words

Revision.Group Property

Gets the revision group. Returns null if the revision does not belong to any group.

[Visual Basic]
Public ReadOnly Property Group As RevisionGroup
[C#]
public RevisionGroup Group {get;}

Remarks

Revision has no group if revision type is RevisionType.StyleDefinitionChange or if the revision is not longer exist in document context (accepted/rejected).

See Also

Revision Class | Aspose.Words Namespace


ParentNode Property

Aspose.Words

Revision.ParentNode Property

Gets the immediate parent node (owner) of this revision. This property will work for any revision type other than StyleDefinitionChange.

[Visual Basic]
Public ReadOnly Property ParentNode As Node
[C#]
public Node ParentNode {get;}

Remarks

If this revision relates to change of Style formatting, use ParentStyle instead.

See Also

Revision Class | Aspose.Words Namespace


ParentStyle Property

Aspose.Words

Revision.ParentStyle Property

Gets the immediate parent style (owner) of this revision. This property will work for only for the StyleDefinitionChange revision type.

[Visual Basic]
Public ReadOnly Property ParentStyle As Style
[C#]
public Style ParentStyle {get;}

Remarks

If this revision relates to changes on document nodes, use ParentNode instead.

See Also

Revision Class | Aspose.Words Namespace


RevisionType Property

Aspose.Words

Revision.RevisionType Property

Gets the type of this revision.

[Visual Basic]
Public ReadOnly Property RevisionType As RevisionType
[C#]
public RevisionType RevisionType {get;}

See Also

Revision Class | Aspose.Words Namespace


Revision Methods

The methods of the Revision class are listed below. For a complete list of Revision class members, see the Revision Members topic.

Public Instance Methods

Accept | Accepts this revision.
Reject | Reject this revision.

See Also

Revision Class | Aspose.Words Namespace


Revision.Accept Method

Accepts this revision.

[Visual Basic]
Public Sub Accept()
[C#]
public void Accept();

See Also

Revision Class | Aspose.Words Namespace


Revision.Reject Method

Reject this revision.

[Visual Basic]
Public Sub Reject()
[C#]
public void Reject();

See Also

Revision Class | Aspose.Words Namespace


RevisionCollection Class

A collection of Revision objects that represent revisions in the document.

For a list of all members of this type, see RevisionCollection Members.

System.Object
Aspose.Words.RevisionCollection

[Visual Basic]
Public Class RevisionCollection
Implements IEnumerable`1([Aspose.Words.Revision, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class RevisionCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

You do not create instances of this class directly. Use the Revisions property to get revisions present in a document.

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RevisionCollection Members | Aspose.Words Namespace


RevisionCollection Members

RevisionCollection overview

Public Instance Properties

Count | Returns the number of revisions in the collection.
Groups | Collection of revision groups.
Item | Returns a Revision at the specified index.

Public Instance Methods

AcceptAll | Accepts all revisions in this collection.
GetEnumerator | Returns an enumerator object.
RejectAll | Rejects all revisions in this collection.

See Also

RevisionCollection Class | Aspose.Words Namespace


RevisionCollection Properties

The properties of the RevisionCollection class are listed below. For a complete list of RevisionCollection class members, see the RevisionCollection Members topic.

Public Instance Properties

Count | Returns the number of revisions in the collection.
Groups | Collection of revision groups.
Item | Returns a Revision at the specified index.

See Also

RevisionCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

RevisionCollection.Count Property

Returns the number of revisions in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

RevisionCollection Class | Aspose.Words Namespace


Groups Property

Aspose.Words

RevisionCollection.Groups Property

Collection of revision groups.

[Visual Basic]
Public ReadOnly Property Groups As RevisionGroupCollection
[C#]
public RevisionGroupCollection Groups {get;}

See Also

RevisionCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

RevisionCollection.Item Property

Returns a Revision at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Revision
[C#]
public Revision this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

RevisionCollection Class | Aspose.Words Namespace


RevisionCollection Methods

The methods of the RevisionCollection class are listed below. For a complete list of RevisionCollection class members, see the RevisionCollection Members topic.

Public Instance Methods

AcceptAll | Accepts all revisions in this collection.
GetEnumerator | Returns an enumerator object.
RejectAll | Rejects all revisions in this collection.

See Also

RevisionCollection Class | Aspose.Words Namespace


RevisionCollection.AcceptAll Method

Accepts all revisions in this collection.

[Visual Basic]
Public Sub AcceptAll()
[C#]
public void AcceptAll();

See Also

RevisionCollection Class | Aspose.Words Namespace


RevisionCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Revision) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Revision> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

RevisionCollection Class | Aspose.Words Namespace


RevisionCollection.RejectAll Method

Rejects all revisions in this collection.

[Visual Basic]
Public Sub RejectAll()
[C#]
public void RejectAll();

See Also

RevisionCollection Class | Aspose.Words Namespace


RevisionGroup Class

Represents a group of sequential Revision objects.

For a list of all members of this type, see RevisionGroup Members.

System.Object
Aspose.Words.RevisionGroup

[Visual Basic]
Public Class RevisionGroup
[C#]
public class RevisionGroup

Example

Shows how to get info about a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

Console.WriteLine("Revision groups count: {0}\n", doc.Revisions.Groups.Count);

// Get info about all of revisions in document
foreach (RevisionGroup group in doc.Revisions.Groups)
{
    Console.WriteLine("Revision author: {0}; Revision type: {1} \nRevision text: {2}", group.Author,
        group.RevisionType, group.RevisionType);
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RevisionGroup Members | Aspose.Words Namespace


RevisionGroup Members

RevisionGroup overview

Public Instance Properties

Author | Gets the author of this revision group.
RevisionType | Gets the type of revisions included in this group.
Text | Returns inserted/deleted/moved text or description of format change.

See Also

RevisionGroup Class | Aspose.Words Namespace


RevisionGroup Properties

The properties of the RevisionGroup class are listed below. For a complete list of RevisionGroup class members, see the RevisionGroup Members topic.

Public Instance Properties

Author | Gets the author of this revision group.
RevisionType | Gets the type of revisions included in this group.
Text | Returns inserted/deleted/moved text or description of format change.

See Also

RevisionGroup Class | Aspose.Words Namespace


Author Property

Aspose.Words

RevisionGroup.Author Property

Gets the author of this revision group.

[Visual Basic]
Public ReadOnly Property Author As String
[C#]
public string Author {get;}

Example

Shows how to get info about a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

Console.WriteLine("Revision groups count: {0}\n", doc.Revisions.Groups.Count);

// Get info about all of revisions in document
foreach (RevisionGroup group in doc.Revisions.Groups)
{
    Console.WriteLine("Revision author: {0}; Revision type: {1} \nRevision text: {2}", group.Author,
        group.RevisionType, group.RevisionType);
}

See Also

RevisionGroup Class | Aspose.Words Namespace


RevisionType Property

Aspose.Words

RevisionGroup.RevisionType Property

Gets the type of revisions included in this group.

[Visual Basic]
Public ReadOnly Property RevisionType As RevisionType
[C#]
public RevisionType RevisionType {get;}

Example

Shows how to get info about a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

Console.WriteLine("Revision groups count: {0}\n", doc.Revisions.Groups.Count);

// Get info about all of revisions in document
foreach (RevisionGroup group in doc.Revisions.Groups)
{
    Console.WriteLine("Revision author: {0}; Revision type: {1} \nRevision text: {2}", group.Author,
        group.RevisionType, group.RevisionType);
}

See Also

RevisionGroup Class | Aspose.Words Namespace


Text Property

Aspose.Words

RevisionGroup.Text Property

Returns inserted/deleted/moved text or description of format change.

[Visual Basic]
Public ReadOnly Property Text As String
[C#]
public string Text {get;}

Example

Shows how to get info about a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

Console.WriteLine("Revision groups count: {0}\n", doc.Revisions.Groups.Count);

// Get info about all of revisions in document
foreach (RevisionGroup group in doc.Revisions.Groups)
{
    Console.WriteLine("Revision author: {0}; Revision type: {1} \nRevision text: {2}", group.Author,
        group.RevisionType, group.RevisionType);
}

See Also

RevisionGroup Class | Aspose.Words Namespace


RevisionGroupCollection Class

A collection of RevisionGroup objects that represent revision groups in the document.

For a list of all members of this type, see RevisionGroupCollection Members.

System.Object
Aspose.Words.RevisionGroupCollection

[Visual Basic]
NotInheritable Public Class RevisionGroupCollection
Implements IEnumerable`1([Aspose.Words.RevisionGroup, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public sealed class RevisionGroupCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

You do not create instances of this class directly. Use the Groups property to get revision groups present in a document.

Example

Shows how to get info about a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

Console.WriteLine("Revision groups count: {0}\n", doc.Revisions.Groups.Count);

// Get info about all of revisions in document
foreach (RevisionGroup group in doc.Revisions.Groups)
{
    Console.WriteLine("Revision author: {0}; Revision type: {1} \nRevision text: {2}", group.Author,
        group.RevisionType, group.RevisionType);
}
Shows how to get a set of revisions in document.
[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get revision group by index.
RevisionGroup revisionGroup = doc.Revisions.Groups[1];

// Get info about specific revision groups sorted by RevisionType
IEnumerable<string> revisionGroupCollectionInsertionType =
    doc.Revisions.Groups.Where(p => p.RevisionType == RevisionType.Insertion).Select(p =>
        string.Format("Revision type: {0},\nRevision author: {1},\nRevision text: {2}.\n",
            p.RevisionType.ToString(), p.Author, p.Text));

foreach (string revisionGroupInfo in revisionGroupCollectionInsertionType)
{
    Console.WriteLine(revisionGroupInfo);
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RevisionGroupCollection Members | Aspose.Words Namespace


RevisionGroupCollection Members

RevisionGroupCollection overview

Public Instance Properties

Count | Returns the number of revision groups in the collection.
Item | Returns a revision group at the specified index.

Public Instance Methods

GetEnumerator Returns an enumerator object.

See Also

RevisionGroupCollection Class | Aspose.Words Namespace


RevisionGroupCollection Properties

The properties of the RevisionGroupCollection class are listed below. For a complete list of RevisionGroupCollection class members, see the RevisionGroupCollection Members topic.

Public Instance Properties

Count | Returns the number of revision groups in the collection.
Item | Returns a revision group at the specified index.

See Also

RevisionGroupCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

RevisionGroupCollection.Count Property

Returns the number of revision groups in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to get info about a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

Console.WriteLine("Revision groups count: {0}\n", doc.Revisions.Groups.Count);

// Get info about all of revisions in document
foreach (RevisionGroup group in doc.Revisions.Groups)
{
    Console.WriteLine("Revision author: {0}; Revision type: {1} \nRevision text: {2}", group.Author,
        group.RevisionType, group.RevisionType);
}

See Also

RevisionGroupCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

RevisionGroupCollection.Item Property

Returns a revision group at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As RevisionGroup
[C#]
public RevisionGroup this[
int index
] {get;}

Example

Shows how to get a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get revision group by index.
RevisionGroup revisionGroup = doc.Revisions.Groups[1];

// Get info about specific revision groups sorted by RevisionType
IEnumerable<string> revisionGroupCollectionInsertionType =
    doc.Revisions.Groups.Where(p => p.RevisionType == RevisionType.Insertion).Select(p =>
        string.Format("Revision type: {0},\nRevision author: {1},\nRevision text: {2}.\n",
            p.RevisionType.ToString(), p.Author, p.Text));

foreach (string revisionGroupInfo in revisionGroupCollectionInsertionType)
{
    Console.WriteLine(revisionGroupInfo);
}

See Also

RevisionGroupCollection Class | Aspose.Words Namespace


RevisionGroupCollection Methods

The methods of the RevisionGroupCollection class are listed below. For a complete list of RevisionGroupCollection class members, see the RevisionGroupCollection Members topic.

Public Instance Methods

GetEnumerator Returns an enumerator object.

See Also

RevisionGroupCollection Class | Aspose.Words Namespace


RevisionGroupCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of RevisionGroup) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<RevisionGroup> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

RevisionGroupCollection Class | Aspose.Words Namespace


RevisionType Enumeration

Specifies the type of change being tracked in Revision.

[Visual Basic]
Public Enum RevisionType
[C#]
public enum RevisionType

Example

Shows how to get a set of revisions in document.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get revision group by index.
RevisionGroup revisionGroup = doc.Revisions.Groups[1];

// Get info about specific revision groups sorted by RevisionType
IEnumerable<string> revisionGroupCollectionInsertionType =
    doc.Revisions.Groups.Where(p => p.RevisionType == RevisionType.Insertion).Select(p =>
        string.Format("Revision type: {0},\nRevision author: {1},\nRevision text: {2}.\n",
            p.RevisionType.ToString(), p.Author, p.Text));

foreach (string revisionGroupInfo in revisionGroupCollectionInsertionType)
{
    Console.WriteLine(revisionGroupInfo);
}

Members

Member Name | Description | Value
Insertion | New content was inserted in the document. | 0
Deletion | Content was removed from the document. | 1
FormatChange | Change of formatting was applied to the parent node. | 2
StyleDefinitionChange | Change of formatting was applied to the parent style. | 3
Moving | Content was moved in the document. | 4

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


RtfLoadOptions Class

Allows to specify additional options when loading Rtf document into a Document object.

For a list of all members of this type, see RtfLoadOptions Members.

System.Object
Aspose.Words.LoadOptions
Aspose.Words.RtfLoadOptions

[Visual Basic]
Public Class RtfLoadOptions
Inherits LoadOptions
[C#]
public class RtfLoadOptions : LoadOptions

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RtfLoadOptions Members | Aspose.Words Namespace


RtfLoadOptions Members

RtfLoadOptions overview

Public Instance Constructors

RtfLoadOptions Constructor Initializes a new instance of this class with default values.

Public Instance Properties

AnnotationsAtBlockLevel (inherited from LoadOptions) | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri (inherited from LoadOptions) | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath (inherited from LoadOptions) | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
Encoding (inherited from LoadOptions) | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings (inherited from LoadOptions) | Allows to specify document font settings.
LanguagePreferences (inherited from LoadOptions) | Gets language preferences that will be used when document is loading.
LoadFormat (inherited from LoadOptions) | Specifies the format of the document to be loaded. Default is Auto.
MswVersion (inherited from LoadOptions) | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password (inherited from LoadOptions) | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreserveIncludePictureField (inherited from LoadOptions) | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
RecognizeUtf8Text | When set to true, CharsetDetector will try to detect UTF8 characters, they will be preserved during import. Default value is false.
ResourceLoadingCallback (inherited from LoadOptions) | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
UpdateDirtyFields (inherited from LoadOptions) | Specifies whether to update the fields with the dirty attribute.
WarningCallback (inherited from LoadOptions) | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

RtfLoadOptions Class | Aspose.Words Namespace


RtfLoadOptions Constructor

Initializes a new instance of this class with default values.

[Visual Basic]
Overloads Public Sub New()
[C#]
public RtfLoadOptions();

See Also

RtfLoadOptions Class | Aspose.Words Namespace


RtfLoadOptions Properties

The properties of the RtfLoadOptions class are listed below. For a complete list of RtfLoadOptions class members, see the RtfLoadOptions Members topic.

Public Instance Properties

AnnotationsAtBlockLevel (inherited from LoadOptions) | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri (inherited from LoadOptions) | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath (inherited from LoadOptions) | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
Encoding (inherited from LoadOptions) | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings (inherited from LoadOptions) | Allows to specify document font settings.
LanguagePreferences (inherited from LoadOptions) | Gets language preferences that will be used when document is loading.
LoadFormat (inherited from LoadOptions) | Specifies the format of the document to be loaded. Default is Auto.
MswVersion (inherited from LoadOptions) | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password (inherited from LoadOptions) | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreserveIncludePictureField (inherited from LoadOptions) | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
RecognizeUtf8Text | When set to true, CharsetDetector will try to detect UTF8 characters, they will be preserved during import. Default value is false.
ResourceLoadingCallback (inherited from LoadOptions) | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
UpdateDirtyFields (inherited from LoadOptions) | Specifies whether to update the fields with the dirty attribute.
WarningCallback (inherited from LoadOptions) | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

RtfLoadOptions Class | Aspose.Words Namespace


RecognizeUtf8Text Property

Aspose.Words

RtfLoadOptions.RecognizeUtf8Text Property

When set to true, CharsetDetector will try to detect UTF8 characters, they will be preserved during import.

Default value is false.
[Visual Basic]
Public Property RecognizeUtf8Text As Boolean
[C#]
public bool RecognizeUtf8Text {get; set;}

Example

Shows how to detect UTF8 characters during import.

[C#]

RtfLoadOptions loadOptions = new RtfLoadOptions
{
    RecognizeUtf8Text = true
};

Document doc = new Document(MyDir + "RtfLoadOptions.RecognizeUtf8Text.rtf", loadOptions);
doc.Save(ArtifactsDir + "RtfLoadOptions.RecognizeUtf8Text.rtf");

See Also

RtfLoadOptions Class | Aspose.Words Namespace


Run Class

Represents a run of characters with the same font formatting.

For a list of all members of this type, see Run Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.Run

[Visual Basic]
Public Class Run
Inherits Inline
[C#]
public class Run : Inline

Remarks

All text of the document is stored in runs of text.

Run can only be a child of Paragraph.

Example

Shows how to add a formatted run of text to a document using the object model.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);
Gets all fonts used in a document.
[C#]

Document doc = new Document(MyDir + "Font.Names.doc");

// Select all runs in the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

// Use a hashtable so we will keep only unique font names.
Hashtable fontNames = new Hashtable();

foreach (Run run in runs.OfType<Run>())
{
    // This adds an entry into the hashtable.
    // The key is the font name. The value is null, we don't need the value.
    fontNames[run.Font.Name] = null;
}

// There are two fonts used in this document.
Console.WriteLine("Font Count: " + fontNames.Count);
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Run Members | Aspose.Words Namespace


Run Members

Run overview

Public Instance Constructors

Run Overloaded. Initializes a new instance of the Run class.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Run.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Text | Gets or sets the text of the run.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText | Gets the text of the run.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Run Class | Aspose.Words Namespace


Run Constructor

Initializes a new instance of the Run class.

Overload List

Initializes a new instance of the Run class.

public Run(DocumentBase);

Initializes a new instance of the Run class.

public Run(DocumentBase,string);

See Also

Run Class | Aspose.Words Namespace


Run Constructor (DocumentBase)

Initializes a new instance of the Run class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Run(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Run is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Run to the document use InsertAfter or InsertBefore on the paragraph where you want the run inserted.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Run Class | Aspose.Words Namespace | Run Constructor Overload List


Run Constructor (DocumentBase, String)

Initializes a new instance of the Run class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal text As String _
)
[C#]
public Run(
DocumentBase doc,
string text
);

Parameters

doc
The owner document.
text
The text of the run.

Remarks

When Run is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Run to the document use InsertAfter or InsertBefore on the paragraph where you want the run inserted.

Example

Shows how to add a formatted run of text to a document using the object model.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);

See Also

Run Class | Aspose.Words Namespace | Run Constructor Overload List


Run Properties

The properties of the Run class are listed below. For a complete list of Run class members, see the Run Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Run.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Text | Gets or sets the text of the run.

See Also

Run Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Run.NodeType Property

Returns NodeType.Run.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Run Class | Aspose.Words Namespace


Text Property

Aspose.Words

Run.Text Property

Gets or sets the text of the run.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Run Class | Aspose.Words Namespace


Run Methods

The methods of the Run class are listed below. For a complete list of Run class members, see the Run Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText | Gets the text of the run.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Run Class | Aspose.Words Namespace


Run.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls DocumentVisitor.VisitRun.

For more info see the Visitor design pattern.

See Also

Run Class | Aspose.Words Namespace


Run.GetText Method

Gets the text of the run.

[Visual Basic]
Overrides Public Function GetText() As String
[C#]
public override string GetText();

Return Value

The text of the run.

See Also

Run Class | Aspose.Words Namespace


RunCollection Class

Provides typed access to a collection of Run nodes.

For a list of all members of this type, see RunCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.RunCollection

[Visual Basic]
Public Class RunCollection
Inherits NodeCollection
[C#]
public class RunCollection : NodeCollection

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RunCollection Members | Aspose.Words Namespace


RunCollection Members

RunCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Run at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all runs from the collection to a new array of runs.

See Also

RunCollection Class | Aspose.Words Namespace


RunCollection Properties

The properties of the RunCollection class are listed below. For a complete list of RunCollection class members, see the RunCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Run at the given index.

See Also

RunCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

RunCollection.Item Property

Retrieves a Run at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Run
[C#]
new public Run this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

RunCollection Class | Aspose.Words Namespace


RunCollection Methods

The methods of the RunCollection class are listed below. For a complete list of RunCollection class members, see the RunCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all runs from the collection to a new array of runs.

See Also

RunCollection Class | Aspose.Words Namespace


RunCollection.ToArray Method

Copies all runs from the collection to a new array of runs.

[Visual Basic]
Public Function ToArray() As Run()
[C#]
new public Run[] ToArray();

Return Value

An array of runs.

See Also

RunCollection Class | Aspose.Words Namespace


SaveFormat Enumeration

Indicates the format in which the document is saved.

[Visual Basic]
Public Enum SaveFormat
[C#]
public enum SaveFormat

Remarks

Example

Converts from DOC to HTML format.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Save(ArtifactsDir + "Document.ConvertToHtml.html", SaveFormat.Html);

Members

Member Name | Description | Value
Unknown | Default, invalid value for file format. | 0
Doc | Saves the document in the Microsoft Word 97 - 2007 Document format. | 10
Dot | Saves the document in the Microsoft Word 97 - 2007 Template format. | 11
Docx | Saves the document as an Office Open XML WordprocessingML Document (macro-free). | 20
Docm | Saves the document as an Office Open XML WordprocessingML Macro-Enabled Document. | 21
Dotx | Saves the document as an Office Open XML WordprocessingML Template (macro-free). | 22
Dotm | Saves the document as an Office Open XML WordprocessingML Macro-Enabled Template. | 23
FlatOpc | Saves the document as an Office Open XML WordprocessingML stored in a flat XML file instead of a ZIP package. | 24
FlatOpcMacroEnabled | Saves the document as an Office Open XML WordprocessingML Macro-Enabled Document stored in a flat XML file instead of a ZIP package. | 25
FlatOpcTemplate | Saves the document as an Office Open XML WordprocessingML Template (macro-free) stored in a flat XML file instead of a ZIP package. | 26
FlatOpcTemplateMacroEnabled | Saves the document as an Office Open XML WordprocessingML Macro-Enabled Template stored in a flat XML file instead of a ZIP package. | 27
Rtf | Saves the document in the RTF format. All characters above 7-bits are escaped as hexadecimal or Unicode characters. | 30
WordML | Saves the document in the Microsoft Word 2003 WordprocessingML format. | 31
Pdf | Saves the document as PDF (Adobe Portable Document) format. | 40
Xps | Saves the document in the XPS (XML Paper Specification) format. | 41
XamlFixed | Saves the document in the Extensible Application Markup Language (XAML) format as a fixed document. | 42
Svg | Saves the document in the Svg (Scalable Vector Graphics) format. | 44
HtmlFixed | Saves the document in the HTML format using absolutely positioned elements | 45
OpenXps | Saves the document in the OpenXPS (Ecma-388) format. | 46
Ps | Saves the document in the PS (PostScript) format. | 47
Pcl | Saves the document in the PCL (Printer Control Language) format. | 48
Html | Saves the document in the HTML format. | 50
Mhtml | Saves the document in the MHTML (Web archive) format. | 51
Epub | Saves the document in the IDPF EPUB format. | 52
Odt | Saves the document as an ODF Text Document. | 60
Ott | Saves the document as an ODF Text Document Template. | 61
Text | Saves the document in the plain text format. | 70
XamlFlow | Beta. Saves the document in the Extensible Application Markup Language (XAML) format as a flow document. | 71
XamlFlowPack | Beta. Saves the document in the Extensible Application Markup Language (XAML) package format as a flow document. | 72
Markdown | Saves the document in the Markdown format. | 73
Tiff | Renders a page or pages of the document and saves them into a single or multipage TIFF file. | 100
Png | Renders a page of the document and saves it as a PNG file. | 101
Bmp | Renders a page of the document and saves it as a BMP file. | 102
Emf | Renders a page of the document and saves it as a vector EMF (Enhanced Meta File) file. | 103
Jpeg | Renders a page of the document and saves it as a JPEG file. | 104
Gif | Renders a page of the document and saves it as a GIF file. | 105

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace | Save | SaveOptions


Section Class

Represents a single section in a document.

For a list of all members of this type, see Section Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Section

[Visual Basic]
NotInheritable Public Class Section
Inherits CompositeNode
[C#]
public sealed class Section : CompositeNode

Remarks

Section can have one Body and maximum one HeaderFooter of each HeaderFooterType. Body and HeaderFooter nodes can be in any order inside Section.

A minimal valid section needs to have Body with one Paragraph.

Each section has its own set of properties that specify page size, orientation, margins etc.

You can create a copy of a section using Clone. The copy can be inserted into the same or different document.

To add, insert or remove a whole section including section break and section properties use methods of the Sections object.

To copy and insert just content of the section excluding the section break and section properties use AppendContent and PrependContent methods.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Section Members | Aspose.Words Namespace


Section Members

Section overview

Public Instance Constructors

Section Constructor Initializes a new instance of the Section class.

Public Instance Properties

Body | Returns the Body child node of the section.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HeadersFooters | Provides access to the headers and footers nodes of the section.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Section.
PageSetup | Returns an object that represents page setup and section properties.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
ProtectedForForms | True if the section is protected for forms. When a section is protected for forms, users can select and modify text only in form fields in Microsoft Word.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendContent | Inserts a copy of content of the source section at the end of this section.
ClearContent | Clears the section.
ClearHeadersFooters | Clears the headers and footers of this section.
Clone | Overloaded. Creates a duplicate of this section.
Clone (inherited from Node) | Overloaded.
DeleteHeaderFooterShapes | Deletes all shapes (drawing objects) from the headers and footers of this section.
EnsureMinimum | Ensures that the section has Body with one Paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PrependContent | Inserts a copy of content of the source section at the beginning of this section.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Section Class | Aspose.Words Namespace


Section Constructor

Initializes a new instance of the Section class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Section(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When the section is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To include Section into a document use Document.InsertAfter, Document.InsertBefore or Sections.Add and Section.Insert methods.

Example

Creates a simple document from scratch using the Aspose.Words object model.

[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Section Class | Aspose.Words Namespace


Section Properties

The properties of the Section class are listed below. For a complete list of Section class members, see the Section Members topic.

Public Instance Properties

Body | Returns the Body child node of the section.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HeadersFooters | Provides access to the headers and footers nodes of the section.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Section.
PageSetup | Returns an object that represents page setup and section properties.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
ProtectedForForms | True if the section is protected for forms. When a section is protected for forms, users can select and modify text only in form fields in Microsoft Word.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

Section Class | Aspose.Words Namespace


Body Property

Aspose.Words

Section.Body Property

Returns the Body child node of the section.

[Visual Basic]
Public ReadOnly Property Body As Body
[C#]
public Body Body {get;}

Remarks

Body contains main text of the section.

Returns null if the section does not have a Body node among its children.

Example

Clears main text from all sections from the document leaving the sections themselves.

[C#]

// Open a document.
Document doc = new Document(MyDir + "Section.BodyEnsureMinimum.doc");

// This shows what is in the document originally. The document has two sections.
Console.WriteLine(doc.GetText());

// Loop through all sections in the document.
foreach (Section section in doc.Sections.OfType<Section>())
{
    // Each section has a Body node that contains main story (main text) of the section.
    Body body = section.Body;

    // This clears all nodes from the body.
    body.RemoveAllChildren();

    // Technically speaking, for the main story of a section to be valid, it needs to have
    // at least one empty paragraph. That's what the EnsureMinimum method does.
    body.EnsureMinimum();
}

// Check how the content of the document looks now.
Console.WriteLine(doc.GetText());

See Also

Section Class | Aspose.Words Namespace


HeadersFooters Property

Aspose.Words

Section.HeadersFooters Property

Provides access to the headers and footers nodes of the section.

[Visual Basic]
Public ReadOnly Property HeadersFooters As HeaderFooterCollection
[C#]
public HeaderFooterCollection HeadersFooters {get;}

Example

Shows how to replace text in the document footer.

[C#]

// Open the template document, containing obsolete copyright information in the footer.
Document doc = new Document(MyDir + "HeaderFooter.ReplaceText.doc");

HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];

FindReplaceOptions options = new FindReplaceOptions
{
    MatchCase = false,
    FindWholeWordsOnly = false
};

footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options);

doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.doc");
Deletes all footers from all sections, but leaves headers intact.
[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

foreach (Section section in doc.OfType<Section>())
{
    // Up to three different footers are possible in a section (for first, even and odd pages).
    // We check and delete all of them.
    HeaderFooter footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    footer?.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    footer?.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    footer?.Remove();
}

doc.Save(ArtifactsDir + "HeaderFooter.RemoveFooters.doc");

See Also

Section Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

Section.NodeType Property

Returns NodeType.Section.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Section Class | Aspose.Words Namespace


PageSetup Property

Aspose.Words

Section.PageSetup Property

Returns an object that represents page setup and section properties.

[Visual Basic]
Public ReadOnly Property PageSetup As PageSetup
[C#]
public PageSetup PageSetup {get;}

Example

Creates a page border that looks like a wide blue band at the top of the first page only.

[C#]

Document doc = new Document();

PageSetup ps = doc.Sections[0].PageSetup;
ps.BorderAlwaysInFront = false;
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge;
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage;

Border border = ps.Borders[BorderType.Top];
border.LineStyle = LineStyle.Single;
border.LineWidth = 30;
border.Color = Color.Blue;
border.DistanceFromText = 0;

doc.Save(ArtifactsDir + "PageSetup.PageBorderTop.doc");
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

See Also

Section Class | Aspose.Words Namespace


ProtectedForForms Property

Aspose.Words

Section.ProtectedForForms Property

True if the section is protected for forms. When a section is protected for forms, users can select and modify text only in form fields in Microsoft Word.

[Visual Basic]
Public Property ProtectedForForms As Boolean
[C#]
public bool ProtectedForForms {get; set;}

Example

Protects a section so only editing in form fields is possible.

[C#]

// Create a blank document
Document doc = new Document();

// Insert two sections with some text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Section 1. Unprotected.");
builder.InsertBreak(BreakType.SectionBreakContinuous);
builder.Writeln("Section 2. Protected.");

// Section protection only works when document protection is turned and only editing in form fields is allowed.
doc.Protect(ProtectionType.AllowOnlyFormFields);

// By default, all sections are protected, but we can selectively turn protection off.
doc.Sections[0].ProtectedForForms = false;

builder.Document.Save(ArtifactsDir + "Section.Protect.doc");

See Also

Section Class | Aspose.Words Namespace


Section Methods

The methods of the Section class are listed below. For a complete list of Section class members, see the Section Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendContent | Inserts a copy of content of the source section at the end of this section.
ClearContent | Clears the section.
ClearHeadersFooters | Clears the headers and footers of this section.
Clone | Overloaded. Creates a duplicate of this section.
Clone (inherited from Node) | Overloaded.
DeleteHeaderFooterShapes | Deletes all shapes (drawing objects) from the headers and footers of this section.
EnsureMinimum | Ensures that the section has Body with one Paragraph.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PrependContent | Inserts a copy of content of the source section at the beginning of this section.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Section Class | Aspose.Words Namespace


Section.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitSectionStart, then calls Accept for all child nodes of the section and calls DocumentVisitor.VisitSectionEnd at the end.

See Also

Section Class | Aspose.Words Namespace


Section.AppendContent Method

Inserts a copy of content of the source section at the end of this section.

[Visual Basic]
Public Sub AppendContent( _
ByVal sourceSection As Section _
)
[C#]
public void AppendContent(
Section sourceSection
);

Parameters

sourceSection
The section to copy content from.

Remarks

Only content of Body of the source section is copied, page setup, headers and footers are not copied.

The nodes are automatically imported if the source section belongs to a different document.

No new section is created in the destination document.

Example

Shows how to append content of an existing section. The number of sections in the document remains the same.

[C#]

Document doc = new Document(MyDir + "Section.AppendContent.doc");

// This is the section that we will append and prepend to.
Section section = doc.Sections[2];

// This copies content of the 1st section and inserts it at the beginning of the specified section.
Section sectionToPrepend = doc.Sections[0];
section.PrependContent(sectionToPrepend);

// This copies content of the 2nd section and inserts it at the end of the specified section.
Section sectionToAppend = doc.Sections[1];
section.AppendContent(sectionToAppend);

See Also

Section Class | Aspose.Words Namespace


Section.ClearContent Method

Clears the section.

[Visual Basic]
Public Sub ClearContent()
[C#]
public void ClearContent();

Remarks

The text of Body is cleared, only one empty paragraph is left that represents the section break.

The text of all headers and footers is cleared, but HeaderFooter objects themselves are not removed.

Example

Shows how to delete main content of a section.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Section section = doc.Sections[0];
section.ClearContent();

See Also

Section Class | Aspose.Words Namespace


Section.ClearHeadersFooters Method

Clears the headers and footers of this section.

[Visual Basic]
Public Sub ClearHeadersFooters()
[C#]
public void ClearHeadersFooters();

Remarks

The text of all headers and footers is cleared, but HeaderFooter objects themselves are not removed.

This makes headers and footers of this section linked to headers and footers of the previous section.

Example

Clears content of all headers and footers in a section.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Section section = doc.Sections[0];
section.ClearHeadersFooters();

See Also

Section Class | Aspose.Words Namespace


Clone Method

Aspose.Words

Section.Clone Method

Creates a duplicate of this section.

Overload List

Creates a duplicate of this section.

public Section Clone();

Inherited from Node.

public Node Clone(bool);

See Also

Section Class | Aspose.Words Namespace


Section.Clone Method ()

Creates a duplicate of this section.

[Visual Basic]
Overloads Public Function Clone() As Section
[C#]
public Section Clone();

Example

Shows how to add/remove sections in a document.

[C#]

// Open the document.
Document doc = new Document(MyDir + "Section.AddRemove.doc");

// This shows what is in the document originally. The document has two sections.
Console.WriteLine(doc.GetText());

// Delete the first section from the document
doc.Sections.RemoveAt(0);

// Duplicate the last section and append the copy to the end of the document.
int lastSectionIdx = doc.Sections.Count - 1;
Section newSection = doc.Sections[lastSectionIdx].Clone();
doc.Sections.Add(newSection);

// Check what the document contains after we changed it.
Console.WriteLine(doc.GetText());

See Also

Section Class | Aspose.Words Namespace | Section.Clone Overload List


Section.DeleteHeaderFooterShapes Method

Deletes all shapes (drawing objects) from the headers and footers of this section.

[Visual Basic]
Public Sub DeleteHeaderFooterShapes()
[C#]
public void DeleteHeaderFooterShapes();

Example

Removes all images and shapes from all headers footers in a section.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Section section = doc.Sections[0];
section.DeleteHeaderFooterShapes();

See Also

Section Class | Aspose.Words Namespace


Section.EnsureMinimum Method

Ensures that the section has Body with one Paragraph.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Ensures that a section is valid.

[C#]

// Create a blank document
Document doc = new Document();
Section section = doc.FirstSection;

// Makes sure that the section contains a body with at least one paragraph.
section.EnsureMinimum();

See Also

Section Class | Aspose.Words Namespace


Section.PrependContent Method

Inserts a copy of content of the source section at the beginning of this section.

[Visual Basic]
Public Sub PrependContent( _
ByVal sourceSection As Section _
)
[C#]
public void PrependContent(
Section sourceSection
);

Parameters

sourceSection
The section to copy content from.

Remarks

Only content of Body of the source section is copied, page setup, headers and footers are not copied.

The nodes are automatically imported if the source section belongs to a different document.

No new section is created in the destination document.

Example

Shows how to append content of an existing section. The number of sections in the document remains the same.

[C#]

Document doc = new Document(MyDir + "Section.AppendContent.doc");

// This is the section that we will append and prepend to.
Section section = doc.Sections[2];

// This copies content of the 1st section and inserts it at the beginning of the specified section.
Section sectionToPrepend = doc.Sections[0];
section.PrependContent(sectionToPrepend);

// This copies content of the 2nd section and inserts it at the end of the specified section.
Section sectionToAppend = doc.Sections[1];
section.AppendContent(sectionToAppend);

See Also

Section Class | Aspose.Words Namespace


SectionCollection Class

A collection of Section objects in the document.

For a list of all members of this type, see SectionCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.SectionCollection

[Visual Basic]
Public Class SectionCollection
Inherits NodeCollection
[C#]
public class SectionCollection : NodeCollection

Remarks

A Microsoft Word document can contain multiple sections. To create a section in a Microsoft Word, select the Insert/Break command and select a break type. The break specifies whether section starts on a new page or on the same page.

Programmatically inserting and removing sections can be used to customize documents produced during mail merge. If a document needs to have different content or parts of the content depending on some criteria, then you can create a "master" document that contains multiple sections and delete some of the sections before or after mail merge.

Example

Shows how to add/remove sections in a document.

[C#]

// Open the document.
Document doc = new Document(MyDir + "Section.AddRemove.doc");

// This shows what is in the document originally. The document has two sections.
Console.WriteLine(doc.GetText());

// Delete the first section from the document
doc.Sections.RemoveAt(0);

// Duplicate the last section and append the copy to the end of the document.
int lastSectionIdx = doc.Sections.Count - 1;
Section newSection = doc.Sections[lastSectionIdx].Clone();
doc.Sections.Add(newSection);

// Check what the document contains after we changed it.
Console.WriteLine(doc.GetText());

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SectionCollection Members | Aspose.Words Namespace


SectionCollection Members

SectionCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a section at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all sections from the collection to a new array of sections.

See Also

SectionCollection Class | Aspose.Words Namespace


SectionCollection Properties

The properties of the SectionCollection class are listed below. For a complete list of SectionCollection class members, see the SectionCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a section at the given index.

See Also

SectionCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

SectionCollection.Item Property

Retrieves a section at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Section
[C#]
new public Section this[
int index
] {get;}

Parameters

index
An index into the list of sections.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to access a section at the specified index.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Section section = doc.Sections[0];
Shows when to request page layout of the document to be recalculated.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Saving a document to PDF or to image or printing for the first time will automatically
// layout document pages and this information will be cached inside the document.
doc.Save(ArtifactsDir + "Rendering.UpdatePageLayout1.pdf");

// Modify the document in any way.
doc.Styles["Normal"].Font.Size = 6;
doc.Sections[0].PageSetup.Orientation = Aspose.Words.Orientation.Landscape;

// In the current version of Aspose.Words, modifying the document does not automatically rebuild
// the cached page layout. If you want to save to PDF or render a modified document again,
// you need to manually request page layout to be updated.
doc.UpdatePageLayout();

doc.Save(ArtifactsDir + "Rendering.UpdatePageLayout2.pdf");

See Also

SectionCollection Class | Aspose.Words Namespace


SectionCollection Methods

The methods of the SectionCollection class are listed below. For a complete list of SectionCollection class members, see the SectionCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all sections from the collection to a new array of sections.

See Also

SectionCollection Class | Aspose.Words Namespace


SectionCollection.ToArray Method

Copies all sections from the collection to a new array of sections.

[Visual Basic]
Public Function ToArray() As Section()
[C#]
new public Section[] ToArray();

Return Value

An array of sections.

See Also

SectionCollection Class | Aspose.Words Namespace


SectionLayoutMode Enumeration

Specifies the layout mode for a section allowing to define the document grid behavior.

[Visual Basic]
Public Enum SectionLayoutMode
[C#]
public enum SectionLayoutMode

Example

Creates headers and footers different for first, even and odd pages using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

PageSetup ps = builder.PageSetup;
ps.DifferentFirstPageHeaderFooter = true;
ps.OddAndEvenPagesHeaderFooter = true;
ps.LayoutMode = SectionLayoutMode.LineGrid;
ps.CharactersPerLine = 1;
ps.LinesPerPage = 1;

builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Writeln("First page header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Writeln("Even pages header.");

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Odd pages header.");

// Move back to the main story of the first section.
builder.MoveToSection(0);
builder.Writeln("Text page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Text page 3.");

builder.Document.Save(ArtifactsDir + "PageSetup.DifferentHeaders.doc");

Members

Member Name | Description | Value
Default | Specifies that no document grid shall be applied to the contents of the corresponding section in the document. | 0
Grid | Specifies that the corresponding section shall have both the additional line pitch and character pitch added to each line and character within it in order to maintain a specific number of lines per page and characters per line. Characters will not be automatically aligned with gridlines on typing. | 1
LineGrid | Specifies that the corresponding section shall have additional line pitch added to each line within it in order to maintain the specified number of lines per page. | 2
SnapToChars | Specifies that the corresponding section shall have both the additional line pitch and character pitch added to each line and character within it in order to maintain a specific number of lines per page and characters per line. Characters will be automatically aligned with gridlines on typing. | 3

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


SectionStart Enumeration

The type of break at the beginning of the section.

[Visual Basic]
Public Enum SectionStart
[C#]
public enum SectionStart

Example

Specifies how the section starts, from a new page, on the same page or other.

[C#]

Document doc = new Document();
doc.Sections[0].PageSetup.SectionStart = Aspose.Words.SectionStart.Continuous;
Creates a simple document from scratch using the Aspose.Words object model.
[C#]

// Create an "empty" document. Note that like in Microsoft Word,
// the empty document has one section, body and one paragraph in it.
Document doc = new Document();

// This truly makes the document empty. No sections (not possible in Microsoft Word).
doc.RemoveAllChildren();

// Create a new section node.
// Note that the section has not yet been added to the document,
// but we have to specify the parent document.
Section section = new Section(doc);

// Append the section to the document.
doc.AppendChild(section);

// Lets set some properties for the section.
section.PageSetup.SectionStart = SectionStart.NewPage;
section.PageSetup.PaperSize = PaperSize.Letter;

// The section that we created is empty, lets populate it. The section needs at least the Body node.
Body body = new Body(doc);
section.AppendChild(body);

// The body needs to have at least one paragraph.
// Note that the paragraph has not yet been added to the document,
// but we have to specify the parent document.
// The parent document is needed so the paragraph can correctly work
// with styles and other document-wide information.
Paragraph para = new Paragraph(doc);
body.AppendChild(para);

// We can set some formatting for the paragraph
para.ParagraphFormat.StyleName = "Heading 1";
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// So far we have one empty paragraph in the document.
// The document is valid and can be saved, but lets add some text before saving.
// Create a new run of text and add it to our paragraph.
Run run = new Run(doc);
run.Text = "Hello World!";
run.Font.Color = Color.Red;
para.AppendChild(run);

// As a matter of interest, you can retrieve text of the whole document and
// see that \x000c is automatically appended. \x000c is the end of section character.
Console.WriteLine("Hello World!\x000c");

// Save the document.
doc.Save(ArtifactsDir + "Section.CreateFromScratch.doc");

Members

Member Name | Description | Value
Continuous | The new section starts on the same page as the previous section. | 0
NewColumn | The section starts from a new column. | 1
NewPage | The section starts from a new page. | 2
EvenPage | The section starts on a new even page. | 3
OddPage | The section starts on a new odd page. | 4

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Shading Class

Contains shading attributes for an object.

For a list of all members of this type, see Shading Members.

System.Object
Aspose.Words.InternableComplexAttr
Aspose.Words.Shading

[Visual Basic]
Public Class Shading
Inherits InternableComplexAttr
[C#]
public class Shading : InternableComplexAttr

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");
Shows how to format table and cell with different borders and shadings
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Shading Members | Aspose.Words Namespace


Shading Members

Shading overview

Public Instance Properties

BackgroundPatternColor | Gets or sets the color that's applied to the background of the Shading object.
ForegroundPatternColor | Gets or sets the color that's applied to the foreground of the Shading object.
Texture | Gets or sets the shading texture.

Public Instance Methods

ClearFormatting | Removes shading from the object.
Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.

See Also

Shading Class | Aspose.Words Namespace


Shading Properties

The properties of the Shading class are listed below. For a complete list of Shading class members, see the Shading Members topic.

Public Instance Properties

BackgroundPatternColor | Gets or sets the color that's applied to the background of the Shading object.
ForegroundPatternColor | Gets or sets the color that's applied to the foreground of the Shading object.
Texture | Gets or sets the shading texture.

See Also

Shading Class | Aspose.Words Namespace


BackgroundPatternColor Property

Aspose.Words

Shading.BackgroundPatternColor Property

Gets or sets the color that's applied to the background of the Shading object.

[Visual Basic]
Public Property BackgroundPatternColor As Color
[C#]
public Color BackgroundPatternColor {get; set;}

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");
Shows how to format table and cell with different borders and shadings
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

Shading Class | Aspose.Words Namespace


ForegroundPatternColor Property

Aspose.Words

Shading.ForegroundPatternColor Property

Gets or sets the color that's applied to the foreground of the Shading object.

[Visual Basic]
Public Property ForegroundPatternColor As Color
[C#]
public Color ForegroundPatternColor {get; set;}

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");

See Also

Shading Class | Aspose.Words Namespace


Texture Property

Aspose.Words

Shading.Texture Property

Gets or sets the shading texture.

[Visual Basic]
Public Property Texture As TextureIndex
[C#]
public TextureIndex Texture {get; set;}

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");

See Also

Shading Class | Aspose.Words Namespace


Shading Methods

The methods of the Shading class are listed below. For a complete list of Shading class members, see the Shading Members topic.

Public Instance Methods

ClearFormatting | Removes shading from the object.
Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.

See Also

Shading Class | Aspose.Words Namespace


Shading.ClearFormatting Method

Removes shading from the object.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

See Also

Shading Class | Aspose.Words Namespace


Shading.Equals Method

Determines whether the specified object is equal in value to the current object.

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

See Also

Shading Class | Aspose.Words Namespace


Shading.GetHashCode Method

Serves as a hash function for this type.

[Visual Basic]
Overrides Public Function GetHashCode() As Integer
[C#]
public override int GetHashCode();

See Also

Shading Class | Aspose.Words Namespace


SignatureLineOptions Class

Allows to specify options for signature line being inserted. Used in DocumentBuilder.

For a list of all members of this type, see SignatureLineOptions Members.

System.Object
Aspose.Words.SignatureLineOptions

[Visual Basic]
Public Class SignatureLineOptions
[C#]
public class SignatureLineOptions

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SignatureLineOptions Members | Aspose.Words Namespace


SignatureLineOptions Members

SignatureLineOptions overview

Public Instance Constructors

SignatureLineOptions Constructor Initializes a new instance of the SignatureLineOptions class.

Public Instance Properties

AllowComments | Gets or sets a value indicating that the signer can add comments in the Sign dialog. Default value for this property is false.
DefaultInstructions | Gets or sets a value indicating that default instructions is shown in the Sign dialog. Default value for this property is true.
Email | Gets or sets suggested signer's e-mail address. Default value for this property is empty string (Empty).
Instructions | Gets or sets instructions to the signer that are displayed on signing the signature line. Default value for this property is empty string (Empty).
ShowDate | Gets or sets a value indicating that sign date is shown in the signature line. Default value for this property is true.
Signer | Gets or sets suggested signer of the signature line. Default value for this property is empty string (Empty).
SignerTitle | Gets or sets suggested signer's title. Default value for this property is empty string (Empty).

See Also

SignatureLineOptions Class | Aspose.Words Namespace


SignatureLineOptions Constructor

Initializes a new instance of the SignatureLineOptions class.

[Visual Basic]
Public Sub New()
[C#]
public SignatureLineOptions();

See Also

SignatureLineOptions Class | Aspose.Words Namespace


SignatureLineOptions Properties

The properties of the SignatureLineOptions class are listed below. For a complete list of SignatureLineOptions class members, see the SignatureLineOptions Members topic.

Public Instance Properties

AllowComments | Gets or sets a value indicating that the signer can add comments in the Sign dialog. Default value for this property is false.
DefaultInstructions | Gets or sets a value indicating that default instructions is shown in the Sign dialog. Default value for this property is true.
Email | Gets or sets suggested signer's e-mail address. Default value for this property is empty string (Empty).
Instructions | Gets or sets instructions to the signer that are displayed on signing the signature line. Default value for this property is empty string (Empty).
ShowDate | Gets or sets a value indicating that sign date is shown in the signature line. Default value for this property is true.
Signer | Gets or sets suggested signer of the signature line. Default value for this property is empty string (Empty).
SignerTitle | Gets or sets suggested signer's title. Default value for this property is empty string (Empty).

See Also

SignatureLineOptions Class | Aspose.Words Namespace


AllowComments Property

Aspose.Words

SignatureLineOptions.AllowComments Property

Gets or sets a value indicating that the signer can add comments in the Sign dialog. Default value for this property is false.

[Visual Basic]
Public Property AllowComments As Boolean
[C#]
public bool AllowComments {get; set;}

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignatureLineOptions Class | Aspose.Words Namespace


DefaultInstructions Property

Aspose.Words

SignatureLineOptions.DefaultInstructions Property

Gets or sets a value indicating that default instructions is shown in the Sign dialog. Default value for this property is true.

[Visual Basic]
Public Property DefaultInstructions As Boolean
[C#]
public bool DefaultInstructions {get; set;}

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignatureLineOptions Class | Aspose.Words Namespace


Email Property

Aspose.Words

SignatureLineOptions.Email Property

Gets or sets suggested signer's e-mail address. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property Email As String
[C#]
public string Email {get; set;}

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignatureLineOptions Class | Aspose.Words Namespace


Instructions Property

Aspose.Words

SignatureLineOptions.Instructions Property

Gets or sets instructions to the signer that are displayed on signing the signature line. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property Instructions As String
[C#]
public string Instructions {get; set;}

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignatureLineOptions Class | Aspose.Words Namespace


ShowDate Property

Aspose.Words

SignatureLineOptions.ShowDate Property

Gets or sets a value indicating that sign date is shown in the signature line. Default value for this property is true.

[Visual Basic]
Public Property ShowDate As Boolean
[C#]
public bool ShowDate {get; set;}

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignatureLineOptions Class | Aspose.Words Namespace


Signer Property

Aspose.Words

SignatureLineOptions.Signer Property

Gets or sets suggested signer of the signature line. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property Signer As String
[C#]
public string Signer {get; set;}

Example

Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.

[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

See Also

SignatureLineOptions Class | Aspose.Words Namespace


SignerTitle Property

Aspose.Words

SignatureLineOptions.SignerTitle Property

Gets or sets suggested signer's title. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property SignerTitle As String
[C#]
public string SignerTitle {get; set;}

Example

Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.

[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

See Also

SignatureLineOptions Class | Aspose.Words Namespace


SignOptions Class

Allows to specify options for document signing.

For a list of all members of this type, see SignOptions Members.

System.Object
Aspose.Words.SignOptions

[Visual Basic]
Public Class SignOptions
[C#]
public class SignOptions

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SignOptions Members | Aspose.Words Namespace


SignOptions Members

SignOptions overview

Public Instance Constructors

SignOptions Constructor Initializes a new instance of the SignOptions class.

Public Instance Properties

Comments | Specifies comments on the digital signature. Default value is empty string (Empty).
DecryptionPassword | The password to decrypt source document. Default value is empty string (Empty).
ProviderId | Specifies the class ID of the signature provider. Default value is Empty (all zeroes) Guid.
SignatureLineId | Signature line identifier. Default value is Empty (all zeroes) Guid.
SignatureLineImage | The image that will be shown in associated SignatureLine. Default value is null.
SignTime | The date of signing. Default value is current time (Now).

See Also

SignOptions Class | Aspose.Words Namespace


SignOptions Constructor

Initializes a new instance of the SignOptions class.

[Visual Basic]
Public Sub New()
[C#]
public SignOptions();

See Also

SignOptions Class | Aspose.Words Namespace


SignOptions Properties

The properties of the SignOptions class are listed below. For a complete list of SignOptions class members, see the SignOptions Members topic.

Public Instance Properties

Comments | Specifies comments on the digital signature. Default value is empty string (Empty).
DecryptionPassword | The password to decrypt source document. Default value is empty string (Empty).
ProviderId | Specifies the class ID of the signature provider. Default value is Empty (all zeroes) Guid.
SignatureLineId | Signature line identifier. Default value is Empty (all zeroes) Guid.
SignatureLineImage | The image that will be shown in associated SignatureLine. Default value is null.
SignTime | The date of signing. Default value is current time (Now).

See Also

SignOptions Class | Aspose.Words Namespace


Comments Property

Aspose.Words

SignOptions.Comments Property

Specifies comments on the digital signature. Default value is empty string (Empty).

[Visual Basic]
Public Property Comments As String
[C#]
public string Comments {get; set;}

Example

Shows how to sign documents using certificate holder and sign options.

[C#]

CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions { Comments = "My comment", SignTime = DateTime.Now };

using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.DigitalSignature.docx", FileMode.OpenOrCreate))
    {
        DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
    }
}

See Also

SignOptions Class | Aspose.Words Namespace


DecryptionPassword Property

Aspose.Words

SignOptions.DecryptionPassword Property

The password to decrypt source document. Default value is empty string (Empty).

[Visual Basic]
Public Property DecryptionPassword As String
[C#]
public string DecryptionPassword {get; set;}

Remarks

If OOXML document is encrypted, you should provide decryption password to decrypt source document before it will be signed. This is not required for documents in binary DOC format.

Example

Shows how to sign encrypted document file.

[C#]

string outputFileName = ArtifactsDir + "Document.Encrypted.docx";

Document doc = new Document(MyDir + "Document.Encrypted.docx", new LoadOptions("docPassword"));

// Create certificate holder from a file.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions
{
    Comments = "Comment",
    SignTime = DateTime.Now,
    DecryptionPassword = "docPassword"
};

// Digitally sign encrypted with "docPassword" document in the specified path.
DigitalSignatureUtil.Sign(doc.OriginalFileName, outputFileName, certificateHolder, signOptions);

See Also

SignOptions Class | Aspose.Words Namespace


ProviderId Property

Aspose.Words

SignOptions.ProviderId Property

Specifies the class ID of the signature provider. Default value is Empty (all zeroes) Guid.

[Visual Basic]
Public Property ProviderId As Guid
[C#]
public Guid ProviderId {get; set;}

Remarks

The cryptographic service provider (CSP) is an independent software module that actually performs cryptography algorithms for authentication, encoding, and encryption. MS Office reserves the value of {00000000-0000-0000-0000-000000000000} for its default signature provider.

The GUID of the additionally installed provider should be obtained from the documentation shipped with the provider.

In addition, all the installed cryptographic providers are enumerated in windows registry. It can be found in the following path: HKLM\SOFTWARE\Microsoft\Cryptography\Defaults\Provider. There is a key name "CP Service UUID" which corresponds to a GUID of signature provider.

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignOptions Class | Aspose.Words Namespace


SignatureLineId Property

Aspose.Words

SignOptions.SignatureLineId Property

Signature line identifier. Default value is Empty (all zeroes) Guid.

[Visual Basic]
Public Property SignatureLineId As Guid
[C#]
public Guid SignatureLineId {get; set;}

Remarks

When set, it associates SignatureLine with corresponding DigitalSignature.

Example

Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.

[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

See Also

SignOptions Class | Aspose.Words Namespace


SignatureLineImage Property

Aspose.Words

SignOptions.SignatureLineImage Property

The image that will be shown in associated SignatureLine. Default value is null.

[Visual Basic]
Public Property SignatureLineImage As Byte()
[C#]
public byte[] SignatureLineImage {get; set;}

Example

Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.

[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

See Also

SignOptions Class | Aspose.Words Namespace


SignTime Property

Aspose.Words

SignOptions.SignTime Property

The date of signing. Default value is current time (Now).

[Visual Basic]
Public Property SignTime As Date
[C#]
public DateTime SignTime {get; set;}

Example

Shows how to sign documents using certificate holder and sign options.

[C#]

CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

SignOptions signOptions = new SignOptions { Comments = "My comment", SignTime = DateTime.Now };

using (Stream streamIn = new FileStream(MyDir + "Document.DigitalSignature.docx", FileMode.Open))
{
    using (Stream streamOut = new FileStream(ArtifactsDir + "Document.DigitalSignature.docx", FileMode.OpenOrCreate))
    {
        DigitalSignatureUtil.Sign(streamIn, streamOut, certificateHolder, signOptions);
    }
}

See Also

SignOptions Class | Aspose.Words Namespace


SpecialChar Class

Base class for special characters in the document.

For a list of all members of this type, see SpecialChar Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.AbsolutePositionTab
Aspose.Words.Fields.FieldChar
Aspose.Words.Fields.FormField

[Visual Basic]
Public Class SpecialChar
Inherits Inline
[C#]
public class SpecialChar : Inline

Remarks

A Microsoft Word document can include a number of special characters that represent fields, form fields, shapes, OLE objects, footnotes etc. For the list of special characters see ControlChar.

SpecialChar is an inline-node and can only be a child of Paragraph.

SpecialChar char is used as a base class for more specific classes that represent special characters that Aspose.Words provides programmatic access for. The SpecialChar class is also used itself to represent special character for which Aspose.Words does not provide detailed programmatic access.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SpecialChar Members | Aspose.Words Namespace


SpecialChar Members

SpecialChar overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.SpecialChar.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

SpecialChar Class | Aspose.Words Namespace


SpecialChar Properties

The properties of the SpecialChar class are listed below. For a complete list of SpecialChar class members, see the SpecialChar Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.SpecialChar.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

SpecialChar Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

SpecialChar.NodeType Property

Returns NodeType.SpecialChar.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

SpecialChar Class | Aspose.Words Namespace


SpecialChar Methods

The methods of the SpecialChar class are listed below. For a complete list of SpecialChar class members, see the SpecialChar Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

SpecialChar Class | Aspose.Words Namespace


SpecialChar.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls DocumentVisitor.VisitSpecialChar.

For more info see the Visitor design pattern.

See Also

SpecialChar Class | Aspose.Words Namespace


SpecialChar.GetText Method

Gets the special character that this node represents.

[Visual Basic]
Overrides Public Function GetText() As String
[C#]
public override string GetText();

Return Value

The string that contains the character that this node represents.

See Also

SpecialChar Class | Aspose.Words Namespace


Story Class

Base class for elements that contain block-level nodes Paragraph and Table.

For a list of all members of this type, see Story Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Story
Aspose.Words.Body
Aspose.Words.HeaderFooter

[Visual Basic]
MustInherit Public Class Story
Inherits CompositeNode
[C#]
public abstract class Story : CompositeNode

Remarks

Text of a Word document is said to consist of several stories. The main text is stored in the main text story represented by Body, each header and footer is stored in a separate story represented by HeaderFooter.

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Story Members | Aspose.Words Namespace


Story Members

Story overview

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph in the story.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
Paragraphs | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType | Gets the type of this story.
Tables | Gets a collection of tables that are immediate children of the story.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendParagraph | A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.
Clone (inherited from Node) |
DeleteShapes | Deletes all shapes from the text of this story.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Story Class | Aspose.Words Namespace


Story Properties

The properties of the Story class are listed below. For a complete list of Story class members, see the Story Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph in the story.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph in the story.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
Paragraphs | Gets a collection of paragraphs that are immediate children of the story.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
StoryType | Gets the type of this story.
Tables | Gets a collection of tables that are immediate children of the story.

See Also

Story Class | Aspose.Words Namespace


FirstParagraph Property

Aspose.Words

Story.FirstParagraph Property

Gets the first paragraph in the story.

[Visual Basic]
Public ReadOnly Property FirstParagraph As Paragraph
[C#]
public Paragraph FirstParagraph {get;}

Example

Shows how to add a formatted run of text to a document using the object model.

[C#]

// Create an empty document. It contains one empty paragraph.
Document doc = new Document();

// Create a new run of text.
Run run = new Run(doc, "Hello");

// Specify character formatting for the run of text.
Aspose.Words.Font f = run.Font;
f.Name = "Courier New";
f.Size = 36;
f.HighlightColor = Color.Yellow;

// Append the run of text to the end of the first paragraph
// in the body of the first section of the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(run);
Creates a textbox with some text and different formatting options in a new document.
[C#]

// Create a blank document.
Document doc = new Document();

// Create a new shape of type TextBox
Shape textBox = new Shape(doc, ShapeType.TextBox);

// Set some settings of the textbox itself.
// Set the wrap of the textbox to inline
textBox.WrapType = WrapType.None;
// Set the horizontal and vertical alignment of the text inside the shape.
textBox.HorizontalAlignment = HorizontalAlignment.Center;
textBox.VerticalAlignment = VerticalAlignment.Top;

// Set the textbox height and width.
textBox.Height = 50;
textBox.Width = 200;

// Set the textbox in front of other shapes with a lower ZOrder
textBox.ZOrder = 2;

// Let's create a new paragraph for the textbox manually and align it in the center. Make sure we add the new nodes to the textbox as well.
textBox.AppendChild(new Paragraph(doc));
Paragraph para = textBox.FirstParagraph;
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Add some text to the paragraph.
Run run = new Run(doc);
run.Text = "Content in textbox";
para.AppendChild(run);

// Append the textbox to the first paragraph in the body.
doc.FirstSection.Body.FirstParagraph.AppendChild(textBox);

// Save the output
doc.Save(ArtifactsDir + "Shape.CreateTextBox.doc");

See Also

Story Class | Aspose.Words Namespace


LastParagraph Property

Aspose.Words

Story.LastParagraph Property

Gets the last paragraph in the story.

[Visual Basic]
Public ReadOnly Property LastParagraph As Paragraph
[C#]
public Paragraph LastParagraph {get;}

Example

Shows how to move a cursor position to a specified node.

[C#]

Document doc = new Document(MyDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveTo(doc.FirstSection.Body.LastParagraph);

See Also

Story Class | Aspose.Words Namespace


Paragraphs Property

Aspose.Words

Story.Paragraphs Property

Gets a collection of paragraphs that are immediate children of the story.

[Visual Basic]
Public ReadOnly Property Paragraphs As ParagraphCollection
[C#]
public ParagraphCollection Paragraphs {get;}

See Also

Story Class | Aspose.Words Namespace


StoryType Property

Aspose.Words

Story.StoryType Property

Gets the type of this story.

[Visual Basic]
Public ReadOnly Property StoryType As StoryType
[C#]
public StoryType StoryType {get;}

See Also

Story Class | Aspose.Words Namespace


Tables Property

Aspose.Words

Story.Tables Property

Gets a collection of tables that are immediate children of the story.

[Visual Basic]
Public ReadOnly Property Tables As TableCollection
[C#]
public TableCollection Tables {get;}

Example

Demonstrates how to use typed properties to access nodes of the document tree.

[C#]

// Quick typed access to the first child Section node of the Document.
Section section = doc.FirstSection;

// Quick typed access to the Body child node of the Section.
Body body = section.Body;

// Quick typed access to all Table child nodes contained in the Body.
TableCollection tables = body.Tables;

foreach (Table table in tables.OfType<Table>())
{
    // Quick typed access to the first row of the table.
    table.FirstRow?.Remove();

    // Quick typed access to the last row of the table.
    table.LastRow?.Remove();
}

See Also

Story Class | Aspose.Words Namespace


Story Methods

The methods of the Story class are listed below. For a complete list of Story class members, see the Story Members topic.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AppendParagraph | A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.
Clone (inherited from Node) |
DeleteShapes | Deletes all shapes from the text of this story.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Story Class | Aspose.Words Namespace


Story.AppendParagraph Method

A shortcut method that creates a Paragraph object with optional text and appends it to the end of this object.

[Visual Basic]
Public Function AppendParagraph( _
ByVal text As String _
) As Paragraph
[C#]
public Paragraph AppendParagraph(
string text
);

Parameters

text
The text for the paragraph. Can be null or empty string.

Return Value

The newly created and appended paragraph.

Example

Creates a header and footer using the document object model and insert them into a section.

[C#]

Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
doc.FirstSection.HeadersFooters.Add(header);

// Add a paragraph with text to the footer.
header.AppendParagraph("My header");

Assert.True(header.IsHeader);

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

Assert.False(footer.IsHeader);

// Add a paragraph with text to the footer.
footer.AppendParagraph("My footer");

Assert.AreEqual(header.ParentSection, footer.ParentSection);

doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterCreate.docx");

See Also

Story Class | Aspose.Words Namespace


Story.DeleteShapes Method

Deletes all shapes from the text of this story.

[Visual Basic]
Public Sub DeleteShapes()
[C#]
public void DeleteShapes();

See Also

Story Class | Aspose.Words Namespace


StoryType Enumeration

Text of a Word document is stored in stories. StoryType identifies a story.

[Visual Basic]
Public Enum StoryType
[C#]
public enum StoryType

Members

Member Name | Description | Value
None | Default value. There is no such story in the document. | 0
MainText | Contains the main text of the document, represented by Body. | 1
Footnotes | Contains footnote text, represented by Footnote. | 2
Endnotes | Contains endnotes text, represented by Footnote. | 3
Comments | Contains document comments (annotations), represented by Comment. | 4
Textbox | Contains shape or textbox text, represented by Shape. | 5
EvenPagesHeader | Contains text of the even pages header, represented by HeaderFooter. | 6
PrimaryHeader | Contains text of the primary header. When header is different for odd and even pages, contains text of the odd pages header. Represented by HeaderFooter. | 7
EvenPagesFooter | Contains text of the even pages footer, represented by HeaderFooter. | 8
PrimaryFooter | Contains text of the primary footer. When footer is different for odd and even pages, contains text of the odd pages footer. Represented by HeaderFooter. | 9
FirstPageHeader | Contains text of the first page header, represented by HeaderFooter. | 10
FirstPageFooter | Contains text of the first page footer, represented by HeaderFooter. | 11
FootnoteSeparator | Contains the text of the footnote separator, represented by FootnoteSeparator. | 12
FootnoteContinuationSeparator | Contains the text of the footnote continuation separator, represented by FootnoteSeparator. | 13
FootnoteContinuationNotice | Contains the text of the footnote continuation notice separator, represented by FootnoteSeparator. | 14
EndnoteSeparator | Contains the text of the endnote separator, represented by FootnoteSeparator. | 15
EndnoteContinuationSeparator | Contains the text of the endnote continuation separator, represented by FootnoteSeparator. | 16
EndnoteContinuationNotice | Contains the text of the endnote continuation notice separator, represented by FootnoteSeparator. | 17

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Style Class

Represents a single built-in or user-defined style.

For a list of all members of this type, see Style Members.

System.Object
Aspose.Words.Style
Aspose.Words.TableStyle

[Visual Basic]
Public Class Style
[C#]
public class Style

Example

Shows how to change the font formatting of all styles in a document.

[C#]

Document doc = new Document();
foreach (Style style in doc.Styles)
{
    if (style.Font != null)
    {
        style.Font.ClearFormatting();
        style.Font.Size = 20;
        style.Font.Name = "Arial";
    }
}
Shows how to create and use a paragraph style with list formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Style Members | Aspose.Words Namespace


Style Members

Style overview

Public Instance Properties

Aliases | Gets all aliases of this style. If style has no aliases then empty array of string is returned.
BaseStyleName | Gets/sets the name of the style this style is based on.
BuiltIn | True if this style is one of the built-in styles in MS Word.
Document | Gets the owner document.
Font | Gets the character formatting of the style.
IsHeading | True when the style is one of the built-in Heading styles.
IsQuickStyle | Specifies whether this style is shown in the Quick Style gallery inside MS Word UI.
LinkedStyleName | Gets the name of the Style linked to this one. Returns Empty string if no styles are linked.
List | Gets the list that defines formatting of this list style.
ListFormat | Provides access to the list formatting properties of a paragraph style.
Name | Gets or sets the name of the style.
NextParagraphStyleName | Gets/sets the name of the style to be applied automatically to a new paragraph inserted after a paragraph formatted with the specified style.
ParagraphFormat | Gets the paragraph formatting of the style.
StyleIdentifier | Gets the locale independent style identifier for a built-in style.
Styles | Gets the collection of styles this style belongs to.
Type | Gets the style type (paragraph or character).

Public Instance Methods

Remove Removes the specified style from the document.

See Also

Style Class | Aspose.Words Namespace


Style Properties

The properties of the Style class are listed below. For a complete list of Style class members, see the Style Members topic.

Public Instance Properties

Aliases | Gets all aliases of this style. If style has no aliases then empty array of string is returned.
BaseStyleName | Gets/sets the name of the style this style is based on.
BuiltIn | True if this style is one of the built-in styles in MS Word.
Document | Gets the owner document.
Font | Gets the character formatting of the style.
IsHeading | True when the style is one of the built-in Heading styles.
IsQuickStyle | Specifies whether this style is shown in the Quick Style gallery inside MS Word UI.
LinkedStyleName | Gets the name of the Style linked to this one. Returns Empty string if no styles are linked.
List | Gets the list that defines formatting of this list style.
ListFormat | Provides access to the list formatting properties of a paragraph style.
Name | Gets or sets the name of the style.
NextParagraphStyleName | Gets/sets the name of the style to be applied automatically to a new paragraph inserted after a paragraph formatted with the specified style.
ParagraphFormat | Gets the paragraph formatting of the style.
StyleIdentifier | Gets the locale independent style identifier for a built-in style.
Styles | Gets the collection of styles this style belongs to.
Type | Gets the style type (paragraph or character).

See Also

Style Class | Aspose.Words Namespace


Aliases Property

Aspose.Words

Style.Aliases Property

Gets all aliases of this style. If style has no aliases then empty array of string is returned.

[Visual Basic]
Public ReadOnly Property Aliases As String()
[C#]
public string[] Aliases {get;}

See Also

Style Class | Aspose.Words Namespace


BaseStyleName Property

Aspose.Words

Style.BaseStyleName Property

Gets/sets the name of the style this style is based on.

[Visual Basic]
Public Property BaseStyleName As String
[C#]
public string BaseStyleName {get; set;}

Remarks

This will be an empty string if the style is not based on any other style and it can be set to an empty string.

See Also

Style Class | Aspose.Words Namespace


BuiltIn Property

Aspose.Words

Style.BuiltIn Property

True if this style is one of the built-in styles in MS Word.

[Visual Basic]
Public ReadOnly Property BuiltIn As Boolean
[C#]
public bool BuiltIn {get;}

Example

Applies double underline to all runs in a document that are formatted with custom character styles.

[C#]

Document doc = new Document(MyDir + "Font.Style.doc");

// Select all run nodes in the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

// Loop through every run node.
foreach (Run run in runs.OfType<Run>())
{
    Style charStyle = run.Font.Style;

    // If the style of the run is not a built-in character style, apply double underline.
    if (!charStyle.BuiltIn)
        run.Font.Underline = Underline.Double;
}

doc.Save(ArtifactsDir + "Font.Style.doc");

See Also

Style Class | Aspose.Words Namespace


Document Property

Aspose.Words

Style.Document Property

Gets the owner document.

[Visual Basic]
Public ReadOnly Property Document As DocumentBase
[C#]
public DocumentBase Document {get;}

See Also

Style Class | Aspose.Words Namespace


Font Property

Aspose.Words

Style.Font Property

Gets the character formatting of the style.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Remarks

For list styles this property returns null.

Example

Shows how to change the font formatting of all styles in a document.

[C#]

Document doc = new Document();
foreach (Style style in doc.Styles)
{
    if (style.Font != null)
    {
        style.Font.ClearFormatting();
        style.Font.Size = 20;
        style.Font.Name = "Arial";
    }
}
Shows how to create and use a paragraph style with list formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

See Also

Style Class | Aspose.Words Namespace


IsHeading Property

Aspose.Words

Style.IsHeading Property

True when the style is one of the built-in Heading styles.

[Visual Basic]
Public ReadOnly Property IsHeading As Boolean
[C#]
public bool IsHeading {get;}

See Also

Style Class | Aspose.Words Namespace


IsQuickStyle Property

Aspose.Words

Style.IsQuickStyle Property

Specifies whether this style is shown in the Quick Style gallery inside MS Word UI.

[Visual Basic]
Public Property IsQuickStyle As Boolean
[C#]
public bool IsQuickStyle {get; set;}

See Also

Style Class | Aspose.Words Namespace


LinkedStyleName Property

Aspose.Words

Style.LinkedStyleName Property

Gets the name of the Style linked to this one. Returns Empty string if no styles are linked.

[Visual Basic]
Public ReadOnly Property LinkedStyleName As String
[C#]
public string LinkedStyleName {get;}

See Also

Style Class | Aspose.Words Namespace


List Property

Aspose.Words

Style.List Property

Gets the list that defines formatting of this list style.

[Visual Basic]
Public ReadOnly Property List As List
[C#]
public List List {get;}

Remarks

This property is only valid for list styles. For other style types this property returns null.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

Style Class | Aspose.Words Namespace


ListFormat Property

Aspose.Words

Style.ListFormat Property

Provides access to the list formatting properties of a paragraph style.

[Visual Basic]
Public ReadOnly Property ListFormat As ListFormat
[C#]
public ListFormat ListFormat {get;}

Remarks

This property is only valid for paragraph styles. For other style types this property returns null.

Example

Shows how to create and use a paragraph style with list formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

See Also

Style Class | Aspose.Words Namespace


Name Property

Aspose.Words

Style.Name Property

Gets or sets the name of the style.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

Can not be empty string.

If there already is a style with such name in the collection, then this style will override it. All affected nodes will reference new style.

Example

Shows how to get access to the collection of styles defined in the document.

[C#]

Document doc = new Document();
StyleCollection styles = doc.Styles;

foreach (Style style in styles)
    Console.WriteLine(style.Name);
Demonstrates how to copy a style within the same document.
[C#]

// The AddCopy method creates a copy of the specified style and automatically generates a new name for the style, such as "Heading 1_0".
Style newStyle = doc.Styles.AddCopy(doc.Styles["Heading 1"]);

// You can change the new style name if required as the Style.Name property is read-write.
newStyle.Name = "My Heading 1";

See Also

Style Class | Aspose.Words Namespace


NextParagraphStyleName Property

Aspose.Words

Style.NextParagraphStyleName Property

Gets/sets the name of the style to be applied automatically to a new paragraph inserted after a paragraph formatted with the specified style.

[Visual Basic]
Public Property NextParagraphStyleName As String
[C#]
public string NextParagraphStyleName {get; set;}

Remarks

This property is not used by Aspose.Words. The next paragraph style will only be applied automatically when you edit the document in MS Word.

See Also

Style Class | Aspose.Words Namespace


ParagraphFormat Property

Aspose.Words

Style.ParagraphFormat Property

Gets the paragraph formatting of the style.

[Visual Basic]
Public ReadOnly Property ParagraphFormat As ParagraphFormat
[C#]
public ParagraphFormat ParagraphFormat {get;}

Remarks

For character and list styles this property returns null.

Example

Shows how to create and use a paragraph style with list formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

See Also

Style Class | Aspose.Words Namespace


StyleIdentifier Property

Aspose.Words

Style.StyleIdentifier Property

Gets the locale independent style identifier for a built-in style.

[Visual Basic]
Public ReadOnly Property StyleIdentifier As StyleIdentifier
[C#]
public StyleIdentifier StyleIdentifier {get;}

Remarks

For user defined (custom) styles, this property returns User.

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

See Also

Style Class | Aspose.Words Namespace | Name


Styles Property

Aspose.Words

Style.Styles Property

Gets the collection of styles this style belongs to.

[Visual Basic]
Public ReadOnly Property Styles As StyleCollection
[C#]
public StyleCollection Styles {get;}

See Also

Style Class | Aspose.Words Namespace


Type Property

Aspose.Words

Style.Type Property

Gets the style type (paragraph or character).

[Visual Basic]
Public ReadOnly Property Type As StyleType
[C#]
public StyleType Type {get;}

See Also

Style Class | Aspose.Words Namespace


Style Methods

The methods of the Style class are listed below. For a complete list of Style class members, see the Style Members topic.

Public Instance Methods

Remove Removes the specified style from the document.

See Also

Style Class | Aspose.Words Namespace


Style.Remove Method

Removes the specified style from the document.

[Visual Basic]
Public Sub Remove()
[C#]
public void Remove();

Remarks

Style removal has following effects on the document model:

  • All references to the style are removed from corresponding paragraphs, runs and tables.
  • If base style is removed its formatting is moved to child styles.
  • If style to be deleted has a linked style, then both of these are deleted.

Example

Shows how to pick a style that is defined in the document and remove it.

[C#]

Document doc = new Document();
doc.Styles["Normal"].Remove();

See Also

Style Class | Aspose.Words Namespace


StyleCollection Class

A collection of Style objects that represent both the built-in and user-defined styles in a document.

For a list of all members of this type, see StyleCollection Members.

System.Object
Aspose.Words.StyleCollection

[Visual Basic]
Public Class StyleCollection
Implements IEnumerable`1([Aspose.Words.Style, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class StyleCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to create and use a paragraph style with list formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a paragraph style and specify some formatting for it.
Style style = doc.Styles.Add(StyleType.Paragraph, "MyStyle1");
style.Font.Size = 24;
style.Font.Name = "Verdana";
style.ParagraphFormat.SpaceAfter = 12;

// Create a list and make sure the paragraphs that use this style will use this list.
style.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDefault);
style.ListFormat.ListLevelNumber = 0;

// Apply the paragraph style to the current paragraph in the document and add some text.
builder.ParagraphFormat.Style = style;
builder.Writeln("Hello World: MyStyle1, bulleted.");

// Change to a paragraph style that has no list formatting.
builder.ParagraphFormat.Style = doc.Styles["Normal"];
builder.Writeln("Hello World: Normal.");

builder.Document.Save(ArtifactsDir + "Lists.ParagraphStyleBulleted.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

StyleCollection Members | Aspose.Words Namespace


StyleCollection Members

StyleCollection overview

Public Instance Properties

Count | Gets the number of styles in the collection.
DefaultFont | Gets document default text formatting.
DefaultParagraphFormat | Gets document default paragraph formatting.
Document | Gets the owner document.
Item | Overloaded. Retrieves a style from the collection.

Public Instance Methods

Add | Creates a new user defined style and adds it the collection.
AddCopy | Copies a style into this collection.
GetEnumerator | Gets an enumerator object that will enumerate styles in the alphabetical order of their names.

See Also

StyleCollection Class | Aspose.Words Namespace


StyleCollection Properties

The properties of the StyleCollection class are listed below. For a complete list of StyleCollection class members, see the StyleCollection Members topic.

Public Instance Properties

Count | Gets the number of styles in the collection.
DefaultFont | Gets document default text formatting.
DefaultParagraphFormat | Gets document default paragraph formatting.
Document | Gets the owner document.
Item | Overloaded. Retrieves a style from the collection.

See Also

StyleCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

StyleCollection.Count Property

Gets the number of styles in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

StyleCollection Class | Aspose.Words Namespace


DefaultFont Property

Aspose.Words

StyleCollection.DefaultFont Property

Gets document default text formatting.

[Visual Basic]
Public ReadOnly Property DefaultFont As Font
[C#]
public Font DefaultFont {get;}

Remarks

Note that document-wide defaults were introduced in Microsoft Word 2007 and are fully supported in OOXML formats (Docx) only. Earlier document formats have limited support for this feature and only font names can be stored.

See Also

StyleCollection Class | Aspose.Words Namespace


DefaultParagraphFormat Property

Aspose.Words

StyleCollection.DefaultParagraphFormat Property

Gets document default paragraph formatting.

[Visual Basic]
Public ReadOnly Property DefaultParagraphFormat As ParagraphFormat
[C#]
public ParagraphFormat DefaultParagraphFormat {get;}

Remarks

Note that document-wide defaults were introduced in Microsoft Word 2007 and are fully supported in OOXML formats (Docx) only. Earlier document formats have no support for document default paragraph formatting.

See Also

StyleCollection Class | Aspose.Words Namespace


Document Property

Aspose.Words

StyleCollection.Document Property

Gets the owner document.

[Visual Basic]
Public ReadOnly Property Document As DocumentBase
[C#]
public DocumentBase Document {get;}

See Also

StyleCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

StyleCollection.Item Property

Retrieves a style from the collection.

Overload List

Gets a built-in style by its locale independent identifier.

public Style this[Aspose.Words.StyleIdentifier] {get;}

Gets a style by index.

public Style this[int] {get;}

Gets a style by name or alias.

public Style this[string] {get;}

See Also

StyleCollection Class | Aspose.Words Namespace


Item Property (StyleIdentifier)

Aspose.Words

StyleCollection.Item Property (StyleIdentifier)

Gets a built-in style by its locale independent identifier.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal sti As StyleIdentifier _
) As Style
[C#]
public Style this[
Aspose.Words.StyleIdentifier sti
] {get;}

Parameters

sti
A StyleIdentifier value that specifies the built in style to retrieve.

Remarks

When accessing a style that does not yet exist, automatically creates it.

See Also

StyleCollection Class | Aspose.Words Namespace | StyleCollection.Item Overload List


Item Property (Int32)

Aspose.Words

StyleCollection.Item Property (Int32)

Gets a style by index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Style
[C#]
public Style this[
int index
] {get;}

See Also

StyleCollection Class | Aspose.Words Namespace | StyleCollection.Item Overload List


Item Property (String)

Aspose.Words

StyleCollection.Item Property (String)

Gets a style by name or alias.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal name As String _
) As Style
[C#]
public Style this[
string name
] {get;}

Remarks

Case sensitive, returns null if the style with the given name is not found.

If this is an English name of a built in style that does not yet exist, automatically creates it.

Example

Shows when to request page layout of the document to be recalculated.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Saving a document to PDF or to image or printing for the first time will automatically
// layout document pages and this information will be cached inside the document.
doc.Save(ArtifactsDir + "Rendering.UpdatePageLayout1.pdf");

// Modify the document in any way.
doc.Styles["Normal"].Font.Size = 6;
doc.Sections[0].PageSetup.Orientation = Aspose.Words.Orientation.Landscape;

// In the current version of Aspose.Words, modifying the document does not automatically rebuild
// the cached page layout. If you want to save to PDF or render a modified document again,
// you need to manually request page layout to be updated.
doc.UpdatePageLayout();

doc.Save(ArtifactsDir + "Rendering.UpdatePageLayout2.pdf");

See Also

StyleCollection Class | Aspose.Words Namespace | StyleCollection.Item Overload List


StyleCollection Methods

The methods of the StyleCollection class are listed below. For a complete list of StyleCollection class members, see the StyleCollection Members topic.

Public Instance Methods

Add | Creates a new user defined style and adds it the collection.
AddCopy | Copies a style into this collection.
GetEnumerator | Gets an enumerator object that will enumerate styles in the alphabetical order of their names.

See Also

StyleCollection Class | Aspose.Words Namespace


StyleCollection.Add Method

Creates a new user defined style and adds it the collection.

[Visual Basic]
Public Function Add( _
ByVal type As StyleType, _
ByVal name As String _
) As Style
[C#]
public Style Add(
StyleType type,
string name
);

Parameters

type
A StyleType value that specifies the type of the style to create.
name
Case sensitive name of the style to create.

Remarks

You can create character, paragraph or a list style.

When creating a list style, the style is created with default numbered list formatting (1 \ a \ i).

Throws an exception if a style with this name already exists.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

StyleCollection Class | Aspose.Words Namespace


StyleCollection.AddCopy Method

Copies a style into this collection.

[Visual Basic]
Public Function AddCopy( _
ByVal style As Style _
) As Style
[C#]
public Style AddCopy(
Style style
);

Parameters

style
Style to be copied.

Return Value

Copied style ready for usage.

Remarks

Style to be copied can belong to the same document as well as to different document.

Linked style is copied.

This method does doesn't copy base styles.

If collection already contains a style with the same name, then new name is automatically generated by adding "_number" suffix starting from 0 e.g. "Normal_0", "Heading 1_1" etc. Use Name setter for changing the name of the imported style.

Example

Demonstrates how to copy a style within the same document.

[C#]

// The AddCopy method creates a copy of the specified style and automatically generates a new name for the style, such as "Heading 1_0".
Style newStyle = doc.Styles.AddCopy(doc.Styles["Heading 1"]);

// You can change the new style name if required as the Style.Name property is read-write.
newStyle.Name = "My Heading 1";
Demonstrates how to copy style from one document into a different document.
[C#]

// This is the style in the source document to copy to the destination document.
Style srcStyle = srcDoc.Styles[StyleIdentifier.Heading1];

// Change the font of the heading style to red.
srcStyle.Font.Color = Color.Red;

// The AddCopy method can be used to copy a style from a different document.
Style newStyle = dstDoc.Styles.AddCopy(srcStyle);
Demonstrates how to copy a style from one document to another and override an existing style in the destination document.
[C#]

// This is the style in the source document to copy to the destination document.
Style srcStyle = srcDoc.Styles[StyleIdentifier.Heading1];

// Change the font of the heading style to red.
srcStyle.Font.Color = Color.Red;

// The AddCopy method can be used to copy a style to a different document.
Style newStyle = dstDoc.Styles.AddCopy(srcStyle);

// The name of the new style can be changed to the name of any existing style. Doing this will override the existing style.
newStyle.Name = "Heading 1";

See Also

StyleCollection Class | Aspose.Words Namespace


StyleCollection.GetEnumerator Method

Gets an enumerator object that will enumerate styles in the alphabetical order of their names.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Style) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Style> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

StyleCollection Class | Aspose.Words Namespace


StyleIdentifier Enumeration

Locale independent style identifier.

[Visual Basic]
Public Enum StyleIdentifier
[C#]
public enum StyleIdentifier

Remarks

The names of built-in styles in MS Word are localized for different languages. Using a style identifier you can find the correct style regardless of the document language.

All user defined styles are assigned the StyleIdentifier.User value.

Example

Shows how to use style identifier to find text formatted with a specific character style and apply different character style.

[C#]

Document doc = new Document(MyDir + "Font.StyleIdentifier.doc");

// Select all run nodes in the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

// Loop through every run node.
foreach (Run run in runs.OfType<Run>())
{
    // If the character style of the run is what we want, do what we need. Change the style in this case.
    // Note that using StyleIdentifier we can identify a built-in style regardless
    // of the language of Microsoft Word used to create the document.
    if (run.Font.StyleIdentifier.Equals(StyleIdentifier.Emphasis))
        run.Font.StyleIdentifier = StyleIdentifier.Strong;
}

doc.Save(ArtifactsDir + "Font.StyleIdentifier.doc");

Members

Member Name | Description | Value
BookTitle |  | 264
CommentReference | The Annotation (Comment) Reference style. | 39
DefaultParagraphFont | The Default Paragraph Font style. | 65
Emphasis |  | 88
EndnoteReference | The Endnote Reference style. | 42
FollowedHyperlink |  | 86
FootnoteReference | The Footnote Reference style. | 38
HtmlAcronym |  | 95
HtmlCite |  | 97
HtmlCode |  | 98
HtmlDefinition |  | 99
HtmlKeyboard |  | 100
HtmlSample |  | 102
HtmlTypewriter |  | 103
HtmlVariable |  | 104
Hyperlink | The Hyperlink style. | 85
IntenseEmphasis |  | 261
IntenseReference |  | 263
LineNumber | The Line Number style. | 40
PageNumber | The Page Number style. | 41
PlaceholderText |  | 156
Strong |  | 87
SubtleEmphasis |  | 260
SubtleReference |  | 262
BalloonText |  | 153
BodyText | The Body Text style. | 66
BodyText2 |  | 80
BodyText3 |  | 81
BodyText1I |  | 77
BodyText1I2 |  | 78
BodyTextInd |  | 67
BodyTextInd2 |  | 82
BodyTextInd3 |  | 83
Closing |  | 63
CommentSubject |  | 106
CommentText | The Annotation (Comment) Text style. | 30
Date |  | 76
DocumentMap |  | 89
EmailSignature |  | 91
EndnoteText | The Endnote Text style. | 43
Footer | The Footer style. | 32
FootnoteText | The Footnote Text style. | 29
Header | The Header style. | 31
Heading1 | The Heading 1 style. | 1
Heading2 | The Heading 2 style. | 2
Heading3 | The Heading 3 style. | 3
Heading4 | The Heading 4 style. | 4
Heading5 | The Heading 5 style. | 5
Heading6 | The Heading 6 style. | 6
Heading7 | The Heading 7 style. | 7
Heading8 | The Heading 8 style. | 8
Heading9 | The Heading 9 style. | 9
HtmlAddress |  | 96
HtmlTopOfForm |  | 92
HtmlBottomOfForm |  | 93
HtmlPreformatted |  | 101
IntenseQuote |  | 181
Macro |  | 45
MessageHeader |  | 73
NoteHeading |  | 79
PlainText |  | 90
Quote |  | 180
Salutation |  | 75
Signature |  | 64
Subtitle |  | 74
Title | The Title style. | 62
Bibliography |  | 265
BlockText |  | 84
Caption |  | 34
EnvelopeAddress | The Envelope Address style. | 36
EnvelopeReturn | The Envelope Return style. | 37
Index1 |  | 10
Index2 |  | 11
Index3 |  | 12
Index4 |  | 13
Index5 |  | 14
Index6 |  | 15
Index7 |  | 16
Index8 |  | 17
Index9 |  | 18
IndexHeading | The Index Heading style. | 33
List | The List style. | 47
List2 |  | 50
List3 |  | 51
List4 |  | 52
List5 |  | 53
ListBullet | The List Bullet style. | 48
ListBullet2 |  | 54
ListBullet3 |  | 55
ListBullet4 |  | 56
ListBullet5 |  | 57
ListContinue |  | 68
ListContinue2 |  | 69
ListContinue3 |  | 70
ListContinue4 |  | 71
ListContinue5 |  | 72
ListNumber | The List Number style. | 49
ListNumber2 |  | 58
ListNumber3 |  | 59
ListNumber4 |  | 60
ListNumber5 |  | 61
ListParagraph |  | 179
NoSpacing |  | 157
Normal | The Normal style. | 0
NormalWeb |  | 94
NormalIndent | The Normal Indent style. | 28
TableOfAuthorities |  | 44
TableOfFigures | The Table of Figures style. | 35
ToaHeading |  | 46
Toc1 |  | 19
Toc2 |  | 20
Toc3 |  | 21
Toc4 |  | 22
Toc5 |  | 23
Toc6 |  | 24
Toc7 |  | 25
Toc8 |  | 26
Toc9 |  | 27
TocHeading |  | 266
Revision |  | 178
OutlineList1 | The 1 / a / i style. | 108
OutlineList2 | The 1 / 1.1 / 1.1.1 style. | 109
OutlineList3 | The Article / Section style. | 110
NoList |  | 107
ColorfulGrid |  | 171
ColorfulGridAccent1 |  | 189
ColorfulGridAccent2 |  | 203
ColorfulGridAccent3 |  | 217
ColorfulGridAccent4 |  | 231
ColorfulGridAccent5 |  | 245
ColorfulGridAccent6 |  | 259
ColorfulList |  | 170
ColorfulListAccent1 |  | 188
ColorfulListAccent2 |  | 202
ColorfulListAccent3 |  | 216
ColorfulListAccent4 |  | 230
ColorfulListAccent5 |  | 244
ColorfulListAccent6 |  | 258
ColorfulShading |  | 169
ColorfulShadingAccent1 |  | 187
ColorfulShadingAccent2 |  | 201
ColorfulShadingAccent3 |  | 215
ColorfulShadingAccent4 |  | 229
ColorfulShadingAccent5 |  | 243
ColorfulShadingAccent6 |  | 257
DarkList |  | 168
DarkListAccent1 |  | 186
DarkListAccent2 |  | 200
DarkListAccent3 |  | 214
DarkListAccent4 |  | 228
DarkListAccent5 |  | 242
DarkListAccent6 |  | 256
LightGrid |  | 160
LightGridAccent1 |  | 174
LightGridAccent2 |  | 192
LightGridAccent3 |  | 206
LightGridAccent4 |  | 220
LightGridAccent5 |  | 234
LightGridAccent6 |  | 248
LightList |  | 159
LightListAccent1 |  | 173
LightListAccent2 |  | 191
LightListAccent3 |  | 205
LightListAccent4 |  | 219
LightListAccent5 |  | 233
LightListAccent6 |  | 247
LightShading |  | 158
LightShadingAccent1 |  | 172
LightShadingAccent2 |  | 190
LightShadingAccent3 |  | 204
LightShadingAccent4 |  | 218
LightShadingAccent5 |  | 232
LightShadingAccent6 |  | 246
MediumGrid1 |  | 165
MediumGrid1Accent1 |  | 183
MediumGrid1Accent2 |  | 197
MediumGrid1Accent3 |  | 211
MediumGrid1Accent4 |  | 225
MediumGrid1Accent5 |  | 239
MediumGrid1Accent6 |  | 253
MediumGrid2 |  | 166
MediumGrid2Accent1 |  | 184
MediumGrid2Accent2 |  | 198
MediumGrid2Accent3 |  | 212
MediumGrid2Accent4 |  | 226
MediumGrid2Accent5 |  | 240
MediumGrid2Accent6 |  | 254
MediumGrid3 |  | 167
MediumGrid3Accent1 |  | 185
MediumGrid3Accent2 |  | 199
MediumGrid3Accent3 |  | 213
MediumGrid3Accent4 |  | 227
MediumGrid3Accent5 |  | 241
MediumGrid3Accent6 |  | 255
MediumList1 |  | 163
MediumList1Accent1 |  | 177
MediumList1Accent2 |  | 195
MediumList1Accent3 |  | 209
MediumList1Accent4 |  | 223
MediumList1Accent5 |  | 237
MediumList1Accent6 |  | 251
MediumList2 |  | 164
MediumList2Accent1 |  | 182
MediumList2Accent2 |  | 196
MediumList2Accent3 |  | 210
MediumList2Accent4 |  | 224
MediumList2Accent5 |  | 238
MediumList2Accent6 |  | 252
MediumShading1 |  | 161
MediumShading1Accent1 |  | 175
MediumShading1Accent2 |  | 193
MediumShading1Accent3 |  | 207
MediumShading1Accent4 |  | 221
MediumShading1Accent5 |  | 235
MediumShading1Accent6 |  | 249
MediumShading2 |  | 162
MediumShading2Accent1 |  | 176
MediumShading2Accent2 |  | 194
MediumShading2Accent3 |  | 208
MediumShading2Accent4 |  | 222
MediumShading2Accent5 |  | 236
MediumShading2Accent6 |  | 250
Table3DEffects1 |  | 142
Table3DEffects2 |  | 143
Table3DEffects3 |  | 144
TableClassic1 |  | 114
TableClassic2 |  | 115
TableClassic3 |  | 116
TableClassic4 |  | 117
TableColorful1 |  | 118
TableColorful2 |  | 119
TableColorful3 |  | 120
TableColumns1 |  | 121
TableColumns2 |  | 122
TableColumns3 |  | 123
TableColumns4 |  | 124
TableColumns5 |  | 125
TableContemporary |  | 145
TableElegant |  | 146
TableGrid |  | 154
TableGrid1 |  | 126
TableGrid2 |  | 127
TableGrid3 |  | 128
TableGrid4 |  | 129
TableGrid5 |  | 130
TableGrid6 |  | 131
TableGrid7 |  | 132
TableGrid8 |  | 133
TableList1 |  | 134
TableList2 |  | 135
TableList3 |  | 136
TableList4 |  | 137
TableList5 |  | 138
TableList6 |  | 139
TableList7 |  | 140
TableList8 |  | 141
TableNormal |  | 105
TableProfessional |  | 147
TableSimple1 |  | 111
TableSimple2 |  | 112
TableSimple3 |  | 113
TableSubtle1 |  | 148
TableSubtle2 |  | 149
TableTheme |  | 155
TableWeb1 |  | 150
TableWeb2 |  | 151
TableWeb3 |  | 152
PlainTable1 | Plain Table 1 | 267
PlainTable2 | Plain Table 2 | 268
PlainTable3 | Plain Table 3 | 269
PlainTable4 | Plain Table 4 | 270
PlainTable5 | Plain Table 5 | 271
TableGridLight | Table Grid Light | 272
GridTable1Light | Grid Table 1 Light | 273
GridTable2 | Grid Table 2 | 274
GridTable3 | Grid Table 3 | 275
GridTable4 | Grid Table 4 | 276
GridTable5Dark | Grid Table 5 Dark | 277
GridTable6Colorful | Grid Table 6 Colorful | 278
GridTable7Colorful | Grid Table 7 Colorful | 279
GridTable1LightAccent1 | Grid Table 1 Light - Accent 1 | 280
GridTable2Accent1 | Grid Table 2 - Accent 1 | 281
GridTable3Accent1 | Grid Table 3 - Accent 1 | 282
GridTable4Accent1 | Grid Table 4 - Accent 1 | 283
GridTable5DarkAccent1 | Grid Table 5 Dark - Accent 1 | 284
GridTable6ColorfulAccent1 | Grid Table 6 Colorful - Accent 1 | 285
GridTable7ColorfulAccent1 | Grid Table 7 Colorful - Accent 1 | 286
GridTable1LightAccent2 | Grid Table 1 Light - Accent 2 | 287
GridTable2Accent2 | Grid Table 2 - Accent 2 | 288
GridTable3Accent2 | Grid Table 3 - Accent 2 | 289
GridTable4Accent2 | Grid Table 4 - Accent 2 | 290
GridTable5DarkAccent2 | Grid Table 5 Dark - Accent 2 | 291
GridTable6ColorfulAccent2 | Grid Table 6 Colorful - Accent 2 | 292
GridTable7ColorfulAccent2 | Grid Table 7 Colorful - Accent 2 | 293
GridTable1LightAccent3 | Grid Table 1 Light - Accent 3 | 294
GridTable2Accent3 | Grid Table 2 - Accent 3 | 295
GridTable3Accent3 | Grid Table 3 - Accent 3 | 296
GridTable4Accent3 | Grid Table 4 - Accent 3 | 297
GridTable5DarkAccent3 | Grid Table 5 Dark - Accent 3 | 298
GridTable6ColorfulAccent3 | Grid Table 6 Colorful - Accent 3 | 299
GridTable7ColorfulAccent3 | Grid Table 7 Colorful - Accent 3 | 300
GridTable1LightAccent4 | Grid Table 1 Light - Accent 4 | 301
GridTable2Accent4 | Grid Table 2 - Accent 4 | 302
GridTable3Accent4 | Grid Table 3 - Accent 4 | 303
GridTable4Accent4 | Grid Table 4 - Accent 4 | 304
GridTable5DarkAccent4 | Grid Table 5 Dark - Accent 4 | 305
GridTable6ColorfulAccent4 | Grid Table 6 Colorful - Accent 4 | 306
GridTable7ColorfulAccent4 | Grid Table 7 Colorful - Accent 4 | 307
GridTable1LightAccent5 | Grid Table 1 Light - Accent 5 | 308
GridTable2Accent5 | Grid Table 2 - Accent 5 | 309
GridTable3Accent5 | Grid Table 3 - Accent 5 | 310
GridTable4Accent5 | Grid Table 4 - Accent 5 | 311
GridTable5DarkAccent5 | Grid Table 5 Dark - Accent 5 | 312
GridTable6ColorfulAccent5 | Grid Table 6 Colorful - Accent 5 | 313
GridTable7ColorfulAccent5 | Grid Table 7 Colorful - Accent 5 | 314
GridTable1LightAccent6 | Grid Table 1 Light - Accent 6 | 315
GridTable2Accent6 | Grid Table 2 - Accent 6 | 316
GridTable3Accent6 | Grid Table 3 - Accent 6 | 317
GridTable4Accent6 | Grid Table 4 - Accent 6 | 318
GridTable5DarkAccent6 | Grid Table 5 Dark - Accent 6 | 319
GridTable6ColorfulAccent6 | Grid Table 6 Colorful - Accent 6 | 320
GridTable7ColorfulAccent6 | Grid Table 7 Colorful - Accent 6 | 321
ListTable1Light | List Table 1 Light | 322
ListTable2 | List Table 2 | 323
ListTable3 | List Table 3 | 324
ListTable4 | List Table 4 | 325
ListTable5Dark | List Table 5 Dark | 326
ListTable6Colorful | List Table 6 Colorful | 327
ListTable7Colorful | List Table 7 Colorful | 328
ListTable1LightAccent1 | List Table 1 Light - Accent 1 | 329
ListTable2Accent1 | List Table 2 - Accent 1 | 330
ListTable3Accent1 | List Table 3 - Accent 1 | 331
ListTable4Accent1 | List Table 4 - Accent 1 | 332
ListTable5DarkAccent1 | List Table 5 Dark - Accent 1 | 333
ListTable6ColorfulAccent1 | List Table 6 Colorful - Accent 1 | 334
ListTable7ColorfulAccent1 | List Table 7 Colorful - Accent 1 | 335
ListTable1LightAccent2 | List Table 1 Light - Accent 2 | 336
ListTable2Accent2 | List Table 2 - Accent 2 | 337
ListTable3Accent2 | List Table 3 - Accent 2 | 338
ListTable4Accent2 | List Table 4 - Accent 2 | 339
ListTable5DarkAccent2 | List Table 5 Dark - Accent 2 | 340
ListTable6ColorfulAccent2 | List Table 6 Colorful - Accent 2 | 341
ListTable7ColorfulAccent2 | List Table 7 Colorful - Accent 2 | 342
ListTable1LightAccent3 | List Table 1 Light - Accent 3 | 343
ListTable2Accent3 | List Table 2 - Accent 3 | 344
ListTable3Accent3 | List Table 3 - Accent 3 | 345
ListTable4Accent3 | List Table 4 - Accent 3 | 346
ListTable5DarkAccent3 | List Table 5 Dark - Accent 3 | 347
ListTable6ColorfulAccent3 | List Table 6 Colorful - Accent 3 | 348
ListTable7ColorfulAccent3 | List Table 7 Colorful - Accent 3 | 349
ListTable1LightAccent4 | List Table 1 Light - Accent 4 | 350
ListTable2Accent4 | List Table 2 - Accent 4 | 351
ListTable3Accent4 | List Table 3 - Accent 4 | 352
ListTable4Accent4 | List Table 4 - Accent 4 | 353
ListTable5DarkAccent4 | List Table 5 Dark - Accent 4 | 354
ListTable6ColorfulAccent4 | List Table 6 Colorful - Accent 4 | 355
ListTable7ColorfulAccent4 | List Table 7 Colorful - Accent 4 | 356
ListTable1LightAccent5 | List Table 1 Light - Accent 5 | 357
ListTable2Accent5 | List Table 2 - Accent 5 | 358
ListTable3Accent5 | List Table 3 - Accent 5 | 359
ListTable4Accent5 | List Table 4 - Accent 5 | 360
ListTable5DarkAccent5 | List Table 5 Dark - Accent 5 | 361
ListTable6ColorfulAccent5 | List Table 6 Colorful - Accent 5 | 362
ListTable7ColorfulAccent5 | List Table 7 Colorful - Accent 5 | 363
ListTable1LightAccent6 | List Table 1 Light - Accent 6 | 364
ListTable2Accent6 | List Table 2 - Accent 6 | 365
ListTable3Accent6 | List Table 3 - Accent 6 | 366
ListTable4Accent6 | List Table 4 - Accent 6 | 367
ListTable5DarkAccent6 | List Table 5 Dark - Accent 6 | 368
ListTable6ColorfulAccent6 | List Table 6 Colorful - Accent 6 | 369
ListTable7ColorfulAccent6 | List Table 7 Colorful - Accent 6 | 370
User | A user defined style. | 4094
Nil | Reserved for internal use. | 4095

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


StyleType Enumeration

Represents type of the style.

[Visual Basic]
Public Enum StyleType
[C#]
public enum StyleType

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

Members

Member Name | Description | Value
Paragraph | The style is a paragraph style. | 1
Character | The style is a character style. | 2
Table | The style is a table style. | 3
List | The style is a list style. | 4

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


SubDocument Class

Represents a SubDocument - which is a reference to an externally stored document.

For a list of all members of this type, see SubDocument Members.

System.Object
Aspose.Words.Node
Aspose.Words.SubDocument

[Visual Basic]
Public Class SubDocument
Inherits Node
[C#]
public class SubDocument : Node

Remarks

In this version of Aspose.Words, SubDocument nodes do not provide public methods and properties to create or modify a subdocument. In this version you are not able to instantiate Subdocument nodes or modify existing except deleting them.

SubDocument can only be a child of Paragraph.

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SubDocument Members | Aspose.Words Namespace


SubDocument Members

SubDocument overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.SubDocument
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

SubDocument Class | Aspose.Words Namespace


SubDocument Properties

The properties of the SubDocument class are listed below. For a complete list of SubDocument class members, see the SubDocument Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.SubDocument
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

SubDocument Class | Aspose.Words Namespace


NodeType Property

Aspose.Words

SubDocument.NodeType Property

Returns NodeType.SubDocument

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

See Also

SubDocument Class | Aspose.Words Namespace


SubDocument Methods

The methods of the SubDocument class are listed below. For a complete list of SubDocument class members, see the SubDocument Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from Node) | Gets the text of this node and of all its children.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

SubDocument Class | Aspose.Words Namespace


SubDocument.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

See Also

SubDocument Class | Aspose.Words Namespace


TabAlignment Enumeration

Specifies the alignment/type of a tab stop.

[Visual Basic]
Public Enum TabAlignment
[C#]
public enum TabAlignment

Members

Member Name | Description | Value
Left | Left-aligns the text after the tab stop. | 0
Center | Centers the text around the tab stop. | 1
Right | Right-aligns the text at the tab stop. | 2
Decimal | Aligns the text at the decimal dot. | 3
Bar | Draws a vertical bar at the tab stop position. | 4
List | The tab is a delimiter between the number/bullet and text in a list item. | 6
Clear | Clears any tab stop in this position. | 7

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TabLeader Enumeration

Specifies the type of the leader line displayed under the tab character.

[Visual Basic]
Public Enum TabLeader
[C#]
public enum TabLeader

Members

Member Name | Description | Value
None | No leader line is displayed. | 0
Dots | The leader line is made up from dots. | 1
Dashes | The leader line is made up from dashes. | 2
Line | The leader line is a single line. | 3
Heavy | The leader line is a single thick line. | 4
MiddleDot | The leader line is made up from middle-dots. | 5

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TableStyle Class

Represents a table style.

For a list of all members of this type, see TableStyle Members.

System.Object
Aspose.Words.Style
Aspose.Words.TableStyle

[Visual Basic]
Public Class TableStyle
Inherits Style
[C#]
public class TableStyle : Style

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TableStyle Members | Aspose.Words Namespace


TableStyle Members

TableStyle overview

Public Instance Properties

Aliases (inherited from Style) | Gets all aliases of this style. If style has no aliases then empty array of string is returned.
Alignment | Specifies the alignment for the table style.
AllowBreakAcrossPages | Gets or sets a flag indicating whether text in a table row is allowed to split across a page break.
BaseStyleName (inherited from Style) | Gets/sets the name of the style this style is based on.
Bidi | Gets or sets whether this is a style for a right-to-left table.
Borders | Gets the collection of default cell borders for the style.
BottomPadding | Gets or sets the amount of space (in points) to add below the contents of table cells.
BuiltIn (inherited from Style) | True if this style is one of the built-in styles in MS Word.
CellSpacing | Gets or sets the amount of space (in points) between the cells.
ColumnStripe | Gets or sets a number of columns to include in the banding when the style specifies odd/even columns banding.
ConditionalStyles | Collection of conditional styles that may be defined for this table style.
Document (inherited from Style) | Gets the owner document.
Font (inherited from Style) | Gets the character formatting of the style.
IsHeading (inherited from Style) | True when the style is one of the built-in Heading styles.
IsQuickStyle (inherited from Style) | Specifies whether this style is shown in the Quick Style gallery inside MS Word UI.
LeftIndent | Gets or sets the value that represents the left indent of a table.
LeftPadding | Gets or sets the amount of space (in points) to add to the left of the contents of table cells.
LinkedStyleName (inherited from Style) | Gets the name of the Style linked to this one. Returns Empty string if no styles are linked.
List (inherited from Style) | Gets the list that defines formatting of this list style.
ListFormat (inherited from Style) | Provides access to the list formatting properties of a paragraph style.
Name (inherited from Style) | Gets or sets the name of the style.
NextParagraphStyleName (inherited from Style) | Gets/sets the name of the style to be applied automatically to a new paragraph inserted after a paragraph formatted with the specified style.
ParagraphFormat (inherited from Style) | Gets the paragraph formatting of the style.
RightPadding | Gets or sets the amount of space (in points) to add to the right of the contents of table cells.
RowStripe | Gets or sets a number of rows to include in the banding when the style specifies odd/even row banding.
Shading | Gets a Shading object that refers to the shading formatting for table cells.
StyleIdentifier (inherited from Style) | Gets the locale independent style identifier for a built-in style.
Styles (inherited from Style) | Gets the collection of styles this style belongs to.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of table cells.
Type (inherited from Style) | Gets the style type (paragraph or character).

Public Instance Methods

ClearCellAttrs |
Remove (inherited from Style) | Removes the specified style from the document.

See Also

TableStyle Class | Aspose.Words Namespace


TableStyle Properties

The properties of the TableStyle class are listed below. For a complete list of TableStyle class members, see the TableStyle Members topic.

Public Instance Properties

Aliases (inherited from Style) | Gets all aliases of this style. If style has no aliases then empty array of string is returned.
Alignment | Specifies the alignment for the table style.
AllowBreakAcrossPages | Gets or sets a flag indicating whether text in a table row is allowed to split across a page break.
BaseStyleName (inherited from Style) | Gets/sets the name of the style this style is based on.
Bidi | Gets or sets whether this is a style for a right-to-left table.
Borders | Gets the collection of default cell borders for the style.
BottomPadding | Gets or sets the amount of space (in points) to add below the contents of table cells.
BuiltIn (inherited from Style) | True if this style is one of the built-in styles in MS Word.
CellSpacing | Gets or sets the amount of space (in points) between the cells.
ColumnStripe | Gets or sets a number of columns to include in the banding when the style specifies odd/even columns banding.
ConditionalStyles | Collection of conditional styles that may be defined for this table style.
Document (inherited from Style) | Gets the owner document.
Font (inherited from Style) | Gets the character formatting of the style.
IsHeading (inherited from Style) | True when the style is one of the built-in Heading styles.
IsQuickStyle (inherited from Style) | Specifies whether this style is shown in the Quick Style gallery inside MS Word UI.
LeftIndent | Gets or sets the value that represents the left indent of a table.
LeftPadding | Gets or sets the amount of space (in points) to add to the left of the contents of table cells.
LinkedStyleName (inherited from Style) | Gets the name of the Style linked to this one. Returns Empty string if no styles are linked.
List (inherited from Style) | Gets the list that defines formatting of this list style.
ListFormat (inherited from Style) | Provides access to the list formatting properties of a paragraph style.
Name (inherited from Style) | Gets or sets the name of the style.
NextParagraphStyleName (inherited from Style) | Gets/sets the name of the style to be applied automatically to a new paragraph inserted after a paragraph formatted with the specified style.
ParagraphFormat (inherited from Style) | Gets the paragraph formatting of the style.
RightPadding | Gets or sets the amount of space (in points) to add to the right of the contents of table cells.
RowStripe | Gets or sets a number of rows to include in the banding when the style specifies odd/even row banding.
Shading | Gets a Shading object that refers to the shading formatting for table cells.
StyleIdentifier (inherited from Style) | Gets the locale independent style identifier for a built-in style.
Styles (inherited from Style) | Gets the collection of styles this style belongs to.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of table cells.
Type (inherited from Style) | Gets the style type (paragraph or character).

See Also

TableStyle Class | Aspose.Words Namespace


Alignment Property

Aspose.Words

TableStyle.Alignment Property

Specifies the alignment for the table style.

[Visual Basic]
Public Property Alignment As TableAlignment
[C#]
public TableAlignment Alignment {get; set;}

Remarks

The default value is Left.

Example

Shows how to set table position.

[C#]

Document doc = new Document();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// By default AW uses Alignment instead of LeftIndent
// To set table position use
tableStyle.Alignment = TableAlignment.Center;
// or
tableStyle.LeftIndent = 55.0;

See Also

TableStyle Class | Aspose.Words Namespace


AllowBreakAcrossPages Property

Aspose.Words

TableStyle.AllowBreakAcrossPages Property

Gets or sets a flag indicating whether text in a table row is allowed to split across a page break.

[Visual Basic]
Public Property AllowBreakAcrossPages As Boolean
[C#]
public bool AllowBreakAcrossPages {get; set;}

Remarks

The default value is true.

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


Bidi Property

Aspose.Words

TableStyle.Bidi Property

Gets or sets whether this is a style for a right-to-left table.

[Visual Basic]
Public Property Bidi As Boolean
[C#]
public bool Bidi {get; set;}

Remarks

When true, the cells in rows are laid out right to left.

The default value is false.

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


Borders Property

Aspose.Words

TableStyle.Borders Property

Gets the collection of default cell borders for the style.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


BottomPadding Property

Aspose.Words

TableStyle.BottomPadding Property

Gets or sets the amount of space (in points) to add below the contents of table cells.

[Visual Basic]
Public Property BottomPadding As Double
[C#]
public double BottomPadding {get; set;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


CellSpacing Property

Aspose.Words

TableStyle.CellSpacing Property

Gets or sets the amount of space (in points) between the cells.

[Visual Basic]
Public Property CellSpacing As Double
[C#]
public double CellSpacing {get; set;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


ColumnStripe Property

Aspose.Words

TableStyle.ColumnStripe Property

Gets or sets a number of columns to include in the banding when the style specifies odd/even columns banding.

[Visual Basic]
Public Property ColumnStripe As Integer
[C#]
public int ColumnStripe {get; set;}

Example

Shows how to work with odd/even row/column styles.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;
// Define our stripe through one column and row
tableStyle.ColumnStripe = 1;
tableStyle.RowStripe = 1;
// Let's start from the first row and second column
tableStyle.ConditionalStyles[ConditionalStyleType.OddRowBanding].Shading.BackgroundPatternColor = Color.AliceBlue;
tableStyle.ConditionalStyles[ConditionalStyleType.EvenColumnBanding].Shading.BackgroundPatternColor = Color.AliceBlue;

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithOddEvenRowColumnStyles.docx");

See Also

TableStyle Class | Aspose.Words Namespace


ConditionalStyles Property

Aspose.Words

TableStyle.ConditionalStyles Property

Collection of conditional styles that may be defined for this table style.

[Visual Basic]
Public ReadOnly Property ConditionalStyles As ConditionalStyleCollection
[C#]
public ConditionalStyleCollection ConditionalStyles {get;}

See Also

TableStyle Class | Aspose.Words Namespace


LeftIndent Property

Aspose.Words

TableStyle.LeftIndent Property

Gets or sets the value that represents the left indent of a table.

[Visual Basic]
Public Property LeftIndent As Double
[C#]
public double LeftIndent {get; set;}

Example

Shows how to set table position.

[C#]

Document doc = new Document();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
// By default AW uses Alignment instead of LeftIndent
// To set table position use
tableStyle.Alignment = TableAlignment.Center;
// or
tableStyle.LeftIndent = 55.0;

See Also

TableStyle Class | Aspose.Words Namespace


LeftPadding Property

Aspose.Words

TableStyle.LeftPadding Property

Gets or sets the amount of space (in points) to add to the left of the contents of table cells.

[Visual Basic]
Public Property LeftPadding As Double
[C#]
public double LeftPadding {get; set;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


RightPadding Property

Aspose.Words

TableStyle.RightPadding Property

Gets or sets the amount of space (in points) to add to the right of the contents of table cells.

[Visual Basic]
Public Property RightPadding As Double
[C#]
public double RightPadding {get; set;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


RowStripe Property

Aspose.Words

TableStyle.RowStripe Property

Gets or sets a number of rows to include in the banding when the style specifies odd/even row banding.

[Visual Basic]
Public Property RowStripe As Integer
[C#]
public int RowStripe {get; set;}

Example

Shows how to work with odd/even row/column styles.

[C#]

Document doc = new Document(MyDir + "Table.ConditionalStyles.docx");

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;
// Define our stripe through one column and row
tableStyle.ColumnStripe = 1;
tableStyle.RowStripe = 1;
// Let's start from the first row and second column
tableStyle.ConditionalStyles[ConditionalStyleType.OddRowBanding].Shading.BackgroundPatternColor = Color.AliceBlue;
tableStyle.ConditionalStyles[ConditionalStyleType.EvenColumnBanding].Shading.BackgroundPatternColor = Color.AliceBlue;

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.WorkWithOddEvenRowColumnStyles.docx");

See Also

TableStyle Class | Aspose.Words Namespace


Shading Property

Aspose.Words

TableStyle.Shading Property

Gets a Shading object that refers to the shading formatting for table cells.

[Visual Basic]
Public ReadOnly Property Shading As Shading
[C#]
public Shading Shading {get;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


TopPadding Property

Aspose.Words

TableStyle.TopPadding Property

Gets or sets the amount of space (in points) to add above the contents of table cells.

[Visual Basic]
Public Property TopPadding As Double
[C#]
public double TopPadding {get; set;}

Example

Shows how to create your own style settings for the table.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("مرحبًا");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();

TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.AllowBreakAcrossPages = true;
tableStyle.Bidi = true;
tableStyle.CellSpacing = 5.0;
tableStyle.BottomPadding = 20.0;
tableStyle.LeftPadding = 5;
tableStyle.RightPadding = 10;
tableStyle.TopPadding = 20.0;
tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
tableStyle.Borders.Color = Color.Black;
tableStyle.Borders.LineStyle = LineStyle.DotDash;

table.Style = tableStyle;

doc.Save(ArtifactsDir + "Table.TableStyleCreation.docx");

See Also

TableStyle Class | Aspose.Words Namespace


TableStyle Methods

The methods of the TableStyle class are listed below. For a complete list of TableStyle class members, see the TableStyle Members topic.

Public Instance Methods

ClearCellAttrs |
Remove (inherited from Style) | Removes the specified style from the document.

See Also

TableStyle Class | Aspose.Words Namespace


TableStyle.ClearCellAttrs Method

[Visual Basic]
NotOverridable Public Sub ClearCellAttrs()
[C#]
public void ClearCellAttrs();

See Also

TableStyle Class | Aspose.Words Namespace


TabStop Class

Represents a single custom tab stop. The TabStop object is a member of the TabStopCollection collection.

For a list of all members of this type, see TabStop Members.

System.Object
Aspose.Words.TabStop

[Visual Basic]
NotInheritable Public Class TabStop
[C#]
public sealed class TabStop

Remarks

Normally, a tab stop specifies a position where a tab stop exists. But because tab stops can be inherited from parent styles, it might be needed for the child object to define explicitly that there is no tab stop at a given position. To clear an inherited tab stop at a given position, create a TabStop object and set Alignment to TabAlignment.Clear.

For more information see TabStopCollection.

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TabStop Members | Aspose.Words Namespace | ParagraphFormat | TabStopCollection | DefaultTabStop


TabStop Members

TabStop overview

Public Instance Constructors

TabStop Overloaded. Initializes a new instance of the TabStop class.

Public Instance Properties

Alignment | Gets or sets the alignment of text at this tab stop.
IsClear | Returns true if this tab stop clears any existing tab stops in this position.
Leader | Gets or sets the type of the leader line displayed under the tab character.
Position | Gets the position of the tab stop in points.

See Also

TabStop Class | Aspose.Words Namespace | ParagraphFormat | TabStopCollection | DefaultTabStop


TabStop Constructor

Initializes a new instance of this class.

Overload List

Initializes a new instance of this class.

public TabStop(double);

Initializes a new instance of this class.

public TabStop(double,TabAlignment,TabLeader);

See Also

TabStop Class | Aspose.Words Namespace


TabStop Constructor (Double)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal position As Double _
)
[C#]
public TabStop(
double position
);

See Also

TabStop Class | Aspose.Words Namespace | TabStop Constructor Overload List


TabStop Constructor (Double, TabAlignment, TabLeader)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal position As Double, _
ByVal alignment As TabAlignment, _
ByVal leader As TabLeader _
)
[C#]
public TabStop(
double position,
TabAlignment alignment,
TabLeader leader
);

Parameters

position
The position of the tab stop in points.
alignment
A TabAlignment value that specifies the alignment of text at this tab stop.
leader
A TabLeader value that specifies the type of the leader line displayed under the tab character.

See Also

TabStop Class | Aspose.Words Namespace | TabStop Constructor Overload List


TabStop Properties

The properties of the TabStop class are listed below. For a complete list of TabStop class members, see the TabStop Members topic.

Public Instance Properties

Alignment | Gets or sets the alignment of text at this tab stop.
IsClear | Returns true if this tab stop clears any existing tab stops in this position.
Leader | Gets or sets the type of the leader line displayed under the tab character.
Position | Gets the position of the tab stop in points.

See Also

TabStop Class | Aspose.Words Namespace | ParagraphFormat | TabStopCollection | DefaultTabStop


Alignment Property

Aspose.Words

TabStop.Alignment Property

Gets or sets the alignment of text at this tab stop.

[Visual Basic]
Public Property Alignment As TabAlignment
[C#]
public TabAlignment Alignment {get; set;}

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

See Also

TabStop Class | Aspose.Words Namespace


IsClear Property

Aspose.Words

TabStop.IsClear Property

Returns true if this tab stop clears any existing tab stops in this position.

[Visual Basic]
Public ReadOnly Property IsClear As Boolean
[C#]
public bool IsClear {get;}

See Also

TabStop Class | Aspose.Words Namespace


Leader Property

Aspose.Words

TabStop.Leader Property

Gets or sets the type of the leader line displayed under the tab character.

[Visual Basic]
Public Property Leader As TabLeader
[C#]
public TabLeader Leader {get; set;}

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

See Also

TabStop Class | Aspose.Words Namespace


Position Property

Aspose.Words

TabStop.Position Property

Gets the position of the tab stop in points.

[Visual Basic]
Public ReadOnly Property Position As Double
[C#]
public double Position {get;}

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

See Also

TabStop Class | Aspose.Words Namespace


TabStopCollection Class

A collection of TabStop objects that represent custom tabs for a paragraph or a style.

For a list of all members of this type, see TabStopCollection Members.

System.Object
Aspose.Words.InternableComplexAttr
Aspose.Words.TabStopCollection

[Visual Basic]
Public Class TabStopCollection
Inherits InternableComplexAttr
[C#]
public class TabStopCollection : InternableComplexAttr

Remarks

In Microsoft Word documents, a tab stop can be defined in the properties of a paragraph style or directly in the properties of a paragraph. A style can be based on another style. Therefore, the complete set of tab stops for a given object is a combination of tab stops defined directly on this object and tab stops inherited from the parent styles.

In Aspose.Words, when you obtain a TabStops collection for a paragraph or a style, it contains only the custom tab stops defined directly for this paragraph or style. The collection does not include tab stops defined in the parent styles or default tab stops.

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TabStopCollection Members | Aspose.Words Namespace | ParagraphFormat | TabStop | DefaultTabStop


TabStopCollection Members

TabStopCollection overview

Public Instance Properties

Count | Gets the number of tab stops in the collection.
Item | Overloaded. Retrieves a tab stop from the collection.

Public Instance Methods

Add | Overloaded. Adds or replaces a tab stop in the collection.
After | Gets a first tab stop to the right of the specified position.
Before | Gets a first tab stop to the left of the specified position.
Clear | Deletes all tab stop positions.
Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.
GetIndexByPosition | Gets the index of a tab stop with the specified position in points.
GetPositionByIndex | Gets the position (in points) of the tab stop at the specified index.
RemoveByIndex | Removes a tab stop at the specified index from the collection.
RemoveByPosition | Removes a tab stop at the specified position from the collection.

See Also

TabStopCollection Class | Aspose.Words Namespace | ParagraphFormat | TabStop | DefaultTabStop


TabStopCollection Properties

The properties of the TabStopCollection class are listed below. For a complete list of TabStopCollection class members, see the TabStopCollection Members topic.

Public Instance Properties

Count | Gets the number of tab stops in the collection.
Item | Overloaded. Retrieves a tab stop from the collection.

See Also

TabStopCollection Class | Aspose.Words Namespace | ParagraphFormat | TabStop | DefaultTabStop


Count Property

Aspose.Words

TabStopCollection.Count Property

Gets the number of tab stops in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

TabStopCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

TabStopCollection.Item Property

Retrieves a tab stop from the collection.

Overload List

Gets a tab stop at the specified position.

public TabStop this[double] {get;}

Gets a tab stop at the given index.

public TabStop this[int] {get;}

See Also

TabStopCollection Class | Aspose.Words Namespace


Item Property (Double)

Aspose.Words

TabStopCollection.Item Property (Double)

Gets a tab stop at the specified position.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal position As Double _
) As TabStop
[C#]
public TabStop this[
double position
] {get;}

Parameters

position
The position (in points) of the tab stop.

Remarks

Returns null if no tab stop is found at the specified position.

See Also

TabStopCollection Class | Aspose.Words Namespace | TabStopCollection.Item Overload List


Item Property (Int32)

Aspose.Words

TabStopCollection.Item Property (Int32)

Gets a tab stop at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As TabStop
[C#]
public TabStop this[
int index
] {get;}

Parameters

index
An index into the collection of tab stops.

See Also

TabStopCollection Class | Aspose.Words Namespace | TabStopCollection.Item Overload List


TabStopCollection Methods

The methods of the TabStopCollection class are listed below. For a complete list of TabStopCollection class members, see the TabStopCollection Members topic.

Public Instance Methods

Add | Overloaded. Adds or replaces a tab stop in the collection.
After | Gets a first tab stop to the right of the specified position.
Before | Gets a first tab stop to the left of the specified position.
Clear | Deletes all tab stop positions.
Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.
GetIndexByPosition | Gets the index of a tab stop with the specified position in points.
GetPositionByIndex | Gets the position (in points) of the tab stop at the specified index.
RemoveByIndex | Removes a tab stop at the specified index from the collection.
RemoveByPosition | Removes a tab stop at the specified position from the collection.

See Also

TabStopCollection Class | Aspose.Words Namespace | ParagraphFormat | TabStop | DefaultTabStop


Add Method

Aspose.Words

TabStopCollection.Add Method

Adds or replaces a tab stop in the collection.

Overload List

Adds or replaces a tab stop in the collection.

public void Add(TabStop);

Adds or replaces a tab stop in the collection.

public void Add(double,TabAlignment,TabLeader);

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.Add Method (TabStop)

Adds or replaces a tab stop in the collection.

[Visual Basic]
Overloads Public Sub Add( _
ByVal tabStop As TabStop _
)
[C#]
public void Add(
TabStop tabStop
);

Parameters

tabStop
A tab stop object to add.

Remarks

If a tab stop already exists at the specified position, it is replaced.

Example

Shows how to create tab stops and add them to a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Create a TabStop object and add it to the document.
TabStop tabStop = new TabStop(ConvertUtil.InchToPoint(3), TabAlignment.Left, TabLeader.Dashes);
paragraph.ParagraphFormat.TabStops.Add(tabStop);

// Add a tab stop without explicitly creating new TabStop objects.
paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(100), TabAlignment.Left,
    TabLeader.Dashes);

// Add tab stops at 5 cm to all paragraphs.
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    para.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(50), TabAlignment.Left,
        TabLeader.Dashes);
}

doc.Save(ArtifactsDir + "Document.AddedTabStops.doc");

See Also

TabStopCollection Class | Aspose.Words Namespace | TabStopCollection.Add Overload List


TabStopCollection.Add Method (Double, TabAlignment, TabLeader)

Adds or replaces a tab stop in the collection.

[Visual Basic]
Overloads Public Sub Add( _
ByVal position As Double, _
ByVal alignment As TabAlignment, _
ByVal leader As TabLeader _
)
[C#]
public void Add(
double position,
TabAlignment alignment,
TabLeader leader
);

Parameters

position
A position (in points) where to add the tab stop.
alignment
A TabAlignment value that specifies the alignment of text at the tab stop.
leader
A TabLeader value that specifies the type of the leader line displayed under the tab character.

Remarks

If a tab stop already exists at the specified position, it is replaced.

Example

Shows how to create tab stops and add them to a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

// Create a TabStop object and add it to the document.
TabStop tabStop = new TabStop(ConvertUtil.InchToPoint(3), TabAlignment.Left, TabLeader.Dashes);
paragraph.ParagraphFormat.TabStops.Add(tabStop);

// Add a tab stop without explicitly creating new TabStop objects.
paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(100), TabAlignment.Left,
    TabLeader.Dashes);

// Add tab stops at 5 cm to all paragraphs.
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    para.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(50), TabAlignment.Left,
        TabLeader.Dashes);
}

doc.Save(ArtifactsDir + "Document.AddedTabStops.doc");

See Also

TabStopCollection Class | Aspose.Words Namespace | TabStopCollection.Add Overload List


TabStopCollection.After Method

Gets a first tab stop to the right of the specified position.

[Visual Basic]
Public Function After( _
ByVal position As Double _
) As TabStop
[C#]
public TabStop After(
double position
);

Parameters

position
The reference position (in points).

Return Value

A tab stop object or null if a suitable tab stop was not found.

Remarks

Skips tab stops with Alignment set to TabAlignment.Bar.

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.Before Method

Gets a first tab stop to the left of the specified position.

[Visual Basic]
Public Function Before( _
ByVal position As Double _
) As TabStop
[C#]
public TabStop Before(
double position
);

Parameters

position
The reference position (in points).

Return Value

A tab stop object or null if a suitable tab stop was not found.

Remarks

Skips tab stops with Alignment set to TabAlignment.Bar.

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.Clear Method

Deletes all tab stop positions.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to remove all tab stops from a document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Clear all tab stops from every paragraph.
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    para.ParagraphFormat.TabStops.Clear();
}

doc.Save(ArtifactsDir + "Document.AllTabStopsRemoved.doc");

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.Equals Method

Determines whether the specified object is equal in value to the current object.

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.GetHashCode Method

Serves as a hash function for this type.

[Visual Basic]
Overrides Public Function GetHashCode() As Integer
[C#]
public override int GetHashCode();

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.GetIndexByPosition Method

Gets the index of a tab stop with the specified position in points.

[Visual Basic]
Public Function GetIndexByPosition( _
ByVal position As Double _
) As Integer
[C#]
public int GetIndexByPosition(
double position
);

Example

Shows how to look up a position to see if a tab stop exists there, and if so, obtain its index.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(30), TabAlignment.Left,
    TabLeader.Dashes);

// An output of -1 signifies that there is no tab stop at that position.
Console.WriteLine(
    paragraph.ParagraphFormat.TabStops.GetIndexByPosition(ConvertUtil.MillimeterToPoint(30))); // 0
Console.WriteLine(
    paragraph.ParagraphFormat.TabStops.GetIndexByPosition(ConvertUtil.MillimeterToPoint(60))); // -1

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.GetPositionByIndex Method

Gets the position (in points) of the tab stop at the specified index.

[Visual Basic]
Public Function GetPositionByIndex( _
ByVal index As Integer _
) As Double
[C#]
public double GetPositionByIndex(
int index
);

Parameters

index
An index into the collection of tab stops.

Return Value

The position of the tab stop.

Example

Shows how to find a tab stop by it's index and get its position.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(30), TabAlignment.Left,
    TabLeader.Dashes);
paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(60), TabAlignment.Left,
    TabLeader.Dashes);

Console.WriteLine("Tab stop at index {0} of the first paragraph is at {1} points.", 1,
    paragraph.ParagraphFormat.TabStops.GetPositionByIndex(1));

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.RemoveByIndex Method

Removes a tab stop at the specified index from the collection.

[Visual Basic]
Public Sub RemoveByIndex( _
ByVal index As Integer _
)
[C#]
public void RemoveByIndex(
int index
);

Parameters

index
An index into the collection of tab stops.

Example

Shows how to select a tab stop in a document by its index and remove it.

[C#]

Document doc = new Document(MyDir + "Document.doc");
Paragraph paragraph = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);

paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(30), TabAlignment.Left,
    TabLeader.Dashes);
paragraph.ParagraphFormat.TabStops.Add(ConvertUtil.MillimeterToPoint(60), TabAlignment.Left,
    TabLeader.Dashes);

// Tab stop placed at 30 mm is removed
paragraph.ParagraphFormat.TabStops.RemoveByIndex(0);

Console.WriteLine(paragraph.ParagraphFormat.TabStops.Count);

doc.Save(ArtifactsDir + "Document.RemovedTabStopsByIndex.doc");

See Also

TabStopCollection Class | Aspose.Words Namespace


TabStopCollection.RemoveByPosition Method

Removes a tab stop at the specified position from the collection.

[Visual Basic]
Public Sub RemoveByPosition( _
ByVal position As Double _
)
[C#]
public void RemoveByPosition(
double position
);

Parameters

position
The position (in points) of the tab stop to remove.

Example

Shows how to modify the position of the right tab stop in TOC related paragraphs.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
    if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 &&
        para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
    {
        // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        TabStop tab = para.ParagraphFormat.TabStops[0];
        // Remove the old tab from the collection.
        para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
        // Insert a new tab using the same properties but at a modified position.
        // We could also change the separators used (dots) by passing a different Leader type
        para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
    }
}

doc.Save(ArtifactsDir + "Document.TableOfContentsTabStops.doc");

See Also

TabStopCollection Class | Aspose.Words Namespace


TextColumn Class

Represents a single text column. TextColumn is a member of the TextColumnCollection collection. The TextColumns collection includes all the columns in a section of a document.

For a list of all members of this type, see TextColumn Members.

System.Object
Aspose.Words.TextColumn

[Visual Basic]
Public Class TextColumn
[C#]
public class TextColumn

Remarks

TextColumn objects are only used to specify columns with custom width and spacing. If you want the columns in the document to be of equal width, set TextColumns.EvenlySpaced to true.

When a new TextColumn is created it has its width and spacing set to zero.

Example

Creates multiple columns of different widths in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Show vertical line between columns.
columns.LineBetween = true;
// Indicate we want to create column with different widths.
columns.EvenlySpaced = false;
// Create two columns, note they will be created with zero widths, need to set them.
columns.SetCount(2);

// Set the first column to be narrow.
TextColumn c1 = columns[0];
c1.Width = 100;
c1.SpaceAfter = 20;

// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns[1];
PageSetup ps = builder.PageSetup;
double contentWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
c2.Width = contentWidth - c1.Width - c1.SpaceAfter;

builder.Writeln("Narrow column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Wide column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsCustomWidth.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TextColumn Members | Aspose.Words Namespace | TextColumnCollection | PageSetup | Section


TextColumn Members

TextColumn overview

Public Instance Properties

SpaceAfter | Gets or sets the space between this column and the next column in points. Not required for the last column.
Width | Gets or sets the width of the text column in points.

See Also

TextColumn Class | Aspose.Words Namespace | TextColumnCollection | PageSetup | Section


TextColumn Properties

The properties of the TextColumn class are listed below. For a complete list of TextColumn class members, see the TextColumn Members topic.

Public Instance Properties

SpaceAfter | Gets or sets the space between this column and the next column in points. Not required for the last column.
Width | Gets or sets the width of the text column in points.

See Also

TextColumn Class | Aspose.Words Namespace | TextColumnCollection | PageSetup | Section


SpaceAfter Property

Aspose.Words

TextColumn.SpaceAfter Property

Gets or sets the space between this column and the next column in points. Not required for the last column.

[Visual Basic]
Public Property SpaceAfter As Double
[C#]
public double SpaceAfter {get; set;}

Example

Creates multiple columns of different widths in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Show vertical line between columns.
columns.LineBetween = true;
// Indicate we want to create column with different widths.
columns.EvenlySpaced = false;
// Create two columns, note they will be created with zero widths, need to set them.
columns.SetCount(2);

// Set the first column to be narrow.
TextColumn c1 = columns[0];
c1.Width = 100;
c1.SpaceAfter = 20;

// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns[1];
PageSetup ps = builder.PageSetup;
double contentWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
c2.Width = contentWidth - c1.Width - c1.SpaceAfter;

builder.Writeln("Narrow column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Wide column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsCustomWidth.doc");

See Also

TextColumn Class | Aspose.Words Namespace


Width Property

Aspose.Words

TextColumn.Width Property

Gets or sets the width of the text column in points.

[Visual Basic]
Public Property Width As Double
[C#]
public double Width {get; set;}

Example

Creates multiple columns of different widths in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Show vertical line between columns.
columns.LineBetween = true;
// Indicate we want to create column with different widths.
columns.EvenlySpaced = false;
// Create two columns, note they will be created with zero widths, need to set them.
columns.SetCount(2);

// Set the first column to be narrow.
TextColumn c1 = columns[0];
c1.Width = 100;
c1.SpaceAfter = 20;

// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns[1];
PageSetup ps = builder.PageSetup;
double contentWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
c2.Width = contentWidth - c1.Width - c1.SpaceAfter;

builder.Writeln("Narrow column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Wide column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsCustomWidth.doc");

See Also

TextColumn Class | Aspose.Words Namespace


TextColumnCollection Class

A collection of TextColumn objects that represent all the columns of text in a section of a document.

For a list of all members of this type, see TextColumnCollection Members.

System.Object
Aspose.Words.TextColumnCollection

[Visual Basic]
Public Class TextColumnCollection
[C#]
public class TextColumnCollection

Remarks

Use SetCount to set the number of text columns.

To make all columns equal width and spaced evenly, set EvenlySpaced to true and specify the amount of space between the columns in Spacing. MS Word will automatically calculate column widths.

If you have EvenlySpaced set to false, you need to specify width and spacing for each column individually. Use the indexer to access individual TextColumn objects.

When using custom column widths, make sure the sum of all column widths and spacings between them equals page width minus left and right page margins.

Example

Creates multiple evenly spaced columns in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Make spacing between columns wider.
columns.Spacing = 100;
// This creates two columns of equal width.
columns.SetCount(2);

builder.Writeln("Text in column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Text in column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsSameWidth.doc");

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TextColumnCollection Members | Aspose.Words Namespace | PageSetup | Section


TextColumnCollection Members

TextColumnCollection overview

Public Instance Properties

Count | Gets the number of columns in the section of a document.
EvenlySpaced | True if text columns are of equal width and evenly spaced.
Item | Returns a text column at the specified index.
LineBetween | When true, adds a vertical line between columns.
Spacing | When columns are evenly spaced, gets or sets the amount of space between each column in points.
Width | When columns are evenly spaced, gets the width of the columns.

Public Instance Methods

SetCount Arranges text into the specified number of text columns.

See Also

TextColumnCollection Class | Aspose.Words Namespace | PageSetup | Section


TextColumnCollection Properties

The properties of the TextColumnCollection class are listed below. For a complete list of TextColumnCollection class members, see the TextColumnCollection Members topic.

Public Instance Properties

Count | Gets the number of columns in the section of a document.
EvenlySpaced | True if text columns are of equal width and evenly spaced.
Item | Returns a text column at the specified index.
LineBetween | When true, adds a vertical line between columns.
Spacing | When columns are evenly spaced, gets or sets the amount of space between each column in points.
Width | When columns are evenly spaced, gets the width of the columns.

See Also

TextColumnCollection Class | Aspose.Words Namespace | PageSetup | Section


Count Property

Aspose.Words

TextColumnCollection.Count Property

Gets the number of columns in the section of a document.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

TextColumnCollection Class | Aspose.Words Namespace


EvenlySpaced Property

Aspose.Words

TextColumnCollection.EvenlySpaced Property

True if text columns are of equal width and evenly spaced.

[Visual Basic]
Public Property EvenlySpaced As Boolean
[C#]
public bool EvenlySpaced {get; set;}

Example

Creates multiple columns of different widths in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Show vertical line between columns.
columns.LineBetween = true;
// Indicate we want to create column with different widths.
columns.EvenlySpaced = false;
// Create two columns, note they will be created with zero widths, need to set them.
columns.SetCount(2);

// Set the first column to be narrow.
TextColumn c1 = columns[0];
c1.Width = 100;
c1.SpaceAfter = 20;

// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns[1];
PageSetup ps = builder.PageSetup;
double contentWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
c2.Width = contentWidth - c1.Width - c1.SpaceAfter;

builder.Writeln("Narrow column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Wide column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsCustomWidth.doc");

See Also

TextColumnCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

TextColumnCollection.Item Property

Returns a text column at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As TextColumn
[C#]
public TextColumn this[
int index
] {get;}

Example

Creates multiple columns of different widths in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Show vertical line between columns.
columns.LineBetween = true;
// Indicate we want to create column with different widths.
columns.EvenlySpaced = false;
// Create two columns, note they will be created with zero widths, need to set them.
columns.SetCount(2);

// Set the first column to be narrow.
TextColumn c1 = columns[0];
c1.Width = 100;
c1.SpaceAfter = 20;

// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns[1];
PageSetup ps = builder.PageSetup;
double contentWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
c2.Width = contentWidth - c1.Width - c1.SpaceAfter;

builder.Writeln("Narrow column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Wide column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsCustomWidth.doc");

See Also

TextColumnCollection Class | Aspose.Words Namespace


LineBetween Property

Aspose.Words

TextColumnCollection.LineBetween Property

When true, adds a vertical line between columns.

[Visual Basic]
Public Property LineBetween As Boolean
[C#]
public bool LineBetween {get; set;}

Example

Creates multiple columns of different widths in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Show vertical line between columns.
columns.LineBetween = true;
// Indicate we want to create column with different widths.
columns.EvenlySpaced = false;
// Create two columns, note they will be created with zero widths, need to set them.
columns.SetCount(2);

// Set the first column to be narrow.
TextColumn c1 = columns[0];
c1.Width = 100;
c1.SpaceAfter = 20;

// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns[1];
PageSetup ps = builder.PageSetup;
double contentWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;
c2.Width = contentWidth - c1.Width - c1.SpaceAfter;

builder.Writeln("Narrow column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Wide column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsCustomWidth.doc");

See Also

TextColumnCollection Class | Aspose.Words Namespace


Spacing Property

Aspose.Words

TextColumnCollection.Spacing Property

When columns are evenly spaced, gets or sets the amount of space between each column in points.

[Visual Basic]
Public Property Spacing As Double
[C#]
public double Spacing {get; set;}

Remarks

Has effect only when EvenlySpaced is set to true.

Example

Creates multiple evenly spaced columns in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Make spacing between columns wider.
columns.Spacing = 100;
// This creates two columns of equal width.
columns.SetCount(2);

builder.Writeln("Text in column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Text in column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsSameWidth.doc");

See Also

TextColumnCollection Class | Aspose.Words Namespace


Width Property

Aspose.Words

TextColumnCollection.Width Property

When columns are evenly spaced, gets the width of the columns.

[Visual Basic]
Public ReadOnly Property Width As Double
[C#]
public double Width {get;}

Remarks

Has effect only when EvenlySpaced is set to true.

See Also

TextColumnCollection Class | Aspose.Words Namespace


TextColumnCollection Methods

The methods of the TextColumnCollection class are listed below. For a complete list of TextColumnCollection class members, see the TextColumnCollection Members topic.

Public Instance Methods

SetCount Arranges text into the specified number of text columns.

See Also

TextColumnCollection Class | Aspose.Words Namespace | PageSetup | Section


TextColumnCollection.SetCount Method

Arranges text into the specified number of text columns.

[Visual Basic]
Public Sub SetCount( _
ByVal newCount As Integer _
)
[C#]
public void SetCount(
int newCount
);

Parameters

newCount
The number of columns the text is to be arranged into.

Remarks

When EvenlySpaced is false and you increase the number of columns, new TextColumn objects are created with zero width and spacing. You need to set width and spacing for the new columns.

Example

Creates multiple evenly spaced columns in a section using DocumentBuilder.

[C#]

DocumentBuilder builder = new DocumentBuilder();

TextColumnCollection columns = builder.PageSetup.TextColumns;
// Make spacing between columns wider.
columns.Spacing = 100;
// This creates two columns of equal width.
columns.SetCount(2);

builder.Writeln("Text in column 1.");
builder.InsertBreak(BreakType.ColumnBreak);
builder.Writeln("Text in column 2.");

builder.Document.Save(ArtifactsDir + "PageSetup.ColumnsSameWidth.doc");

See Also

TextColumnCollection Class | Aspose.Words Namespace


TextDmlEffect Enumeration

Dml text effect for text runs.

[Visual Basic]
Public Enum TextDmlEffect
[C#]
public enum TextDmlEffect

Members

Member Name | Description | Value
Glow | Glow effect, in which a color blurred outline is added outside the edges of the object. | 0
Fill | Fill overlay effect. | 1
Shadow | Shadow effect. | 2
Outline | Outline effect. | 3
Effect3D | 3D effect. | 4
Reflection | Reflection effect. | 5

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TextEffect Enumeration

Animation effect for text runs.

[Visual Basic]
Public Enum TextEffect
[C#]
public enum TextEffect

Members

Member Name | Description | Value
None |  | 0
LasVegasLights |  | 1
BlinkingBackground |  | 2
SparkleText |  | 3
MarchingBlackAnts |  | 4
MarchingRedAnts |  | 5
Shimmer |  | 6

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TextOrientation Enumeration

Specifies orientation of text on a page, in a table cell or a text frame.

[Visual Basic]
Public Enum TextOrientation
[C#]
public enum TextOrientation

Example

Shows how to build a formatted table that contains 2 rows and 2 columns.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

Members

Member Name | Description | Value
Horizontal | Text is arranged horizontally (lr-tb). | 0
Downward | Text is rotated 90 degrees to the right to appear from top to bottom (tb-rl). | 1
Upward | Text is rotated 90 degrees to the left to appear from bottom to top (bt-lr). | 3
HorizontalRotatedFarEast | Text is arranged horizontally, but Far East characters are rotated 90 degrees to the left (lr-tb-v). | 4
VerticalFarEast | Far East characters appear vertical, other text is rotated 90 degrees to the right to appear from top to bottom (tb-rl-v). | 5
VerticalRotatedFarEast | Far East characters appear vertical, other text is rotated 90 degrees to the right to appear from top to bottom vertically, then left to right horizontally (tb-lr-v). | 7

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TextureIndex Enumeration

Specifies shading texture.

[Visual Basic]
Public Enum TextureIndex
[C#]
public enum TextureIndex

Example

Shows how to apply borders and shading to a paragraph.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = Color.LightCoral;
shading.ForegroundPatternColor = Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");
Shows how to apply a outline border to a table.
[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

doc.Save(ArtifactsDir + "Table.SetOutlineBorders.doc");

Members

Member Name | Description | Value
Texture10Percent |  | 3
Texture12Pt5Percent |  | 37
Texture15Percent |  | 38
Texture17Pt5Percent |  | 39
Texture20Percent |  | 4
Texture22Pt5Percent |  | 40
Texture25Percent |  | 5
Texture27Pt5Percent |  | 41
Texture2Pt5Percent |  | 35
Texture30Percent |  | 6
Texture32Pt5Percent |  | 42
Texture35Percent |  | 43
Texture37Pt5Percent |  | 44
Texture40Percent |  | 7
Texture42Pt5Percent |  | 45
Texture45Percent |  | 46
Texture47Pt5Percent |  | 47
Texture50Percent |  | 8
Texture52Pt5Percent |  | 48
Texture55Percent |  | 49
Texture57Pt5Percent |  | 50
Texture5Percent |  | 2
Texture60Percent |  | 9
Texture62Pt5Percent |  | 51
Texture65Percent |  | 52
Texture67Pt5Percent |  | 53
Texture70Percent |  | 10
Texture72Pt5Percent |  | 54
Texture75Percent |  | 11
Texture77Pt5Percent |  | 55
Texture7Pt5Percent |  | 36
Texture80Percent |  | 12
Texture82Pt5Percent |  | 56
Texture85Percent |  | 57
Texture87Pt5Percent |  | 58
Texture90Percent |  | 13
Texture92Pt5Percent |  | 59
Texture95Percent |  | 60
Texture97Pt5Percent |  | 61
TextureCross |  | 24
TextureDarkCross |  | 18
TextureDarkDiagonalCross |  | 19
TextureDarkDiagonalDown |  | 16
TextureDarkDiagonalUp |  | 17
TextureDarkHorizontal |  | 14
TextureDarkVertical |  | 15
TextureDiagonalCross |  | 25
TextureDiagonalDown |  | 22
TextureDiagonalUp |  | 23
TextureHorizontal |  | 20
TextureNone |  | 0
TextureSolid |  | 1
TextureVertical |  | 21
TextureNil | Specifies that there shall be no pattern used on the current shaded region (i.e. the pattern shall be a complete fill with the background color). | 65535

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TxtLeadingSpacesOptions Enumeration

Specifies available options for leading space handling during import from Text file.

[Visual Basic]
Public Enum TxtLeadingSpacesOptions
[C#]
public enum TxtLeadingSpacesOptions

Example

Shows how to load plain text as is.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions
{
    // If it sets to true Aspose.Words insert additional periods after numbers in the content.
    DetectNumberingWithWhitespaces = false,
    TrailingSpacesOptions = TxtTrailingSpacesOptions.Preserve,
    LeadingSpacesOptions = TxtLeadingSpacesOptions.Preserve
};

Document doc = new Document(MyDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt", loadOptions);
doc.Save(ArtifactsDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt");

Members

Member Name | Description | Value
ConvertToIndent |  | 0
Trim |  | 1
Preserve |  | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


TxtLoadOptions Class

Allows to specify additional options when loading Text document into a Document object.

For a list of all members of this type, see TxtLoadOptions Members.

System.Object
Aspose.Words.LoadOptions
Aspose.Words.TxtLoadOptions

[Visual Basic]
Public Class TxtLoadOptions
Inherits LoadOptions
[C#]
public class TxtLoadOptions : LoadOptions

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TxtLoadOptions Members | Aspose.Words Namespace


TxtLoadOptions Members

TxtLoadOptions overview

Public Instance Constructors

TxtLoadOptions Constructor Initializes a new instance of this class with default values.

Public Instance Properties

AnnotationsAtBlockLevel (inherited from LoadOptions) | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri (inherited from LoadOptions) | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath (inherited from LoadOptions) | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
DetectNumberingWithWhitespaces | Allows to specify how numbered list items are recognized when document is imported from plain text format. The default value is true.
Encoding (inherited from LoadOptions) | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings (inherited from LoadOptions) | Allows to specify document font settings.
LanguagePreferences (inherited from LoadOptions) | Gets language preferences that will be used when document is loading.
LeadingSpacesOptions | Gets or sets preferred option of a leading space handling. Default value is ConvertToIndent.
LoadFormat (inherited from LoadOptions) | Specifies the format of the document to be loaded. Default is Auto.
MswVersion (inherited from LoadOptions) | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password (inherited from LoadOptions) | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreserveIncludePictureField (inherited from LoadOptions) | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
ResourceLoadingCallback (inherited from LoadOptions) | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
TrailingSpacesOptions | Gets or sets preferred option of a trailing space handling. Default value is Trim.
UpdateDirtyFields (inherited from LoadOptions) | Specifies whether to update the fields with the dirty attribute.
WarningCallback (inherited from LoadOptions) | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

TxtLoadOptions Class | Aspose.Words Namespace


TxtLoadOptions Constructor

Initializes a new instance of this class with default values.

[Visual Basic]
Public Sub New()
[C#]
public TxtLoadOptions();

See Also

TxtLoadOptions Class | Aspose.Words Namespace


TxtLoadOptions Properties

The properties of the TxtLoadOptions class are listed below. For a complete list of TxtLoadOptions class members, see the TxtLoadOptions Members topic.

Public Instance Properties

AnnotationsAtBlockLevel (inherited from LoadOptions) | Gets or sets a flag indicating whether cross structure annotation nodes can be added at block/cell/row level.
BaseUri (inherited from LoadOptions) | Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.
ConvertShapeToOfficeMath (inherited from LoadOptions) | Gets or sets whether to convert shapes with EquationXML to Office Math objects.
DetectNumberingWithWhitespaces | Allows to specify how numbered list items are recognized when document is imported from plain text format. The default value is true.
Encoding (inherited from LoadOptions) | Gets or sets the encoding that will be used to load an HTML or TXT document if the encoding is not specified in HTML/TXT. Can be null. Default is null.
FontSettings (inherited from LoadOptions) | Allows to specify document font settings.
LanguagePreferences (inherited from LoadOptions) | Gets language preferences that will be used when document is loading.
LeadingSpacesOptions | Gets or sets preferred option of a leading space handling. Default value is ConvertToIndent.
LoadFormat (inherited from LoadOptions) | Specifies the format of the document to be loaded. Default is Auto.
MswVersion (inherited from LoadOptions) | Allows to specify that the document loading process should match a specific MS Word version. Default value is Word2007
Password (inherited from LoadOptions) | Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.
PreserveIncludePictureField (inherited from LoadOptions) | Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.
ResourceLoadingCallback (inherited from LoadOptions) | Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.
TrailingSpacesOptions | Gets or sets preferred option of a trailing space handling. Default value is Trim.
UpdateDirtyFields (inherited from LoadOptions) | Specifies whether to update the fields with the dirty attribute.
WarningCallback (inherited from LoadOptions) | Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

TxtLoadOptions Class | Aspose.Words Namespace


DetectNumberingWithWhitespaces Property

Aspose.Words

TxtLoadOptions.DetectNumberingWithWhitespaces Property

Allows to specify how numbered list items are recognized when document is imported from plain text format. The default value is true.

[Visual Basic]
Public Property DetectNumberingWithWhitespaces As Boolean
[C#]
public bool DetectNumberingWithWhitespaces {get; set;}

Remarks

If this option is set to false, lists recognition algorithm detects list paragraphs, when list numbers ends with either dot, right bracket or bullet symbols (such as "•", "*", "-" or "o").

If this option is set to true, whitespaces are also used as list number delimeters: list recognition algorithm for Arabic style numbering (1., 1.1.2.) uses both whitespaces and dot (".") symbols.

Example

Shows how to load plain text as is.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions
{
    // If it sets to true Aspose.Words insert additional periods after numbers in the content.
    DetectNumberingWithWhitespaces = false,
    TrailingSpacesOptions = TxtTrailingSpacesOptions.Preserve,
    LeadingSpacesOptions = TxtLeadingSpacesOptions.Preserve
};

Document doc = new Document(MyDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt", loadOptions);
doc.Save(ArtifactsDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt");

See Also

TxtLoadOptions Class | Aspose.Words Namespace


LeadingSpacesOptions Property

Aspose.Words

TxtLoadOptions.LeadingSpacesOptions Property

Gets or sets preferred option of a leading space handling. Default value is ConvertToIndent.

[Visual Basic]
Public Property LeadingSpacesOptions As TxtLeadingSpacesOptions
[C#]
public TxtLeadingSpacesOptions LeadingSpacesOptions {get; set;}

Example

Shows how to load plain text as is.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions
{
    // If it sets to true Aspose.Words insert additional periods after numbers in the content.
    DetectNumberingWithWhitespaces = false,
    TrailingSpacesOptions = TxtTrailingSpacesOptions.Preserve,
    LeadingSpacesOptions = TxtLeadingSpacesOptions.Preserve
};

Document doc = new Document(MyDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt", loadOptions);
doc.Save(ArtifactsDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt");

See Also

TxtLoadOptions Class | Aspose.Words Namespace


TrailingSpacesOptions Property

Aspose.Words

TxtLoadOptions.TrailingSpacesOptions Property

Gets or sets preferred option of a trailing space handling. Default value is Trim.

[Visual Basic]
Public Property TrailingSpacesOptions As TxtTrailingSpacesOptions
[C#]
public TxtTrailingSpacesOptions TrailingSpacesOptions {get; set;}

Example

Shows how to load plain text as is.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions
{
    // If it sets to true Aspose.Words insert additional periods after numbers in the content.
    DetectNumberingWithWhitespaces = false,
    TrailingSpacesOptions = TxtTrailingSpacesOptions.Preserve,
    LeadingSpacesOptions = TxtLeadingSpacesOptions.Preserve
};

Document doc = new Document(MyDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt", loadOptions);
doc.Save(ArtifactsDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt");

See Also

TxtLoadOptions Class | Aspose.Words Namespace


TxtTrailingSpacesOptions Enumeration

Specifies available options for trailing spaces handling during import from Text file.

[Visual Basic]
Public Enum TxtTrailingSpacesOptions
[C#]
public enum TxtTrailingSpacesOptions

Example

Shows how to load plain text as is.

[C#]

TxtLoadOptions loadOptions = new TxtLoadOptions
{
    // If it sets to true Aspose.Words insert additional periods after numbers in the content.
    DetectNumberingWithWhitespaces = false,
    TrailingSpacesOptions = TxtTrailingSpacesOptions.Preserve,
    LeadingSpacesOptions = TxtLeadingSpacesOptions.Preserve
};

Document doc = new Document(MyDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt", loadOptions);
doc.Save(ArtifactsDir + "TxtLoadOptions.DetectNumberingWithWhitespaces.txt");

Members

Member Name | Description | Value
Trim |  | 0
Preserve |  | 1

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Underline Enumeration

Indicates type of the underline applied to a font.

[Visual Basic]
Public Enum Underline
[C#]
public enum Underline

Example

Inserts a hyperlink into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Please make sure to visit ");

// Specify font formatting for the hyperlink.
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;
// Insert the link.
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false);

// Revert to default formatting.
builder.Font.ClearFormatting();

builder.Write(" for more information.");

doc.Save(ArtifactsDir + "DocumentBuilder.InsertHyperlink.doc");

Members

Member Name | Description | Value
None |  | 0
Single |  | 1
Words |  | 2
Double |  | 3
Dotted |  | 4
Thick |  | 6
Dash |  | 7
DashLong |  | 39
DotDash |  | 9
DotDotDash |  | 10
Wavy |  | 11
DottedHeavy |  | 20
DashHeavy |  | 23
DashLongHeavy |  | 55
DotDashHeavy |  | 25
DotDotDashHeavy |  | 26
WavyHeavy |  | 27
WavyDouble |  | 43

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


UnsupportedFileFormatException Class

Thrown during document load, when the document format is not recognized or not supported by Aspose.Words.

System.Object
System.Exception
Aspose.Words.UnsupportedFileFormatException

[Visual Basic]
Public Class UnsupportedFileFormatException
Inherits Exception
[C#]
public class UnsupportedFileFormatException : Exception

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


VariableCollection Class

A collection of document variables.

For a list of all members of this type, see VariableCollection Members.

System.Object
Aspose.Words.VariableCollection

[Visual Basic]
Public Class VariableCollection
Implements IEnumerable`1([System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089),[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), IEnumerable
[C#]
public class VariableCollection : 0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], IEnumerable

Remarks

Variable names and values are strings.

Variable names are case-insensitive.

Example

Shows how to enumerate over document variables.

[C#]

Document doc = new Document(MyDir + "Document.doc");

foreach (KeyValuePair<string, string> entry in doc.Variables)
{
    String name = entry.Key;
    String value = entry.Value;

    // Do something useful.
    Console.WriteLine("Name: {0}, Value: {1}", name, value);
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

VariableCollection Members | Aspose.Words Namespace


VariableCollection Members

VariableCollection overview

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Overloaded. Provides access to the collection items.

Public Instance Methods

Add | Adds a document variable to the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains a document variable with the given name.
GetEnumerator | Returns an enumerator object that can be used to iterate over all variable in the collection.
IndexOfKey | Returns the zero-based index of the specified document variable in the collection.
Remove | Removes a document variable with the specified name from the collection.
RemoveAt | Removes a document variable at the specified index.

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection Properties

The properties of the VariableCollection class are listed below. For a complete list of VariableCollection class members, see the VariableCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Overloaded. Provides access to the collection items.

See Also

VariableCollection Class | Aspose.Words Namespace


Count Property

Aspose.Words

VariableCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to clear all document variables from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

doc.Variables.Clear();
Console.WriteLine(doc.Variables.Count); // 0

See Also

VariableCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

VariableCollection.Item Property

Provides access to the collection items.

Overload List

Gets or sets a document variable at the specified index. null values are not allowed as a right hand side of the assignment and will be replaced by empty string.

public string this[int] {get; set;}

Gets or a sets a document variable by the case-insensitive name. null values are not allowed as a right hand side of the assignment and will be replaced by empty string.

public string this[string] {get; set;}

See Also

VariableCollection Class | Aspose.Words Namespace


Item Property (Int32)

Aspose.Words

VariableCollection.Item Property (Int32)

Gets or sets a document variable at the specified index. null values are not allowed as a right hand side of the assignment and will be replaced by empty string.

[Visual Basic]
Overloads Public Default Property Item( _
ByVal index As Integer _
) As String
[C#]
public string this[
int index
] {get; set;}

Parameters

index
Zero-based index of the document variable.

See Also

VariableCollection Class | Aspose.Words Namespace | VariableCollection.Item Overload List


Item Property (String)

Aspose.Words

VariableCollection.Item Property (String)

Gets or a sets a document variable by the case-insensitive name. null values are not allowed as a right hand side of the assignment and will be replaced by empty string.

[Visual Basic]
Overloads Public Default Property Item( _
ByVal name As String _
) As String
[C#]
public string this[
string name
] {get; set;}

See Also

VariableCollection Class | Aspose.Words Namespace | VariableCollection.Item Overload List


VariableCollection Methods

The methods of the VariableCollection class are listed below. For a complete list of VariableCollection class members, see the VariableCollection Members topic.

Public Instance Methods

Add | Adds a document variable to the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains a document variable with the given name.
GetEnumerator | Returns an enumerator object that can be used to iterate over all variable in the collection.
IndexOfKey | Returns the zero-based index of the specified document variable in the collection.
Remove | Removes a document variable with the specified name from the collection.
RemoveAt | Removes a document variable at the specified index.

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.Add Method

Adds a document variable to the collection.

[Visual Basic]
Public Sub Add( _
ByVal name As String, _
ByVal value As String _
)
[C#]
public void Add(
string name,
string value
);

Parameters

name
The case-insensitive name of the variable to add.
value
The value of the variable. The value cannot be null, if value is null empty string will be used instead.

Example

Shows how to create document variables and add them to a document's variable collection.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Word processing document");
// Duplicate values can be stored but adding a duplicate name overwrites the old one.
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to clear all document variables from a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

doc.Variables.Clear();
Console.WriteLine(doc.Variables.Count); // 0

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.Contains Method

Determines whether the collection contains a document variable with the given name.

[Visual Basic]
Public Function Contains( _
ByVal name As String _
) As Boolean
[C#]
public bool Contains(
string name
);

Parameters

name
Case-insensitive name of the document variable to locate.

Return Value

True if item is found in the collection; otherwise, false.

Example

Shows how to check if a collection of document variables contains a key.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");

Console.WriteLine(doc.Variables.Contains("doc")); // True
Console.WriteLine(doc.Variables.Contains("Word processing document")); // False

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all variable in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of KeyValuePair`2([System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089),[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089))) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to obtain an enumerator from a collection of document variables and use it.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

using (IEnumerator<KeyValuePair<string, string>> enumerator = doc.Variables.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        KeyValuePair<string, string> de = enumerator.Current;
        Console.WriteLine("Name: {0}, Value: {1}", de.Key, de.Value);
    }
}

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.IndexOfKey Method

Returns the zero-based index of the specified document variable in the collection.

[Visual Basic]
Public Function IndexOfKey( _
ByVal name As String _
) As Integer
[C#]
public int IndexOfKey(
string name
);

Parameters

name
The case-insensitive name of the variable.

Return Value

The zero based index. Negative value if not found.

Example

Shows how to get the index of a key.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

Console.WriteLine(doc.Variables.IndexOfKey("bmp")); // 0
Console.WriteLine(doc.Variables.IndexOfKey("txt")); // 4

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.Remove Method

Removes a document variable with the specified name from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal name As String _
)
[C#]
public void Remove(
string name
);

Parameters

name
The case-insensitive name of the variable.

Example

Shows how to remove an element from a document's variable collection by key.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

doc.Variables.Remove("bmp");
Console.WriteLine(doc.Variables.Count); // 4

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.RemoveAt Method

Removes a document variable at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to remove an element from a document's variable collection by index.

[C#]

Document doc = new Document(MyDir + "Document.doc");

doc.Variables.Add("doc", "Word processing document");
doc.Variables.Add("docx", "Word processing document");
doc.Variables.Add("txt", "Plain text file");
doc.Variables.Add("bmp", "Image");
doc.Variables.Add("png", "Image");

int index = doc.Variables.IndexOfKey("bmp");
doc.Variables.RemoveAt(index);
Console.WriteLine(doc.Variables.Count); // 4

See Also

VariableCollection Class | Aspose.Words Namespace


VbaModule Class

Provides access to VBA project module.

For a list of all members of this type, see VbaModule Members.

System.Object
Aspose.Words.VbaModule

[Visual Basic]
Public Class VbaModule
[C#]
public class VbaModule

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

VbaModule Members | Aspose.Words Namespace


VbaModule Members

VbaModule overview

Public Instance Properties

Name | Returns VBA project module name.
SourceCode | Returns VBA project module source code.

See Also

VbaModule Class | Aspose.Words Namespace


VbaModule Properties

The properties of the VbaModule class are listed below. For a complete list of VbaModule class members, see the VbaModule Members topic.

Public Instance Properties

Name | Returns VBA project module name.
SourceCode | Returns VBA project module source code.

See Also

VbaModule Class | Aspose.Words Namespace


Name Property

Aspose.Words

VbaModule.Name Property

Returns VBA project module name.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

See Also

VbaModule Class | Aspose.Words Namespace


SourceCode Property

Aspose.Words

VbaModule.SourceCode Property

Returns VBA project module source code.

[Visual Basic]
Public ReadOnly Property SourceCode As String
[C#]
public string SourceCode {get;}

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

See Also

VbaModule Class | Aspose.Words Namespace


VbaModuleCollection Class

Represents a collection of VbaModule objects.

For a list of all members of this type, see VbaModuleCollection Members.

System.Object
Aspose.Words.VbaModuleCollection

[Visual Basic]
NotInheritable Public Class VbaModuleCollection
Implements IEnumerable`1([Aspose.Words.VbaModule, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public sealed class VbaModuleCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

VbaModuleCollection Members | Aspose.Words Namespace


VbaModuleCollection Members

VbaModuleCollection overview

Public Instance Constructors

VbaModuleCollection Constructor Initializes a new instance of the VbaModuleCollection class.

Public Instance Properties

Item Retrieves a VbaModule object by index.

See Also

VbaModuleCollection Class | Aspose.Words Namespace


VbaModuleCollection Constructor

Initializes a new instance of the VbaModuleCollection class.

[Visual Basic]
Public Sub New()
[C#]
public VbaModuleCollection();

See Also

VbaModuleCollection Class | Aspose.Words Namespace


VbaModuleCollection Properties

The properties of the VbaModuleCollection class are listed below. For a complete list of VbaModuleCollection class members, see the VbaModuleCollection Members topic.

Public Instance Properties

Item Retrieves a VbaModule object by index.

See Also

VbaModuleCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

VbaModuleCollection.Item Property

Retrieves a VbaModule object by index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As VbaModule
[C#]
public VbaModule this[
int index
] {get;}

Parameters

index
Zero-based index of the conditional style to retrieve.

See Also

VbaModuleCollection Class | Aspose.Words Namespace


VbaProject Class

Provides access to VBA project information. A VBA project inside the document is defined as a collection of VBA modules.

For a list of all members of this type, see VbaProject Members.

System.Object
Aspose.Words.VbaProject

[Visual Basic]
Public Class VbaProject
[C#]
public class VbaProject

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

VbaProject Members | Aspose.Words Namespace


VbaProject Members

VbaProject overview

Public Instance Properties

Modules | Returns collection of VBA project modules.
Name | Returns VBA project name.

See Also

VbaProject Class | Aspose.Words Namespace


VbaProject Properties

The properties of the VbaProject class are listed below. For a complete list of VbaProject class members, see the VbaProject Members topic.

Public Instance Properties

Modules | Returns collection of VBA project modules.
Name | Returns VBA project name.

See Also

VbaProject Class | Aspose.Words Namespace


Modules Property

Aspose.Words

VbaProject.Modules Property

Returns collection of VBA project modules.

[Visual Basic]
Public ReadOnly Property Modules As VbaModuleCollection
[C#]
public VbaModuleCollection Modules {get;}

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

See Also

VbaProject Class | Aspose.Words Namespace


Name Property

Aspose.Words

VbaProject.Name Property

Returns VBA project name.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Example

Shows how to get access to VBA project information in the document.

[C#]

Document doc = new Document(MyDir + "Document.TestButton.docm");

// A VBA project inside the document is defined as a collection of VBA modules
VbaProject vbaProject = doc.VbaProject;
Console.WriteLine($"Project name: {vbaProject.Name}; Modules count: {vbaProject.Modules.Count()}\n");

VbaModuleCollection vbaModules = doc.VbaProject.Modules;
foreach (VbaModule module in vbaModules)
{
    Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");
}

See Also

VbaProject Class | Aspose.Words Namespace


VisitorAction Enumeration

Allows the visitor to control the enumeration of nodes.

[Visual Basic]
Public Enum VisitorAction
[C#]
public enum VisitorAction

Example

Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.

[C#]

// Open the document we want to convert.
    Document doc = new Document(MyDir + "Visitor.ToText.doc");

    // Create an object that inherits from the DocumentVisitor class.
    MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).
    //
    // Note that every node in the object model has the Accept method so the visiting
    // can be executed not only for the whole document, but for any node in the document.
    doc.Accept(myConverter);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor.
    Console.WriteLine(myConverter.GetText());
}

/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyDocToTxtWriter : DocumentVisitor
{
    public MyDocToTxtWriter()
    {
        this.mIsSkipText = false;
        this.mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return this.mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        this.AppendText(run.Text);

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
        // after a field start character. We want to skip field codes and output field
        // result only, therefore we use a flag to suspend the output while inside a field code.
        //
        // Note this is a very simplistic implementation and will not work very well
        // if you have nested fields in a document.
        this.mIsSkipText = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // Once reached a field separator node, we enable the output because we are
        // now entering the field result nodes.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        // Make sure we enable the output when reached a field end because some fields
        // do not have field separator and do not have field result.
        this.mIsSkipText = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Paragraph node is ended in the document.
    /// </summary>
    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        // When outputting to plain text we output Cr+Lf characters.
        this.AppendText(ControlChar.CrLf);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyStart(Body body)
    {
        // We can detect beginning and end of all composite nodes such as Section, Body,
        // Table, Paragraph etc and provide custom handling for them.
        this.mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        this.mBuilder.Append("*** Body Ended ***\r\n");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a HeaderFooter node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
    {
        // Returning this value from a visitor method causes visiting of this
        // node to stop and move on to visiting the next sibling node.
        // The net effect in this example is that the text of headers and footers
        // is not included in the resulting output.
        return VisitorAction.SkipThisNode;
    }

    /// <summary>
    /// Called when an AbsolutePositionTab is encountered in the document.
    /// </summary>
    public override VisitorAction VisitAbsolutePositionTab(AbsolutePositionTab tab)
    {
        this.mBuilder.Append("\t");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkStart is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
    {
        this.mBuilder.Append("[");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a BookmarkEnd is encountered in the document.
    /// </summary>
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
    {
        this.mBuilder.Append("]");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(String text)
    {
        if (!this.mIsSkipText)
            this.mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}

Members

Member Name | Description | Value
Continue | The visitor requests the enumeration to continue. | 0
SkipThisNode | The visitor requests to skip the current node and continue enumeration. | 1
Stop | The visitor requests the enumeration of nodes to stop. | 2

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


WarningInfo Class

Contains information about a warning that Aspose.Words issued during document loading or saving.

For a list of all members of this type, see WarningInfo Members.

System.Object
Aspose.Words.WarningInfo

[Visual Basic]
Public Class WarningInfo
[C#]
public class WarningInfo

Remarks

You do not create instances of this class. Objects of this class are created and passed by Aspose.Words to the Warning method.

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

WarningInfo Members | Aspose.Words Namespace | IWarningCallback


WarningInfo Members

WarningInfo overview

Public Instance Properties

Description | Returns the description of the warning.
Source | Returns the source of the warning.
WarningType | Returns the type of the warning.

See Also

WarningInfo Class | Aspose.Words Namespace | IWarningCallback


WarningInfo Properties

The properties of the WarningInfo class are listed below. For a complete list of WarningInfo class members, see the WarningInfo Members topic.

Public Instance Properties

Description | Returns the description of the warning.
Source | Returns the source of the warning.
WarningType | Returns the type of the warning.

See Also

WarningInfo Class | Aspose.Words Namespace | IWarningCallback


Description Property

Aspose.Words

WarningInfo.Description Property

Returns the description of the warning.

[Visual Basic]
Public ReadOnly Property Description As String
[C#]
public string Description {get;}

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

See Also

WarningInfo Class | Aspose.Words Namespace


Source Property

Aspose.Words

WarningInfo.Source Property

Returns the source of the warning.

[Visual Basic]
Public ReadOnly Property Source As WarningSource
[C#]
public WarningSource Source {get;}

See Also

WarningInfo Class | Aspose.Words Namespace


WarningType Property

Aspose.Words

WarningInfo.WarningType Property

Returns the type of the warning.

[Visual Basic]
Public ReadOnly Property WarningType As WarningType
[C#]
public WarningType WarningType {get;}

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

See Also

WarningInfo Class | Aspose.Words Namespace


WarningInfoCollection Class

Represents a typed collection of WarningInfo objects.

For a list of all members of this type, see WarningInfoCollection Members.

System.Object
Aspose.Words.WarningInfoCollection

[Visual Basic]
Public Class WarningInfoCollection
Implements IWarningCallback, IEnumerable`1([Aspose.Words.WarningInfo, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class WarningInfoCollection : IWarningCallback, 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

You can use this collection object as the simplest form of IWarningCallback implementation to gather all warnings that Aspose.Words generates during a load or save operation. Create an instance of this class and assign it to the WarningCallback or WarningCallback property.

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

WarningInfoCollection Members | Aspose.Words Namespace | WarningInfo | IWarningCallback


WarningInfoCollection Members

WarningInfoCollection overview

Public Instance Constructors

WarningInfoCollection Constructor Initializes a new instance of the WarningInfoCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets an item at the specified index.

Public Instance Methods

Clear | Removes all elements from the collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
Warning | Implements the IWarningCallback interface. Adds a warning to this collection.

See Also

WarningInfoCollection Class | Aspose.Words Namespace | WarningInfo | IWarningCallback


WarningInfoCollection Constructor

Initializes a new instance of the WarningInfoCollection class.

[Visual Basic]
Public Sub New()
[C#]
public WarningInfoCollection();

See Also

WarningInfoCollection Class | Aspose.Words Namespace


WarningInfoCollection Properties

The properties of the WarningInfoCollection class are listed below. For a complete list of WarningInfoCollection class members, see the WarningInfoCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets an item at the specified index.

See Also

WarningInfoCollection Class | Aspose.Words Namespace | WarningInfo | IWarningCallback


Count Property

Aspose.Words

WarningInfoCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

WarningInfoCollection Class | Aspose.Words Namespace


Item Property

Aspose.Words

WarningInfoCollection.Item Property

Gets an item at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As WarningInfo
[C#]
public WarningInfo this[
int index
] {get;}

Parameters

index
Zero-based index of the item.

See Also

WarningInfoCollection Class | Aspose.Words Namespace


WarningInfoCollection Methods

The methods of the WarningInfoCollection class are listed below. For a complete list of WarningInfoCollection class members, see the WarningInfoCollection Members topic.

Public Instance Methods

Clear | Removes all elements from the collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
Warning | Implements the IWarningCallback interface. Adds a warning to this collection.

See Also

WarningInfoCollection Class | Aspose.Words Namespace | WarningInfo | IWarningCallback


WarningInfoCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to read and clear a collection of warnings.

[C#]

WarningInfoCollection wic = new WarningInfoCollection();

using (IEnumerator<WarningInfo> enumerator = wic.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        WarningInfo wi = enumerator.Current;
        if (wi != null) Console.WriteLine(wi.Description);
    }

    wic.Clear();
}

See Also

WarningInfoCollection Class | Aspose.Words Namespace


WarningInfoCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of WarningInfo) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<WarningInfo> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to read and clear a collection of warnings.

[C#]

WarningInfoCollection wic = new WarningInfoCollection();

using (IEnumerator<WarningInfo> enumerator = wic.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        WarningInfo wi = enumerator.Current;
        if (wi != null) Console.WriteLine(wi.Description);
    }

    wic.Clear();
}

See Also

WarningInfoCollection Class | Aspose.Words Namespace


WarningInfoCollection.Warning Method

Implements the IWarningCallback interface. Adds a warning to this collection.

[Visual Basic]
NotOverridable Public Sub Warning( _
ByVal info As WarningInfo _
) _
Implements IWarningCallback.Warning
[C#]
public void Warning(
WarningInfo info
);

Implements

IWarningCallback.Warning

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

See Also

WarningInfoCollection Class | Aspose.Words Namespace


WarningSource Enumeration

Specifies the module that produces a warning during document loading or saving.

[Visual Basic]
Public Enum WarningSource
[C#]
public enum WarningSource

Members

Member Name | Description | Value
Unknown | The warning source is not specified. | 0
Layout | Module that builds a document layout. | 1
DrawingML | Module that renders DrawingML shapes. | 2
OfficeMath | Module that renders OfficeMath. | 3
Shapes | Module that renders ordinary shapes. | 4
Metafile | Module that renders metafiles. | 5
Xps | Module that renders XPS. | 6
Pdf | Module that renders PDF. | 7
Image | Module that renders images. | 8
Docx | Module that reads/writes DOCX files. | 9
Doc | Module that reads/writes binary DOC files. | 10
Text | Module that reads/writes plaintext files. | 11
Rtf | Module that reads/writes RTF files. | 12
WordML | Module that reads/writes WML files. | 13
Nrx | Common modules that are shared between DOCX/WML reader/writer modules. | 14
Odt | Module that reads/writes ODT files. | 15
Html | Module that reads/writes HTML/MHTML files. | 16
Validator | Module that verifies model consistency and validity. | 17
Xaml | Module that reads/writes Xaml files. | 18
Svm | Module that reads Svm files. | 19
MathML | Module that reads W3C MathML files. | 20
Font | Module that reads font files. | 21

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


WarningType Enumeration

Specifies the type of a warning that is issued by Aspose.Words during document loading or saving.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum WarningType
[C#]
public enum WarningType

Example

Shows how to implement the IWarningCallback to be notified of any font substitution during document save.

[C#]

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        // We are only interested in fonts being substituted.
        if (info.WarningType == WarningType.FontSubstitution)
        {
            Console.WriteLine("Font substitution: " + info.Description);
        }
    }

}

Members

Member Name | Description | Value
DataLossCategory | Some text/char/image or other data will be missing from either the document tree following load, or from the created document following save. | 255
DataLoss | Generic data loss, no specific code. | 1
MajorFormattingLossCategory | The resulting document or a particular location in it might look substantially different compared to the original document. | 65280
MajorFormattingLoss | Generic major formatting loss, no specific code. | 256
MinorFormattingLossCategory | The resulting document or a particular location in it might look somewhat different compared to the original document. | 16711680
MinorFormattingLoss | Generic minor formatting loss, no specific code. | 65536
FontSubstitution | Font has been substituted. | 131072
FontEmbedding | Loss of embedded font information during document saving. | 262144
UnexpectedContentCategory | Some content in the source document could not be recognized (i.e. is unsupported), this may or may not cause issues or result in data/formatting loss. | 251658240
UnexpectedContent | Generic unexpected content, no specific code. | 16777216
Hint | Advises of a potential problem or suggests an improvement. | 268435456

Requirements

Namespace: Aspose.Words

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words Namespace


Aspose.Words.BuildingBlocks

Aspose.Words

Aspose.Words.BuildingBlocks Namespace

The Aspose.Words.BuildingBlocks namespace provides classes that allow to access and use AutoText, AutoCorrect entries and Building Blocks in a document.

Namespace hierarchy

Classes

Class | Description
BuildingBlock | Represents a glossary document entry such as a Building Block, AutoText or an AutoCorrect entry.
BuildingBlockCollection | A collection of BuildingBlock objects in the document.
GlossaryDocument | Represents the root element for a glossary document within a Word document. A glossary document is a storage for AutoText, AutoCorrect entries and Building Blocks.

Enumerations

Enumeration | Description
BuildingBlockBehavior | Specifies the behavior that shall be applied to the contents of the building block when it is inserted into the main document.
BuildingBlockGallery | Specifies the predefined gallery into which a building block is classified.
BuildingBlockType | Specifies a building block type. The type might affect the visibility and behavior of the building block in Microsoft Word.


BuildingBlock Class

Represents a glossary document entry such as a Building Block, AutoText or an AutoCorrect entry.

For a list of all members of this type, see BuildingBlock Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.BuildingBlocks.BuildingBlock

[Visual Basic]
Public Class BuildingBlock
Inherits CompositeNode
[C#]
public class BuildingBlock : CompositeNode

Remarks

BuildingBlock can contain only Section nodes.

BuildingBlock can only be a child of GlossaryDocument.

You can create new building blocks and insert them into a glossary document. You can modify or delete existing building blocks. You can copy or move building blocks between documents. You can insert content of a building block into a document.

Corresponds to the docPart, docPartPr and docPartBody elements in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

Requirements

Namespace: Aspose.Words.BuildingBlocks

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BuildingBlock Members | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument


BuildingBlock Members

BuildingBlock overview

Public Instance Constructors

BuildingBlock Constructor Initializes a new instance of this class.

Public Instance Properties

Behavior | Specifies the behavior that shall be applied when the contents of the building block is inserted into the main document.
Category | Specifies the second-level categorization for the building block.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Description | Gets or sets the description associated with this building block.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstSection | Gets the first section in the building block.
Gallery | Specifies the first-level categorization for the building block for the purposes of classification or user interface sorting.
Guid | Gets or sets an identifier (a 128-bit GUID) that uniquely identifies this building block.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastSection | Gets the last section in the building block.
Name | Gets or sets the name of this building block.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns the BuildingBlock value.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Sections | Returns a collection that represents all sections in the building block.
Type | Specifies the building block type.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument


BuildingBlock Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal glossaryDoc As GlossaryDocument _
)
[C#]
public BuildingBlock(
GlossaryDocument glossaryDoc
);

Parameters

glossaryDoc
The owner document.

Remarks

When BuildingBlock is created, it belongs to the specified glossary document, but is not yet part of the glossary document and ParentNode is null.

To append BuildingBlock to a GlossaryDocument use AppendChild.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


BuildingBlock Properties

The properties of the BuildingBlock class are listed below. For a complete list of BuildingBlock class members, see the BuildingBlock Members topic.

Public Instance Properties

Behavior | Specifies the behavior that shall be applied when the contents of the building block is inserted into the main document.
Category | Specifies the second-level categorization for the building block.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Description | Gets or sets the description associated with this building block.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstSection | Gets the first section in the building block.
Gallery | Specifies the first-level categorization for the building block for the purposes of classification or user interface sorting.
Guid | Gets or sets an identifier (a 128-bit GUID) that uniquely identifies this building block.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastSection | Gets the last section in the building block.
Name | Gets or sets the name of this building block.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns the BuildingBlock value.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Sections | Returns a collection that represents all sections in the building block.
Type | Specifies the building block type.

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument


Behavior Property

Aspose.Words

BuildingBlock.Behavior Property

Specifies the behavior that shall be applied when the contents of the building block is inserted into the main document.

[Visual Basic]
Public Property Behavior As BuildingBlockBehavior
[C#]
public BuildingBlockBehavior Behavior {get; set;}

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


Category Property

Aspose.Words

BuildingBlock.Category Property

Specifies the second-level categorization for the building block.

[Visual Basic]
Public Property Category As String
[C#]
public string Category {get; set;}

Remarks

Building blocks in Microsoft Word user interface are arranged into Galleries. Each Gallery can have multiple Categories. Each block within a Category has a Name.

Cannot be null and cannot be an empty string.

Corresponds to the docPartPr.category.name element in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace | Gallery | Name


Description Property

Aspose.Words

BuildingBlock.Description Property

Gets or sets the description associated with this building block.

[Visual Basic]
Public Property Description As String
[C#]
public string Description {get; set;}

Remarks

The description may contain any string content, usually additional information.

Cannot be null, but can be an empty string.

Corresponds to the docPartPr.description element in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


FirstSection Property

Aspose.Words

BuildingBlock.FirstSection Property

Gets the first section in the building block.

[Visual Basic]
Public ReadOnly Property FirstSection As Section
[C#]
public Section FirstSection {get;}

Remarks

Returns null if there are no sections.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


Gallery Property

Aspose.Words

BuildingBlock.Gallery Property

Specifies the first-level categorization for the building block for the purposes of classification or user interface sorting.

[Visual Basic]
Public Property Gallery As BuildingBlockGallery
[C#]
public BuildingBlockGallery Gallery {get; set;}

Remarks

Building blocks in Microsoft Word user interface are arranged into Galleries. Each Gallery can have multiple Categories. Each block within a Category has a Name.

Corresponds to the docPartPr.category.gallery element in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace | Category | Name


Guid Property

Aspose.Words

BuildingBlock.Guid Property

Gets or sets an identifier (a 128-bit GUID) that uniquely identifies this building block.

[Visual Basic]
Public Property Guid As Guid
[C#]
public Guid Guid {get; set;}

Remarks

Can be used by an application to uniquely reference a building block regardless of different naming due to localization.

Corresponds to the docPartPr.guid element in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


LastSection Property

Aspose.Words

BuildingBlock.LastSection Property

Gets the last section in the building block.

[Visual Basic]
Public ReadOnly Property LastSection As Section
[C#]
public Section LastSection {get;}

Remarks

Returns null if there are no sections.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


Name Property

Aspose.Words

BuildingBlock.Name Property

Gets or sets the name of this building block.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

The name may contain any string content, usually a friendly identifier. Multiple building blocks can have the same name.

Cannot be null and cannot be an empty string.

Corresponds to the docPartPr.name element in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace | Gallery | Category


NodeType Property

Aspose.Words

BuildingBlock.NodeType Property

Returns the BuildingBlock value.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


Sections Property

Aspose.Words

BuildingBlock.Sections Property

Returns a collection that represents all sections in the building block.

[Visual Basic]
Public ReadOnly Property Sections As SectionCollection
[C#]
public SectionCollection Sections {get;}

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


Type Property

Aspose.Words

BuildingBlock.Type Property

Specifies the building block type.

[Visual Basic]
Public Property Type As BuildingBlockType
[C#]
public BuildingBlockType Type {get; set;}

Remarks

The building block type can influence the visibility and behavior of the building block in Microsoft Word.

Corresponds to the docPartPr.types element in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


BuildingBlock Methods

The methods of the BuildingBlock class are listed below. For a complete list of BuildingBlock class members, see the BuildingBlock Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument


BuildingBlock.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitBuildingBlockStart, then calls Accept for all child nodes of this building block, then calls VisitBuildingBlockEnd.

Note: A building block node and its children are not visited when you execute a Visitor over a Document. If you want to execute a Visitor over a building block, you need to execute the visitor over GlossaryDocument or call Accept.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

See Also

BuildingBlock Class | Aspose.Words.BuildingBlocks Namespace


BuildingBlockBehavior Enumeration

Specifies the behavior that shall be applied to the contents of the building block when it is inserted into the main document.

[Visual Basic]
Public Enum BuildingBlockBehavior
[C#]
public enum BuildingBlockBehavior

Remarks

Corresponds to the ST_DocPartBehavior type in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

Members

Member Name | Description | Value
Content | Specifies that the building block shall be inserted as inline content. | 0
Paragraph | Specifies that the building block shall be inserted into its own paragraph. | 1
Page | Specifies that the building block shall be added into its own page. | 2
Default | Same as Content. | 0

Requirements

Namespace: Aspose.Words.BuildingBlocks

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.BuildingBlocks Namespace | Behavior


BuildingBlockCollection Class

A collection of BuildingBlock objects in the document.

For a list of all members of this type, see BuildingBlockCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.BuildingBlocks.BuildingBlockCollection

[Visual Basic]
Public Class BuildingBlockCollection
Inherits NodeCollection
[C#]
public class BuildingBlockCollection : NodeCollection

Remarks

You do not create instances of this class directly. To access a collection of building blocks use the BuildingBlocks property.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words.BuildingBlocks

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BuildingBlockCollection Members | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument | BuildingBlocks | BuildingBlock


BuildingBlockCollection Members

BuildingBlockCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a building block at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all building blocks from the collection to a new array of building blocks.

See Also

BuildingBlockCollection Class | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument | BuildingBlocks | BuildingBlock


BuildingBlockCollection Properties

The properties of the BuildingBlockCollection class are listed below. For a complete list of BuildingBlockCollection class members, see the BuildingBlockCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a building block at the given index.

See Also

BuildingBlockCollection Class | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument | BuildingBlocks | BuildingBlock


Item Property

Aspose.Words

BuildingBlockCollection.Item Property

Retrieves a building block at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As BuildingBlock
[C#]
new public BuildingBlock this[
int index
] {get;}

Parameters

index
An index into the list of building blocks.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

BuildingBlockCollection Class | Aspose.Words.BuildingBlocks Namespace


BuildingBlockCollection Methods

The methods of the BuildingBlockCollection class are listed below. For a complete list of BuildingBlockCollection class members, see the BuildingBlockCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all building blocks from the collection to a new array of building blocks.

See Also

BuildingBlockCollection Class | Aspose.Words.BuildingBlocks Namespace | GlossaryDocument | BuildingBlocks | BuildingBlock


BuildingBlockCollection.ToArray Method

Copies all building blocks from the collection to a new array of building blocks.

[Visual Basic]
Public Function ToArray() As BuildingBlock()
[C#]
new public BuildingBlock[] ToArray();

Return Value

An array of building blocks.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

BuildingBlockCollection Class | Aspose.Words.BuildingBlocks Namespace


BuildingBlockGallery Enumeration

Specifies the predefined gallery into which a building block is classified.

[Visual Basic]
Public Enum BuildingBlockGallery
[C#]
public enum BuildingBlockGallery

Remarks

Corresponds to the ST_DocPartGallery type in OOXML.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

Members

Member Name | Description | Value
All | Specifies that this glossary document entry shall be associated with all possible gallery classification values. | 0
AutoText |  | 1
Bibliography |  | 2
CoverPage |  | 3
CustomAutoText |  | 4
CustomBibliography |  | 5
CustomCoverPage |  | 6
CustomEquations |  | 7
CustomFooters |  | 8
CustomHeaders |  | 9
Custom1 |  | 10
Custom2 |  | 11
Custom3 |  | 12
Custom4 |  | 13
Custom5 |  | 14
CustomPageNumber |  | 15
CustomPageNumberAtBottom |  | 16
CustomPageNumberAtMargin |  | 17
CustomPageNumberAtTop |  | 18
CustomQuickParts |  | 19
CustomTableOfContents |  | 20
CustomTables |  | 21
CustomTextBox |  | 22
CustomWatermarks |  | 23
NoGallery |  | 24
QuickParts |  | 25
Equations |  | 26
Footers |  | 27
Headers |  | 28
PageNumber |  | 29
PageNumberAtBottom |  | 30
PageNumberAtMargin |  | 31
PageNumberAtTop |  | 32
StructuredDocumentTagPlaceholderText |  | 33
TableOfContents |  | 34
Tables |  | 35
TextBox |  | 36
Watermarks |  | 37
Default | Same as All. | 0

Requirements

Namespace: Aspose.Words.BuildingBlocks

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.BuildingBlocks Namespace | Gallery


BuildingBlockType Enumeration

Specifies a building block type. The type might affect the visibility and behavior of the building block in Microsoft Word.

[Visual Basic]
Public Enum BuildingBlockType
[C#]
public enum BuildingBlockType

Remarks

Corresponds to the ST_DocPartType type in OOXML.

Example

Shows how to add a custom building block to a document.

[C#]

public void BuildingBlockFields()
{
    Document doc = new Document();

    // BuildingBlocks live inside the glossary document
    // If you're making a document from scratch, the glossary document must also be manually created
    GlossaryDocument glossaryDoc = new GlossaryDocument();
    doc.GlossaryDocument = glossaryDoc;

    // Create a building block and name it
    BuildingBlock block = new BuildingBlock(glossaryDoc);
    block.Name = "Custom Block";

    // Put in in the document's glossary document
    glossaryDoc.AppendChild(block);
    Assert.AreEqual(1, glossaryDoc.Count);

    // All GUIDs are this value by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

    // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
    Assert.AreEqual("(Empty Category)", block.Category);
    Assert.AreEqual(BuildingBlockType.None, block.Type);
    Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

    // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
    // All the necessary preparation will be done in a custom document visitor that we will accept
    BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
    block.Accept(visitor);

    // We can find the block we made in the glossary document like this
    BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
        "My custom building blocks", "Custom Block");

    // Our block contains one section which now contains our text
    Assert.AreEqual("Text inside " + customBlock.Name + '\f',
        customBlock.FirstSection.Body.FirstParagraph.GetText());
    Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);

    Assert.AreNotEqual("00000000-0000-0000-0000-000000000000", customBlock.Guid.ToString());
    Assert.AreEqual("My custom building blocks", customBlock.Category);
    Assert.AreEqual(BuildingBlockType.None, customBlock.Type);
    Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);
    Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior);

    // Then we can insert it into the document as a new section
    doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

    // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
    doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlock.dotx");
}

/// <summary>
/// Simple implementation of adding text to a building block and preparing it for usage in the document. Implemented as a Visitor.
/// </summary>
public class BuildingBlockVisitor : DocumentVisitor
{
    public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
    {
        mBuilder = new StringBuilder();
        mGlossaryDoc = ownerGlossaryDoc;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        // Change values by default of created BuildingBlock
        block.Behavior = BuildingBlockBehavior.Paragraph;
        block.Category = "My custom building blocks";
        block.Description =
            "Using this block in the Quick Parts section of word will place its contents at the cursor.";
        block.Gallery = BuildingBlockGallery.QuickParts;

        block.Guid = Guid.NewGuid();

        // Add content for the BuildingBlock to have an effect when used in the document
        Section section = new Section(mGlossaryDoc);
        block.AppendChild(section);

        Body body = new Body(mGlossaryDoc);
        section.AppendChild(body);

        Paragraph paragraph = new Paragraph(mGlossaryDoc);
        body.AppendChild(paragraph);

        // Add text that will be visible in the document
        Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
        block.FirstSection.Body.FirstParagraph.AppendChild(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.Append("Visited " + block.Name + "\r\n");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
    private readonly GlossaryDocument mGlossaryDoc;
}

Members

Member Name | Description | Value
None | No type information is specified for the building block. | 0
AutomaticallyReplaceNameWithContent | Allows the building block to be automatically inserted into the document whenever its name is entered into an application. | 1
StructuredDocumentTagPlaceholderText | The building block is a structured document tag placeholder text. | 2
FormFieldHelpText | The building block is a form field help text. | 3
Normal | The building block is a normal (i.e. regular) glossary document entry. | 4
AutoCorrect | The building block is associated with the spelling and grammar tools. | 5
AutoText | The building block is an AutoText entry. | 6
All | The building block is associated with all types. | 7
Default | Save as None. | 0

Requirements

Namespace: Aspose.Words.BuildingBlocks

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.BuildingBlocks Namespace | Type


GlossaryDocument Class

Represents the root element for a glossary document within a Word document. A glossary document is a storage for AutoText, AutoCorrect entries and Building Blocks.

For a list of all members of this type, see GlossaryDocument Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.DocumentBase
Aspose.Words.BuildingBlocks.GlossaryDocument

[Visual Basic]
Public Class GlossaryDocument
Inherits DocumentBase
[C#]
public class GlossaryDocument : DocumentBase

Remarks

Some documents, usually templates, can contain AutoText, AutoCorrect entries and/or Building Blocks (also known as glossary document entries, document parts or building blocks).

To access building blocks, you need to load a document into a Document object. Building blocks will be available via the GlossaryDocument property.

GlossaryDocument can contain any number of BuildingBlock objects. Each BuildingBlock represents one document part.

Corresponds to the glossaryDocument and docParts elements in OOXML.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words.BuildingBlocks

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

GlossaryDocument Members | Aspose.Words.BuildingBlocks Namespace | Document | GlossaryDocument | BuildingBlock


GlossaryDocument Members

GlossaryDocument overview

Public Instance Constructors

GlossaryDocument Constructor Initializes a new instance of the GlossaryDocument class.

Public Instance Properties

BackgroundShape (inherited from DocumentBase) | Gets or sets the background shape of the document. Can be null.
BuildingBlocks | Returns a typed collection that represents all building blocks in the glossary document.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstBuildingBlock | Gets the first building block in the glossary document.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FontInfos (inherited from DocumentBase) | Provides access to properties of fonts used in this document.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastBuildingBlock | Gets the last building block in the glossary document.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Lists (inherited from DocumentBase) | Provides access to the list formatting used in the document.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeChangingCallback (inherited from DocumentBase) | Called when a node is inserted or removed in the document.
NodeType | Returns the GlossaryDocument value.
PageColor (inherited from DocumentBase) | Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
ResourceLoadingCallback (inherited from DocumentBase) | Allows to control how external resources are loaded.
Styles (inherited from DocumentBase) | Returns a collection of styles defined in the document.
WarningCallback (inherited from DocumentBase) | Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetBuildingBlock | Finds a building block using the specified gallery, category and name.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
ImportNode (inherited from DocumentBase) | Overloaded. Imports a node from another document to the current document.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace | Document | GlossaryDocument | BuildingBlock


GlossaryDocument Constructor

Initializes a new instance of the GlossaryDocument class.

[Visual Basic]
Public Sub New()
[C#]
public GlossaryDocument();

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


GlossaryDocument Properties

The properties of the GlossaryDocument class are listed below. For a complete list of GlossaryDocument class members, see the GlossaryDocument Members topic.

Public Instance Properties

BackgroundShape (inherited from DocumentBase) | Gets or sets the background shape of the document. Can be null.
BuildingBlocks | Returns a typed collection that represents all building blocks in the glossary document.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstBuildingBlock | Gets the first building block in the glossary document.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FontInfos (inherited from DocumentBase) | Provides access to properties of fonts used in this document.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastBuildingBlock | Gets the last building block in the glossary document.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Lists (inherited from DocumentBase) | Provides access to the list formatting used in the document.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeChangingCallback (inherited from DocumentBase) | Called when a node is inserted or removed in the document.
NodeType | Returns the GlossaryDocument value.
PageColor (inherited from DocumentBase) | Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
ResourceLoadingCallback (inherited from DocumentBase) | Allows to control how external resources are loaded.
Styles (inherited from DocumentBase) | Returns a collection of styles defined in the document.
WarningCallback (inherited from DocumentBase) | Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace | Document | GlossaryDocument | BuildingBlock


BuildingBlocks Property

Aspose.Words

GlossaryDocument.BuildingBlocks Property

Returns a typed collection that represents all building blocks in the glossary document.

[Visual Basic]
Public ReadOnly Property BuildingBlocks As BuildingBlockCollection
[C#]
public BuildingBlockCollection BuildingBlocks {get;}

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


FirstBuildingBlock Property

Aspose.Words

GlossaryDocument.FirstBuildingBlock Property

Gets the first building block in the glossary document.

[Visual Basic]
Public ReadOnly Property FirstBuildingBlock As BuildingBlock
[C#]
public BuildingBlock FirstBuildingBlock {get;}

Remarks

Returns null if there are no building blocks available.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


LastBuildingBlock Property

Aspose.Words

GlossaryDocument.LastBuildingBlock Property

Gets the last building block in the glossary document.

[Visual Basic]
Public ReadOnly Property LastBuildingBlock As BuildingBlock
[C#]
public BuildingBlock LastBuildingBlock {get;}

Remarks

Returns null if there are no building blocks available.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


NodeType Property

Aspose.Words

GlossaryDocument.NodeType Property

Returns the GlossaryDocument value.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


GlossaryDocument Methods

The methods of the GlossaryDocument class are listed below. For a complete list of GlossaryDocument class members, see the GlossaryDocument Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetBuildingBlock | Finds a building block using the specified gallery, category and name.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
ImportNode (inherited from DocumentBase) | Overloaded. Imports a node from another document to the current document.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace | Document | GlossaryDocument | BuildingBlock


GlossaryDocument.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitGlossaryDocumentStart, then calls Accept for all child nodes of this node and then calls VisitGlossaryDocumentEnd at the end.

Note: A glossary document node and its children are not visited when you execute a Visitor over a Document. If you want to execute a Visitor over a glossary document, you need to call Accept.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


GlossaryDocument.GetBuildingBlock Method

Finds a building block using the specified gallery, category and name.

[Visual Basic]
Public Function GetBuildingBlock( _
ByVal gallery As BuildingBlockGallery, _
ByVal category As String, _
ByVal name As String _
) As BuildingBlock
[C#]
public BuildingBlock GetBuildingBlock(
BuildingBlockGallery gallery,
string category,
string name
);

Parameters

gallery
The gallery criteria.
category
The category criteria. Can be null, in which case it will not be used for comparison.
name
The building block name criteria.

Return Value

The matching building block or null if a match was not found.

Remarks

This is a convenience method that iterates over all building blocks in this collection and returns the first building block that matches the specified gallery, category and name.

Microsoft Word organizes building blocks into galleries. The galleries are predefined using the BuildingBlockGallery enum. Within each gallery, building blocks can be organized into one or more categories. The category name is a string. Each building block has a name. A building block name is not guaranteed to be unique.

Example

Shows how to use GlossaryDocument and BuildingBlockCollection.

[C#]

public void GlossaryDocument()
{
    Document doc = new Document();

    GlossaryDocument glossaryDoc = new GlossaryDocument();
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 1" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 2" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 3" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 4" });
    glossaryDoc.AppendChild(new BuildingBlock(glossaryDoc) { Name = "Block 5" });

    Assert.AreEqual(5, glossaryDoc.BuildingBlocks.Count);

    doc.GlossaryDocument = glossaryDoc;

    // There is a different ways how to get created building blocks
    Assert.AreEqual("Block 1", glossaryDoc.FirstBuildingBlock.Name);
    Assert.AreEqual("Block 2", glossaryDoc.BuildingBlocks[1].Name);
    Assert.AreEqual("Block 3", glossaryDoc.BuildingBlocks.ToArray()[2].Name);
    Assert.AreEqual("Block 5", glossaryDoc.LastBuildingBlock.Name);

    // Get a block by gallery, category and name
    BuildingBlock block4 =
        glossaryDoc.GetBuildingBlock(BuildingBlockGallery.All, "(Empty Category)", "Block 4");

    // All GUIDs are the same by default
    Assert.AreEqual("00000000-0000-0000-0000-000000000000", block4.Guid.ToString());

    // To be able to uniquely identify blocks by GUID, each GUID must be unique
    // We will do that using a custom visitor
    GlossaryDocVisitor visitor = new GlossaryDocVisitor();
    glossaryDoc.Accept(visitor);

    Assert.AreEqual(5, visitor.GetDictionary().Count);

    Console.WriteLine(visitor.GetText());

    // We can find our new blocks in Microsoft Word via Insert > Quick Parts > Building Blocks Organizer...
    doc.Save(ArtifactsDir + "BuildingBlocks.GlossaryDocument.dotx");
}

/// <summary>
/// Simple implementation of giving each building block in a glossary document a unique GUID. Implemented as a Visitor.
/// </summary>
public class GlossaryDocVisitor : DocumentVisitor
{
    public GlossaryDocVisitor()
    {
        mBlocksByGuid = new Dictionary<Guid, BuildingBlock>();
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public Dictionary<Guid, BuildingBlock> GetDictionary()
    {
        return mBlocksByGuid;
    }

    public override VisitorAction VisitGlossaryDocumentStart(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Glossary documnent found!");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGlossaryDocumentEnd(GlossaryDocument glossary)
    {
        mBuilder.AppendLine("Reached end of glossary!");
        mBuilder.AppendLine("BuildingBlocks found: " + mBlocksByGuid.Count);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
    {
        block.Guid = Guid.NewGuid();
        mBlocksByGuid.Add(block.Guid, block);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
    {
        mBuilder.AppendLine("\tVisited block \"" + block.Name + "\"");
        mBuilder.AppendLine("\t Type: " + block.Type);
        mBuilder.AppendLine("\t Gallery: " + block.Gallery);
        mBuilder.AppendLine("\t Behavior: " + block.Behavior);
        mBuilder.AppendLine("\t Description: " + block.Description);

        return VisitorAction.Continue;
    }

    private readonly Dictionary<Guid, BuildingBlock> mBlocksByGuid;
    private readonly StringBuilder mBuilder;
}

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


Aspose.Words.Drawing

Aspose.Words

Aspose.Words.Drawing Namespace

The Aspose.Words.Drawing namespace provides classes that allow to create and modify drawing objects.

All drawing objects in in Microsoft Word documents are represented by instances of the Shape and GroupShape classes. An object of the Shape class is a node in a document and can represent a picture, textbox, AutoShape or an OLE object.

The classes in this namespace support the latest (Word 2007 - 2013 DrawingML) and the earlier (pre Word 2007 - Office Art) shapes.

Namespace hierarchy

Classes

Class | Description
Fill | Defines a fill for a shape.
GroupShape | Represents a group of shapes in a document.
ImageData | Defines an image for a shape.
ImageSize | Contains information about image size and resolution.
OleFormat | Provides access to the data of an OLE object or ActiveX control.
OlePackage | Allows to access OLE Package properties.
Shape | Represents an object in the drawing layer, such as an AutoShape, textbox, freeform, OLE object, ActiveX control, or picture.
ShapeBase | Base class for objects in the drawing layer, such as an AutoShape, freeform, OLE object, ActiveX control, or picture.
SignatureLine | Provides access to signature line properties.
Stroke | Defines a stroke for a shape.
TextBox | Defines attributes that specify how a text is displayed inside a shape.
TextPath | Defines the text and formatting of the text path (of a WordArt object).

Enumerations

Enumeration | Description
ArrowLength | Length of the arrow at the end of a line.
ArrowType | Specifies the type of an arrow at a line end.
ArrowWidth | Width of the arrow at the end of a line.
DashStyle | Dashed line style.
EndCap | Specifies line cap style.
FlipOrientation | Possible values for the orientation of a shape.
HorizontalAlignment | Specifies horizontal alignment of a floating shape, text frame or floating table.
ImageType | Specifies the type (format) of an image in a Microsoft Word document.
JoinStyle | Line join style.
LayoutFlow | Determines the flow of the text layout in a textbox.
RelativeHorizontalPosition | Specifies to what the horizontal position of a shape or text frame is relative.
RelativeVerticalPosition | Specifies to what the vertical position of a shape or text frame is relative.
ShapeLineStyle | Specifies the compound line style of a Shape.
ShapeMarkupLanguage | Specifies Markup language used for the shape.
ShapeType | Specifies the type of shape in a Microsoft Word document.
TextBoxAnchor | Specifies values used for shape text vertical alignment.
TextBoxWrapMode | Specifies how text wraps inside a shape.
TextPathAlignment | WordArt alignment.
VerticalAlignment | Specifies vertical alignment of a floating shape, text frame or a floating table.
WrapSide | Specifies what side(s) of the shape or picture the text wraps around.
WrapType | Specifies how text is wrapped around a shape or picture.


ArrowLength Enumeration

Length of the arrow at the end of a line.

[Visual Basic]
Public Enum ArrowLength
[C#]
public enum ArrowLength

Remarks

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

Members

Member Name | Description | Value
Short |  | 0
Medium |  | 1
Long |  | 2
Default | Same as Short. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | StartArrowLength | EndArrowLength


ArrowType Enumeration

Specifies the type of an arrow at a line end.

[Visual Basic]
Public Enum ArrowType
[C#]
public enum ArrowType

Remarks

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

Members

Member Name | Description | Value
None | The line does not have an arrow at the end. | 0
Arrow | The arrow is a solid triangle. | 1
Stealth | The arrow is a "stealth" arrow. | 2
Diamond | The line end is a solid diamond. | 3
Oval | The line end is a solid oval. | 4
Open | The arrow is an open arrow. | 5
Default | Same as None. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | StartArrowType | EndArrowType


ArrowWidth Enumeration

Width of the arrow at the end of a line.

[Visual Basic]
Public Enum ArrowWidth
[C#]
public enum ArrowWidth

Remarks

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

Members

Member Name | Description | Value
Narrow |  | 0
Medium |  | 1
Wide |  | 2
Default | Same as Narrow. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | StartArrowWidth | EndArrowWidth


DashStyle Enumeration

Dashed line style.

[Visual Basic]
Public Enum DashStyle
[C#]
public enum DashStyle

Remarks

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

Members

Member Name | Description | Value
Solid | Solid (continuous) pen. | 0
ShortDash | System dash style. | 1
ShortDot | System dash style. | 2
ShortDashDot | System dash style. | 3
ShortDashDotDot | System dash style. | 4
Dot | Square dot style. | 5
Dash | Dash style. | 6
LongDash | Long dash style. | 7
DashDot | Dash short dash. | 8
LongDashDot | Long dash short dash. | 9
LongDashDotDot | Long dash short dash short dash. | 10
Default | Same as Solid. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | DashStyle


EndCap Enumeration

Specifies line cap style.

[Visual Basic]
Public Enum EndCap
[C#]
public enum EndCap

Remarks

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

Members

Member Name | Description | Value
Round | Rounded ends. | 0
Square | Square protrudes by half line width. | 1
Flat | Line ends at end point. | 2
Default | Default value is Flat. | 2

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | EndCap


Fill Class

Defines a fill for a shape.

For a list of all members of this type, see Fill Members.

System.Object
Aspose.Words.Drawing.Fill

[Visual Basic]
Public Class Fill
[C#]
public class Fill

Remarks

Use the Fill property to access fill properties of a shape. You do not create instances of the Fill class directly.

Although the Fill class provides properties to specify solid color fill only, all of the more complex fill types, including as gradient, pattern and texture are fully preserved during document open-save cycles.

Example

Demonstrates how to create shapes with fill.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln();
builder.Writeln();
builder.Writeln();
builder.Write("Some text under the shape.");

// Create a red balloon, semitransparent.
// The shape is floating and its coordinates are (0,0) by default, relative to the current paragraph.
Shape shape = new Shape(builder.Document, ShapeType.Balloon);
shape.FillColor = Color.Red;
shape.Fill.Opacity = 0.3;
shape.Width = 100;
shape.Height = 100;
shape.Top = -100;
builder.InsertNode(shape);

builder.Document.Save(ArtifactsDir + "Shape.Fill.doc");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Fill Members | Aspose.Words.Drawing Namespace | Fill


Fill Members

Fill overview

Public Instance Properties

Color | Defines the color of a fill.
ImageBytes | Gets the raw bytes of the fill texture or pattern.
On | Determines whether the shape will be filled.
Opacity | Defines the transparency of a fill. Valid range from 0 to 1, where 0 is fully transparent and 1 is fully opaque.

See Also

Fill Class | Aspose.Words.Drawing Namespace | Fill


Fill Properties

The properties of the Fill class are listed below. For a complete list of Fill class members, see the Fill Members topic.

Public Instance Properties

Color | Defines the color of a fill.
ImageBytes | Gets the raw bytes of the fill texture or pattern.
On | Determines whether the shape will be filled.
Opacity | Defines the transparency of a fill. Valid range from 0 to 1, where 0 is fully transparent and 1 is fully opaque.

See Also

Fill Class | Aspose.Words.Drawing Namespace | Fill


Color Property

Aspose.Words

Fill.Color Property

Defines the color of a fill.

[Visual Basic]
Public Property Color As Color
[C#]
public Color Color {get; set;}

Remarks

The default value is White.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Fill Class | Aspose.Words.Drawing Namespace


ImageBytes Property

Aspose.Words

Fill.ImageBytes Property

Gets the raw bytes of the fill texture or pattern.

[Visual Basic]
Public ReadOnly Property ImageBytes As Byte()
[C#]
public byte[] ImageBytes {get;}

Remarks

The default value is null.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Fill Class | Aspose.Words.Drawing Namespace


On Property

Aspose.Words

Fill.On Property

Determines whether the shape will be filled.

[Visual Basic]
Public Property On As Boolean
[C#]
public bool On {get; set;}

Remarks

The default value is true.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Fill Class | Aspose.Words.Drawing Namespace


Opacity Property

Aspose.Words

Fill.Opacity Property

Defines the transparency of a fill. Valid range from 0 to 1, where 0 is fully transparent and 1 is fully opaque.

[Visual Basic]
Public Property Opacity As Double
[C#]
public double Opacity {get; set;}

Remarks

The default value is 1.

Example

Demonstrates how to create shapes with fill.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln();
builder.Writeln();
builder.Writeln();
builder.Write("Some text under the shape.");

// Create a red balloon, semitransparent.
// The shape is floating and its coordinates are (0,0) by default, relative to the current paragraph.
Shape shape = new Shape(builder.Document, ShapeType.Balloon);
shape.FillColor = Color.Red;
shape.Fill.Opacity = 0.3;
shape.Width = 100;
shape.Height = 100;
shape.Top = -100;
builder.InsertNode(shape);

builder.Document.Save(ArtifactsDir + "Shape.Fill.doc");

See Also

Fill Class | Aspose.Words.Drawing Namespace


FlipOrientation Enumeration

Possible values for the orientation of a shape.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum FlipOrientation
[C#]
public enum FlipOrientation

Remarks

Example

Shows how to create line shapes and set specific location and size.

[C#]

Document doc = new Document();

// The lines will cross the whole page.
float pageWidth = (float) doc.FirstSection.PageSetup.PageWidth;
float pageHeight = (float) doc.FirstSection.PageSetup.PageHeight;

// This line goes from top left to bottom right by default.
Shape lineA = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineA.BoundsInPoints);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    FlipOrientation = FlipOrientation.Horizontal,
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineB.BoundsInPoints);

// Add lines to the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(ArtifactsDir + "Shape.LineFlipOrientation.doc");

Members

Member Name | Description | Value
None | Coordinates are not flipped. | 0
Horizontal | Flip along the y-axis, reversing the x-coordinates. | 1
Vertical | Flip along the x-axis, reversing the y-coordinates. | 2
Both | Flip along both the y- and x-axis. | 3

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | FlipOrientation


GroupShape Class

Represents a group of shapes in a document.

For a list of all members of this type, see GroupShape Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Drawing.ShapeBase
Aspose.Words.Drawing.GroupShape

[Visual Basic]
Public Class GroupShape
Inherits ShapeBase
[C#]
public class GroupShape : ShapeBase

Remarks

A GroupShape is a composite node and can have Shape and GroupShape nodes as children.

Each GroupShape defines a new coordinate system for its child shapes. The coordinate system is defined using the CoordSize and CoordOrigin properties.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

GroupShape Members | Aspose.Words.Drawing Namespace | ShapeBase | Shape


GroupShape Members

GroupShape overview

Public Instance Constructors

GroupShape Constructor Creates a new group shape.

Public Instance Properties

AllowOverlap (inherited from ShapeBase) | Gets or sets a value that specifies whether this shape can overlap other shapes.
AlternativeText (inherited from ShapeBase) | Defines alternative text to be displayed instead of a graphic.
AnchorLocked (inherited from ShapeBase) | Specifies whether the shape's anchor is locked.
AspectRatioLocked (inherited from ShapeBase) | Specifies whether the shape's aspect ratio is locked.
BehindText (inherited from ShapeBase) | Specifies whether the shape is below or above text.
Bottom (inherited from ShapeBase) | Gets the position of the bottom edge of the containing block of the shape.
Bounds (inherited from ShapeBase) | Gets or sets the location and size of the containing block of the shape.
BoundsInPoints (inherited from ShapeBase) | Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.
BoundsWithEffects (inherited from ShapeBase) | Gets final extent that this shape object has after applying drawing effects. Value is measured in points.
CanHaveImage (inherited from ShapeBase) | Returns true if the shape type allows the shape to have an image.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CoordOrigin (inherited from ShapeBase) | The coordinates at the top-left corner of the containing block of this shape.
CoordSize (inherited from ShapeBase) | The width and height of the coordinate space inside the containing block of this shape.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DistanceBottom (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the bottom edge of the shape.
DistanceLeft (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the left edge of the shape.
DistanceRight (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the right edge of the shape.
DistanceTop (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the top edge of the shape.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FlipOrientation (inherited from ShapeBase) | Switches the orientation of a shape.
Font (inherited from ShapeBase) | Provides access to the font formatting of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Height (inherited from ShapeBase) | Gets or sets the height of the containing block of the shape.
HorizontalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned horizontally.
HRef (inherited from ShapeBase) | Gets or sets the full hyperlink address for a shape.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from ShapeBase) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsGroup (inherited from ShapeBase) | Returns true if this is a group shape.
IsHorizontalRule (inherited from ShapeBase) | Returns true if this shape is a horizontal rule.
IsImage (inherited from ShapeBase) | Returns true if this shape is an image shape.
IsInline (inherited from ShapeBase) | A quick way to determine if this shape is positioned inline with text.
IsInsertRevision (inherited from ShapeBase) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLayoutInCell (inherited from ShapeBase) | Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.
IsMoveFromRevision (inherited from ShapeBase) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from ShapeBase) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
IsSignatureLine (inherited from ShapeBase) | Indicates that shape is a SignatureLine.
IsTopLevel (inherited from ShapeBase) | Returns true if this shape is not a child of a group shape.
IsWordArt (inherited from ShapeBase) | Returns true if this shape is a WordArt object.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Left (inherited from ShapeBase) | Gets or sets the position of the left edge of the containing block of the shape.
MarkupLanguage (inherited from ShapeBase) | Gets MarkupLanguage used for this graphic object.
Name (inherited from ShapeBase) | Gets or sets the optional shape name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns GroupShape.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from ShapeBase) | Returns the immediate parent paragraph.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned horizontally.
RelativeVerticalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned vertically.
Right (inherited from ShapeBase) | Gets the position of the right edge of the containing block of the shape.
Rotation (inherited from ShapeBase) | Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.
ScreenTip (inherited from ShapeBase) | Defines the text displayed when the mouse pointer moves over the shape.
ShapeType (inherited from ShapeBase) | Gets the shape type.
SizeInPoints (inherited from ShapeBase) | Gets the size of the shape in points.
Target (inherited from ShapeBase) | Gets or sets the target frame for the shape hyperlink.
Title (inherited from ShapeBase) | Gets or sets the title (caption) of the current shape object.
Top (inherited from ShapeBase) | Gets or sets the position of the top edge of the containing block of the shape.
VerticalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned vertically.
Width (inherited from ShapeBase) | Gets or sets the width of the containing block of the shape.
WrapSide (inherited from ShapeBase) | Specifies how the text is wrapped around the shape.
WrapType (inherited from ShapeBase) | Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.
ZOrder (inherited from ShapeBase) | Determines the display order of overlapping shapes.

Public Instance Methods

Accept | Accepts a visitor.
AdjustWithEffects (inherited from ShapeBase) | Adds to the source rectangle values of the effect extent and returns the final rectangle.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetShapeRenderer (inherited from ShapeBase) | Creates and returns an object that can be used to render this shape into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
LocalToParent (inherited from ShapeBase) | Converts a value from the local coordinate space into the coordinate space of the parent shape.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

GroupShape Class | Aspose.Words.Drawing Namespace | ShapeBase | Shape


GroupShape Constructor

Creates a new group shape.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public GroupShape(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

By default, the shape is floating and has default location and size.

You should specify desired shape properties after you created a shape.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

GroupShape Class | Aspose.Words.Drawing Namespace


GroupShape Properties

The properties of the GroupShape class are listed below. For a complete list of GroupShape class members, see the GroupShape Members topic.

Public Instance Properties

AllowOverlap (inherited from ShapeBase) | Gets or sets a value that specifies whether this shape can overlap other shapes.
AlternativeText (inherited from ShapeBase) | Defines alternative text to be displayed instead of a graphic.
AnchorLocked (inherited from ShapeBase) | Specifies whether the shape's anchor is locked.
AspectRatioLocked (inherited from ShapeBase) | Specifies whether the shape's aspect ratio is locked.
BehindText (inherited from ShapeBase) | Specifies whether the shape is below or above text.
Bottom (inherited from ShapeBase) | Gets the position of the bottom edge of the containing block of the shape.
Bounds (inherited from ShapeBase) | Gets or sets the location and size of the containing block of the shape.
BoundsInPoints (inherited from ShapeBase) | Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.
BoundsWithEffects (inherited from ShapeBase) | Gets final extent that this shape object has after applying drawing effects. Value is measured in points.
CanHaveImage (inherited from ShapeBase) | Returns true if the shape type allows the shape to have an image.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CoordOrigin (inherited from ShapeBase) | The coordinates at the top-left corner of the containing block of this shape.
CoordSize (inherited from ShapeBase) | The width and height of the coordinate space inside the containing block of this shape.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DistanceBottom (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the bottom edge of the shape.
DistanceLeft (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the left edge of the shape.
DistanceRight (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the right edge of the shape.
DistanceTop (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the top edge of the shape.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FlipOrientation (inherited from ShapeBase) | Switches the orientation of a shape.
Font (inherited from ShapeBase) | Provides access to the font formatting of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Height (inherited from ShapeBase) | Gets or sets the height of the containing block of the shape.
HorizontalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned horizontally.
HRef (inherited from ShapeBase) | Gets or sets the full hyperlink address for a shape.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from ShapeBase) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsGroup (inherited from ShapeBase) | Returns true if this is a group shape.
IsHorizontalRule (inherited from ShapeBase) | Returns true if this shape is a horizontal rule.
IsImage (inherited from ShapeBase) | Returns true if this shape is an image shape.
IsInline (inherited from ShapeBase) | A quick way to determine if this shape is positioned inline with text.
IsInsertRevision (inherited from ShapeBase) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLayoutInCell (inherited from ShapeBase) | Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.
IsMoveFromRevision (inherited from ShapeBase) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from ShapeBase) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
IsSignatureLine (inherited from ShapeBase) | Indicates that shape is a SignatureLine.
IsTopLevel (inherited from ShapeBase) | Returns true if this shape is not a child of a group shape.
IsWordArt (inherited from ShapeBase) | Returns true if this shape is a WordArt object.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Left (inherited from ShapeBase) | Gets or sets the position of the left edge of the containing block of the shape.
MarkupLanguage (inherited from ShapeBase) | Gets MarkupLanguage used for this graphic object.
Name (inherited from ShapeBase) | Gets or sets the optional shape name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns GroupShape.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from ShapeBase) | Returns the immediate parent paragraph.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned horizontally.
RelativeVerticalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned vertically.
Right (inherited from ShapeBase) | Gets the position of the right edge of the containing block of the shape.
Rotation (inherited from ShapeBase) | Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.
ScreenTip (inherited from ShapeBase) | Defines the text displayed when the mouse pointer moves over the shape.
ShapeType (inherited from ShapeBase) | Gets the shape type.
SizeInPoints (inherited from ShapeBase) | Gets the size of the shape in points.
Target (inherited from ShapeBase) | Gets or sets the target frame for the shape hyperlink.
Title (inherited from ShapeBase) | Gets or sets the title (caption) of the current shape object.
Top (inherited from ShapeBase) | Gets or sets the position of the top edge of the containing block of the shape.
VerticalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned vertically.
Width (inherited from ShapeBase) | Gets or sets the width of the containing block of the shape.
WrapSide (inherited from ShapeBase) | Specifies how the text is wrapped around the shape.
WrapType (inherited from ShapeBase) | Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.
ZOrder (inherited from ShapeBase) | Determines the display order of overlapping shapes.

See Also

GroupShape Class | Aspose.Words.Drawing Namespace | ShapeBase | Shape


NodeType Property

Aspose.Words

GroupShape.NodeType Property

Returns GroupShape.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

GroupShape Class | Aspose.Words.Drawing Namespace


GroupShape Methods

The methods of the GroupShape class are listed below. For a complete list of GroupShape class members, see the GroupShape Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AdjustWithEffects (inherited from ShapeBase) | Adds to the source rectangle values of the effect extent and returns the final rectangle.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetShapeRenderer (inherited from ShapeBase) | Creates and returns an object that can be used to render this shape into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
LocalToParent (inherited from ShapeBase) | Converts a value from the local coordinate space into the coordinate space of the parent shape.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

GroupShape Class | Aspose.Words.Drawing Namespace | ShapeBase | Shape


GroupShape.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitGroupShapeStart, then calls Accept for all child shapes of this group shape and calls VisitGroupShapeEnd at the end.

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

GroupShape Class | Aspose.Words.Drawing Namespace


HorizontalAlignment Enumeration

Specifies horizontal alignment of a floating shape, text frame or floating table.

[Visual Basic]
Public Enum HorizontalAlignment
[C#]
public enum HorizontalAlignment

Remarks

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

Members

Member Name | Description | Value
None | The object is explicitly positioned, usually using its Left property. | 0
Default | Same as None. | 0
Left | Specifies that the object shall be left aligned to the horizontal alignment base. | 1
Center | Specifies that the object shall be centered with respect to the horizontal alignment base. | 2
Right | Specifies that the object shall be right aligned to the horizontal alignment base. | 3
Inside | Specifies that the object shall be inside of the horizontal alignment base. | 4
Outside | Specifies that the object shall be outside of the horizontal alignment base. | 5

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | HorizontalAlignment


ImageData Class

Defines an image for a shape.

For a list of all members of this type, see ImageData Members.

System.Object
Aspose.Words.Drawing.ImageData

[Visual Basic]
Public Class ImageData
[C#]
public class ImageData

Remarks

Use the ImageData property to access and modify the image inside a shape. You do not create instances of the ImageData class directly.

An image can be stored inside a shape, linked to external file or both (linked and stored in the document).

Regardless of whether the image is stored inside the shape or linked, you can always access the actual image using the ToByteArray, ToStream, ToImage or Save methods. If the image is stored inside the shape, you can also directly access it using the ImageBytes property.

To store an image inside a shape use the SetImage method. To link an image to a shape, set the SourceFullName property.

Example

Shows how to extract images from a document and save them as files.

[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}
Shows how to insert a linked image into a document.
[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "Images/Hammer.wmf";

builder.Write("Image linked, not stored in the document: ");

Shape linkedOnly = new Shape(builder.Document, ShapeType.Image);
linkedOnly.WrapType = WrapType.Inline;
linkedOnly.ImageData.SourceFullName = imageFileName;

builder.InsertNode(linkedOnly);
builder.Writeln();

builder.Write("Image linked and stored in the document: ");

Shape linkedAndStored = new Shape(builder.Document, ShapeType.Image);
linkedAndStored.WrapType = WrapType.Inline;
linkedAndStored.ImageData.SourceFullName = imageFileName;
linkedAndStored.ImageData.SetImage(imageFileName);

builder.InsertNode(linkedAndStored);
builder.Writeln();

builder.Write("Image stored in the document, but not linked: ");

Shape stored = new Shape(builder.Document, ShapeType.Image);
stored.WrapType = WrapType.Inline;
stored.ImageData.SetImage(imageFileName);

builder.InsertNode(stored);
builder.Writeln();

builder.Document.Save(ArtifactsDir + "Image.CreateLinkedImage.doc");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ImageData Members | Aspose.Words.Drawing Namespace


ImageData Members

ImageData overview

Public Instance Properties

BiLevel | Determines whether an image will be displayed in black and white.
Borders | Gets the collection of borders of the image. Borders only have effect for inline images.
Brightness | Gets or sets the brightness of the picture. The value for this property must be a number from 0.0 (dimmest) to 1.0 (brightest).
ChromaKey | Defines the color value of the image that will be treated as transparent.
Contrast | Gets or sets the contrast for the specified picture. The value for this property must be a number from 0.0 (the least contrast) to 1.0 (the greatest contrast).
CropBottom | Defines the fraction of picture removal from the bottom side.
CropLeft | Defines the fraction of picture removal from the left side.
CropRight | Defines the fraction of picture removal from the right side.
CropTop | Defines the fraction of picture removal from the top side.
GrayScale | Determines whether a picture will display in grayscale mode.
HasImage | Returns true if the shape has image bytes or links an image.
ImageBytes | Gets or sets the raw bytes of the image stored in the shape.
ImageSize | Gets the information about image size and resolution.
ImageType | Gets the type of the image.
IsLink | Returns true if the image is linked to the shape (when SourceFullName is specified).
IsLinkOnly | Returns true if the image is linked and not stored in the document.
SourceFullName | Gets or sets the path and name of the source file for the linked image.
Title | Defines the title of an image.

Public Instance Methods

Save | Overloaded. Saves the image of the shape.
SetImage | Overloaded. Sets the image that the shape displays.
ToByteArray | Returns image bytes for any image regardless whether the image is stored or linked.
ToImage | Gets the image stored in the shape as a Image object.
ToStream | Creates and returns a stream that contains the image bytes.

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageData Properties

The properties of the ImageData class are listed below. For a complete list of ImageData class members, see the ImageData Members topic.

Public Instance Properties

BiLevel | Determines whether an image will be displayed in black and white.
Borders | Gets the collection of borders of the image. Borders only have effect for inline images.
Brightness | Gets or sets the brightness of the picture. The value for this property must be a number from 0.0 (dimmest) to 1.0 (brightest).
ChromaKey | Defines the color value of the image that will be treated as transparent.
Contrast | Gets or sets the contrast for the specified picture. The value for this property must be a number from 0.0 (the least contrast) to 1.0 (the greatest contrast).
CropBottom | Defines the fraction of picture removal from the bottom side.
CropLeft | Defines the fraction of picture removal from the left side.
CropRight | Defines the fraction of picture removal from the right side.
CropTop | Defines the fraction of picture removal from the top side.
GrayScale | Determines whether a picture will display in grayscale mode.
HasImage | Returns true if the shape has image bytes or links an image.
ImageBytes | Gets or sets the raw bytes of the image stored in the shape.
ImageSize | Gets the information about image size and resolution.
ImageType | Gets the type of the image.
IsLink | Returns true if the image is linked to the shape (when SourceFullName is specified).
IsLinkOnly | Returns true if the image is linked and not stored in the document.
SourceFullName | Gets or sets the path and name of the source file for the linked image.
Title | Defines the title of an image.

See Also

ImageData Class | Aspose.Words.Drawing Namespace


BiLevel Property

Aspose.Words

ImageData.BiLevel Property

Determines whether an image will be displayed in black and white.

[Visual Basic]
Public Property BiLevel As Boolean
[C#]
public bool BiLevel {get; set;}

Remarks

The default value is false.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


Borders Property

Aspose.Words

ImageData.Borders Property

Gets the collection of borders of the image. Borders only have effect for inline images.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


Brightness Property

Aspose.Words

ImageData.Brightness Property

Gets or sets the brightness of the picture. The value for this property must be a number from 0.0 (dimmest) to 1.0 (brightest).

[Visual Basic]
Public Property Brightness As Double
[C#]
public double Brightness {get; set;}

Remarks

The default value is 0.5.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ChromaKey Property

Aspose.Words

ImageData.ChromaKey Property

Defines the color value of the image that will be treated as transparent.

[Visual Basic]
Public Property ChromaKey As Color
[C#]
public Color ChromaKey {get; set;}

Remarks

The default value is 0.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


Contrast Property

Aspose.Words

ImageData.Contrast Property

Gets or sets the contrast for the specified picture. The value for this property must be a number from 0.0 (the least contrast) to 1.0 (the greatest contrast).

[Visual Basic]
Public Property Contrast As Double
[C#]
public double Contrast {get; set;}

Remarks

The default value is 0.5.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


CropBottom Property

Aspose.Words

ImageData.CropBottom Property

Defines the fraction of picture removal from the bottom side.

[Visual Basic]
Public Property CropBottom As Double
[C#]
public double CropBottom {get; set;}

Remarks

The amount of cropping can range from -1.0 to 1.0. The default value is 0. Note that a value of 1 will display no picture at all. Negative values will result in the picture being squeezed inward from the edge being cropped (the empty space between the picture and the cropped edge will be filled by the fill color of the shape). Positive values less than 1 will result in the remaining picture being stretched to fit the shape.

The default value is 0.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


CropLeft Property

Aspose.Words

ImageData.CropLeft Property

Defines the fraction of picture removal from the left side.

[Visual Basic]
Public Property CropLeft As Double
[C#]
public double CropLeft {get; set;}

Remarks

The amount of cropping can range from -1.0 to 1.0. The default value is 0. Note that a value of 1 will display no picture at all. Negative values will result in the picture being squeezed inward from the edge being cropped (the empty space between the picture and the cropped edge will be filled by the fill color of the shape). Positive values less than 1 will result in the remaining picture being stretched to fit the shape.

The default value is 0.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


CropRight Property

Aspose.Words

ImageData.CropRight Property

Defines the fraction of picture removal from the right side.

[Visual Basic]
Public Property CropRight As Double
[C#]
public double CropRight {get; set;}

Remarks

The amount of cropping can range from -1.0 to 1.0. The default value is 0. Note that a value of 1 will display no picture at all. Negative values will result in the picture being squeezed inward from the edge being cropped (the empty space between the picture and the cropped edge will be filled by the fill color of the shape). Positive values less than 1 will result in the remaining picture being stretched to fit the shape.

The default value is 0.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


CropTop Property

Aspose.Words

ImageData.CropTop Property

Defines the fraction of picture removal from the top side.

[Visual Basic]
Public Property CropTop As Double
[C#]
public double CropTop {get; set;}

Remarks

The amount of cropping can range from -1.0 to 1.0. The default value is 0. Note that a value of 1 will display no picture at all. Negative values will result in the picture being squeezed inward from the edge being cropped (the empty space between the picture and the cropped edge will be filled by the fill color of the shape). Positive values less than 1 will result in the remaining picture being stretched to fit the shape.

The default value is 0.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


GrayScale Property

Aspose.Words

ImageData.GrayScale Property

Determines whether a picture will display in grayscale mode.

[Visual Basic]
Public Property GrayScale As Boolean
[C#]
public bool GrayScale {get; set;}

Remarks

The default value is false.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


HasImage Property

Aspose.Words

ImageData.HasImage Property

Returns true if the shape has image bytes or links an image.

[Visual Basic]
Public ReadOnly Property HasImage As Boolean
[C#]
public bool HasImage {get;}

Property Value

Example

Shows how to save all the images from a document to the file system.

[C#]

Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

// Images are stored as shapes
// Get into the document's shape collection to verify that it contains 6 images
List<Shape> shapes = imgSourceDoc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(6, shapes.Count);

// We will use an ImageFormatConverter to determine an image's file extension
ImageFormatConverter formatConverter = new ImageFormatConverter();

// Go over all of the document's shapes
// If a shape contains image data, save the image in the local file system
for (int i = 0; i < shapes.Count; i++)
{
    ImageData imageData = shapes[i].ImageData;

    if (imageData.HasImage)
    {
        ImageFormat format = imageData.ToImage().RawFormat;
        string fileExtension = formatConverter.ConvertToString(format);

        using (FileStream fileStream = File.Create(ArtifactsDir + $"Image from shape {i}.{fileExtension}"))
        {
            imageData.Save(fileStream);
        }
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageBytes Property

Aspose.Words

ImageData.ImageBytes Property

Gets or sets the raw bytes of the image stored in the shape.

[Visual Basic]
Public Property ImageBytes As Byte()
[C#]
public byte[] ImageBytes {get; set;}

Remarks

Setting the value to null or an empty array will remove the image from the shape.

Returns null if the image is not stored in the document (e.g the image is probably linked in this case).

Example

Shows how to access raw image data in a shape's ImageData object.

[C#]

Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

// Images are stored as shapes
// Get into the document's shape collection to verify that it contains 6 images
List<Shape> shapes = imgSourceDoc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(6, shapes.Count);

// ToByteArray() returns the value of the ImageBytes property
Assert.AreEqual(shapes[0].ImageData.ImageBytes, shapes[0].ImageData.ToByteArray());

// Put the shape's image data into a stream
// Then, put the image data from that stream into another stream which creates an image file in the local file system
using (Stream imgStream = shapes[0].ImageData.ToStream())
{
    using (FileStream outStream = new FileStream(ArtifactsDir + "MyImg.png", FileMode.CreateNew))
    {
        imgStream.CopyTo(outStream);
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace | SetImage | ToByteArray | ToImage | ToStream | Save


ImageSize Property

Aspose.Words

ImageData.ImageSize Property

Gets the information about image size and resolution.

[Visual Basic]
Public ReadOnly Property ImageSize As ImageSize
[C#]
public ImageSize ImageSize {get;}

Property Value

Remarks

If the image is linked only and not stored in the document, returns zero size.

Example

Shows how to resize an image shape.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inserted at 100% scale.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// It is easy to change the shape size. In this case, make it 50% relative to the current shape size.
shape.Width = shape.Width * 0.5;
shape.Height = shape.Height * 0.5;

// However, we can also go back to the original image size and scale from there, say 110%.
ImageSize imageSize = shape.ImageData.ImageSize;
shape.Width = imageSize.WidthPoints * 1.1;
shape.Height = imageSize.HeightPoints * 1.1;

builder.Document.Save(ArtifactsDir + "Image.ScaleImage.doc");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageType Property

Aspose.Words

ImageData.ImageType Property

Gets the type of the image.

[Visual Basic]
Public ReadOnly Property ImageType As ImageType
[C#]
public ImageType ImageType {get;}

Property Value

Example

Shows how to extract images from a document and save them as files.

[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace


IsLink Property

Aspose.Words

ImageData.IsLink Property

Returns true if the image is linked to the shape (when SourceFullName is specified).

[Visual Basic]
Public ReadOnly Property IsLink As Boolean
[C#]
public bool IsLink {get;}

Property Value

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


IsLinkOnly Property

Aspose.Words

ImageData.IsLinkOnly Property

Returns true if the image is linked and not stored in the document.

[Visual Basic]
Public ReadOnly Property IsLinkOnly As Boolean
[C#]
public bool IsLinkOnly {get;}

Property Value

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


SourceFullName Property

Aspose.Words

ImageData.SourceFullName Property

Gets or sets the path and name of the source file for the linked image.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "Images/Hammer.wmf";

builder.Write("Image linked, not stored in the document: ");

Shape linkedOnly = new Shape(builder.Document, ShapeType.Image);
linkedOnly.WrapType = WrapType.Inline;
linkedOnly.ImageData.SourceFullName = imageFileName;

builder.InsertNode(linkedOnly);
builder.Writeln();

builder.Write("Image linked and stored in the document: ");

Shape linkedAndStored = new Shape(builder.Document, ShapeType.Image);
linkedAndStored.WrapType = WrapType.Inline;
linkedAndStored.ImageData.SourceFullName = imageFileName;
linkedAndStored.ImageData.SetImage(imageFileName);

builder.InsertNode(linkedAndStored);
builder.Writeln();

builder.Write("Image stored in the document, but not linked: ");

Shape stored = new Shape(builder.Document, ShapeType.Image);
stored.WrapType = WrapType.Inline;
stored.ImageData.SetImage(imageFileName);

builder.InsertNode(stored);
builder.Writeln();

builder.Document.Save(ArtifactsDir + "Image.CreateLinkedImage.doc");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


Title Property

Aspose.Words

ImageData.Title Property

Defines the title of an image.

[Visual Basic]
Public Property Title As String
[C#]
public string Title {get; set;}

Remarks

The default value is an empty string.

Example

Shows how to edit images using the ImageData attribute.

[C#]

// Open a document that contains images
Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

Shape sourceShape = (Shape)imgSourceDoc.GetChildNodes(NodeType.Shape, true)[0];

Document dstDoc = new Document();

// Import a shape from the source document and append it to the first paragraph, effectively cloning it
Shape importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

// Get the ImageData of the imported shape
ImageData imageData = importedShape.ImageData;
imageData.Title = "Imported Image";

// If an image appears to have no borders, its ImageData object will still have them, but in an unspecified color
Assert.AreEqual(4, imageData.Borders.Count);
Assert.AreEqual(Color.Empty, imageData.Borders[0].Color);

Assert.True(imageData.HasImage);

// This image is not linked to a shape or to an image in the file system
Assert.False(imageData.IsLink);
Assert.False(imageData.IsLinkOnly);

// Brightness and contrast are defined on a 0-1 scale, with 0.5 being the default value
imageData.Brightness = 0.8d;
imageData.Contrast = 1.0d;

// Our image will have a lot of white now that we've changed the brightness and contrast like that
// We can treat white as transparent with the following attribute
imageData.ChromaKey = Color.White;

// Import the source shape again, set it to black and white
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.GrayScale = true;

// Import the source shape again to create a third image, and set it to BiLevel
// Unlike greyscale, which preserves the brightness of the original colors,
// BiLevel sets every pixel to either black or white, whichever is closer to the original color
importedShape = (Shape)dstDoc.ImportNode(sourceShape, true);
dstDoc.FirstSection.Body.FirstParagraph.AppendChild(importedShape);

importedShape.ImageData.BiLevel = true;

// Cropping is determined on a 0-1 scale
// Cropping a side by 0.3 will crop 30% of the image out at that side
importedShape.ImageData.CropBottom = 0.3d;
importedShape.ImageData.CropLeft = 0.3d;
importedShape.ImageData.CropTop = 0.3d;
importedShape.ImageData.CropRight = 0.3d;

dstDoc.Save(ArtifactsDir + "ImageData.EditedImages.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageData Methods

The methods of the ImageData class are listed below. For a complete list of ImageData class members, see the ImageData Members topic.

Public Instance Methods

Save | Overloaded. Saves the image of the shape.
SetImage | Overloaded. Sets the image that the shape displays.
ToByteArray | Returns image bytes for any image regardless whether the image is stored or linked.
ToImage | Gets the image stored in the shape as a Image object.
ToStream | Creates and returns a stream that contains the image bytes.

See Also

ImageData Class | Aspose.Words.Drawing Namespace


Save Method

Aspose.Words

ImageData.Save Method

Saves the image of the shape.

Overload List

Saves the image into the specified stream.

public void Save(Stream);

Saves the image into a file.

public void Save(string);

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageData.Save Method (Stream)

Saves the image into the specified stream.

[Visual Basic]
Overloads Public Sub Save( _
ByVal stream As Stream _
)
[C#]
public void Save(
Stream stream
);

Parameters

stream
The stream where to save the image to.

Remarks

Is it the responsibility of the caller to dispose the stream object.

Example

Shows how to save all the images from a document to the file system.

[C#]

Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

// Images are stored as shapes
// Get into the document's shape collection to verify that it contains 6 images
List<Shape> shapes = imgSourceDoc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(6, shapes.Count);

// We will use an ImageFormatConverter to determine an image's file extension
ImageFormatConverter formatConverter = new ImageFormatConverter();

// Go over all of the document's shapes
// If a shape contains image data, save the image in the local file system
for (int i = 0; i < shapes.Count; i++)
{
    ImageData imageData = shapes[i].ImageData;

    if (imageData.HasImage)
    {
        ImageFormat format = imageData.ToImage().RawFormat;
        string fileExtension = formatConverter.ConvertToString(format);

        using (FileStream fileStream = File.Create(ArtifactsDir + $"Image from shape {i}.{fileExtension}"))
        {
            imageData.Save(fileStream);
        }
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.Save Overload List


ImageData.Save Method (String)

Saves the image into a file.

[Visual Basic]
Overloads Public Sub Save( _
ByVal fileName As String _
)
[C#]
public void Save(
string fileName
);

Parameters

fileName
The file name where to save the image.

Example

Shows how to extract images from a document and save them as files.

[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.Save Overload List


SetImage Method

Aspose.Words

ImageData.SetImage Method

Sets the image that the shape displays.

Overload List

Sets the image that the shape displays.

public void SetImage(Image);

Sets the image that the shape displays.

public void SetImage(Stream);

Sets the image that the shape displays.

public void SetImage(string);

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageData.SetImage Method (Image)

Sets the image that the shape displays.

[Visual Basic]
Overloads Public Sub SetImage( _
ByVal image As Image _
)
[C#]
public void SetImage(
Image image
);

Parameters

image
The image object.

Example

Shows two ways of importing images from the local file system into a document.

[C#]

Document doc = new Document();

// We can get an image from a file, set it as the image of a shape and append it to a paragraph
Image srcImage = Image.FromFile(ImageDir + "Aspose.Words.gif");

Shape imgShape = new Shape(doc, ShapeType.Image);
doc.FirstSection.Body.FirstParagraph.AppendChild(imgShape);
imgShape.ImageData.SetImage(srcImage);
srcImage.Dispose();

// We can also open an image file using a stream and set its contents as a shape's image
using (Stream stream = new FileStream(ImageDir + "Aspose.Words.gif", FileMode.Open, FileAccess.Read))
{
    imgShape = new Shape(doc, ShapeType.Image);
    doc.FirstSection.Body.FirstParagraph.AppendChild(imgShape);
    imgShape.ImageData.SetImage(stream);
    imgShape.Left = 150.0f;
}

doc.Save(ArtifactsDir + "ImageData.ImportedImage.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.SetImage Overload List


ImageData.SetImage Method (Stream)

Sets the image that the shape displays.

[Visual Basic]
Overloads Public Sub SetImage( _
ByVal stream As Stream _
)
[C#]
public void SetImage(
Stream stream
);

Parameters

stream
The stream that contains the image.

Example

Shows two ways of importing images from the local file system into a document.

[C#]

Document doc = new Document();

// We can get an image from a file, set it as the image of a shape and append it to a paragraph
Image srcImage = Image.FromFile(ImageDir + "Aspose.Words.gif");

Shape imgShape = new Shape(doc, ShapeType.Image);
doc.FirstSection.Body.FirstParagraph.AppendChild(imgShape);
imgShape.ImageData.SetImage(srcImage);
srcImage.Dispose();

// We can also open an image file using a stream and set its contents as a shape's image
using (Stream stream = new FileStream(ImageDir + "Aspose.Words.gif", FileMode.Open, FileAccess.Read))
{
    imgShape = new Shape(doc, ShapeType.Image);
    doc.FirstSection.Body.FirstParagraph.AppendChild(imgShape);
    imgShape.ImageData.SetImage(stream);
    imgShape.Left = 150.0f;
}

doc.Save(ArtifactsDir + "ImageData.ImportedImage.docx");

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.SetImage Overload List


ImageData.SetImage Method (String)

Sets the image that the shape displays.

[Visual Basic]
Overloads Public Sub SetImage( _
ByVal fileName As String _
)
[C#]
public void SetImage(
string fileName
);

Parameters

fileName
The image file. Can be a file name or a URL.

Example

Shows how to insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "Images/Hammer.wmf";

builder.Write("Image linked, not stored in the document: ");

Shape linkedOnly = new Shape(builder.Document, ShapeType.Image);
linkedOnly.WrapType = WrapType.Inline;
linkedOnly.ImageData.SourceFullName = imageFileName;

builder.InsertNode(linkedOnly);
builder.Writeln();

builder.Write("Image linked and stored in the document: ");

Shape linkedAndStored = new Shape(builder.Document, ShapeType.Image);
linkedAndStored.WrapType = WrapType.Inline;
linkedAndStored.ImageData.SourceFullName = imageFileName;
linkedAndStored.ImageData.SetImage(imageFileName);

builder.InsertNode(linkedAndStored);
builder.Writeln();

builder.Write("Image stored in the document, but not linked: ");

Shape stored = new Shape(builder.Document, ShapeType.Image);
stored.WrapType = WrapType.Inline;
stored.ImageData.SetImage(imageFileName);

builder.InsertNode(stored);
builder.Writeln();

builder.Document.Save(ArtifactsDir + "Image.CreateLinkedImage.doc");

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.SetImage Overload List


ImageData.ToByteArray Method

Returns image bytes for any image regardless whether the image is stored or linked.

[Visual Basic]
Public Function ToByteArray() As Byte()
[C#]
public byte[] ToByteArray();

Return Value

Remarks

If the image is linked, downloads the image every time it is called.

Example

Shows how to access raw image data in a shape's ImageData object.

[C#]

Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

// Images are stored as shapes
// Get into the document's shape collection to verify that it contains 6 images
List<Shape> shapes = imgSourceDoc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(6, shapes.Count);

// ToByteArray() returns the value of the ImageBytes property
Assert.AreEqual(shapes[0].ImageData.ImageBytes, shapes[0].ImageData.ToByteArray());

// Put the shape's image data into a stream
// Then, put the image data from that stream into another stream which creates an image file in the local file system
using (Stream imgStream = shapes[0].ImageData.ToStream())
{
    using (FileStream outStream = new FileStream(ArtifactsDir + "MyImg.png", FileMode.CreateNew))
    {
        imgStream.CopyTo(outStream);
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageBytes


ImageData.ToImage Method

Gets the image stored in the shape as a Image object.

[Visual Basic]
Public Function ToImage() As Image
[C#]
public Image ToImage();

Return Value

Remarks

A new Image object is created every time this method is called.

It is the responsibility of the caller to dispose the image object.

Example

Shows how to save all the images from a document to the file system.

[C#]

Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

// Images are stored as shapes
// Get into the document's shape collection to verify that it contains 6 images
List<Shape> shapes = imgSourceDoc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(6, shapes.Count);

// We will use an ImageFormatConverter to determine an image's file extension
ImageFormatConverter formatConverter = new ImageFormatConverter();

// Go over all of the document's shapes
// If a shape contains image data, save the image in the local file system
for (int i = 0; i < shapes.Count; i++)
{
    ImageData imageData = shapes[i].ImageData;

    if (imageData.HasImage)
    {
        ImageFormat format = imageData.ToImage().RawFormat;
        string fileExtension = formatConverter.ConvertToString(format);

        using (FileStream fileStream = File.Create(ArtifactsDir + $"Image from shape {i}.{fileExtension}"))
        {
            imageData.Save(fileStream);
        }
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageData.ToStream Method

Creates and returns a stream that contains the image bytes.

[Visual Basic]
Public Function ToStream() As Stream
[C#]
public Stream ToStream();

Remarks

If the image bytes are stored in the shape, creates and returns a MemoryStream object.

If the image is linked and stored in a file, opens the file and returns a FileStream object.

If the image is linked and stored in an external URL, downloads the file and returns a MemoryStream object.

Is it the responsibility of the caller to dispose the stream object.

Example

Shows how to access raw image data in a shape's ImageData object.

[C#]

Document imgSourceDoc = new Document(MyDir + "Image.SampleImages.doc");

// Images are stored as shapes
// Get into the document's shape collection to verify that it contains 6 images
List<Shape> shapes = imgSourceDoc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(6, shapes.Count);

// ToByteArray() returns the value of the ImageBytes property
Assert.AreEqual(shapes[0].ImageData.ImageBytes, shapes[0].ImageData.ToByteArray());

// Put the shape's image data into a stream
// Then, put the image data from that stream into another stream which creates an image file in the local file system
using (Stream imgStream = shapes[0].ImageData.ToStream())
{
    using (FileStream outStream = new FileStream(ArtifactsDir + "MyImg.png", FileMode.CreateNew))
    {
        imgStream.CopyTo(outStream);
    }
}

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageSize Class

Contains information about image size and resolution.

For a list of all members of this type, see ImageSize Members.

System.Object
Aspose.Words.Drawing.ImageSize

[Visual Basic]
Public Class ImageSize
[C#]
public class ImageSize

Remarks

Example

Shows how to resize an image shape.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inserted at 100% scale.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// It is easy to change the shape size. In this case, make it 50% relative to the current shape size.
shape.Width = shape.Width * 0.5;
shape.Height = shape.Height * 0.5;

// However, we can also go back to the original image size and scale from there, say 110%.
ImageSize imageSize = shape.ImageData.ImageSize;
shape.Width = imageSize.WidthPoints * 1.1;
shape.Height = imageSize.HeightPoints * 1.1;

builder.Document.Save(ArtifactsDir + "Image.ScaleImage.doc");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ImageSize Members | Aspose.Words.Drawing Namespace | ImageSize


ImageSize Members

ImageSize overview

Public Instance Constructors

ImageSize Overloaded. Initializes a new instance of the ImageSize class.

Public Instance Properties

HeightPixels | Gets the height of the image in pixels.
HeightPoints | Gets the height of the image in points. 1 point is 1/72 inch.
HorizontalResolution | Gets the horizontal resolution in DPI.
VerticalResolution | Gets the vertical resolution in DPI.
WidthPixels | Gets the width of the image in pixels.
WidthPoints | Gets the width of the image in points. 1 point is 1/72 inch.

See Also

ImageSize Class | Aspose.Words.Drawing Namespace | ImageSize


ImageSize Constructor

Initializes width and height to the given values in pixels. Initializes resolution to 96 dpi.

Overload List

Initializes width and height to the given values in pixels. Initializes resolution to 96 dpi.

public ImageSize(int,int);

Initializes width, height and resolution to the given values.

public ImageSize(int,int,double,double);

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


ImageSize Constructor (Int32, Int32)

Initializes width and height to the given values in pixels. Initializes resolution to 96 dpi.

[Visual Basic]
Overloads Public Sub New( _
ByVal widthPixels As Integer, _
ByVal heightPixels As Integer _
)
[C#]
public ImageSize(
int widthPixels,
int heightPixels
);

Parameters

widthPixels
Width in pixels.
heightPixels
Height in pixels.

See Also

ImageSize Class | Aspose.Words.Drawing Namespace | ImageSize Constructor Overload List


ImageSize Constructor (Int32, Int32, Double, Double)

Initializes width, height and resolution to the given values.

[Visual Basic]
Overloads Public Sub New( _
ByVal widthPixels As Integer, _
ByVal heightPixels As Integer, _
ByVal horizontalResolution As Double, _
ByVal verticalResolution As Double _
)
[C#]
public ImageSize(
int widthPixels,
int heightPixels,
double horizontalResolution,
double verticalResolution
);

Parameters

widthPixels
Width in pixels.
heightPixels
Height in pixels.
horizontalResolution
Horizontal resolution in DPI.
verticalResolution
Vertical resolution in DPI.

See Also

ImageSize Class | Aspose.Words.Drawing Namespace | ImageSize Constructor Overload List


ImageSize Properties

The properties of the ImageSize class are listed below. For a complete list of ImageSize class members, see the ImageSize Members topic.

Public Instance Properties

HeightPixels | Gets the height of the image in pixels.
HeightPoints | Gets the height of the image in points. 1 point is 1/72 inch.
HorizontalResolution | Gets the horizontal resolution in DPI.
VerticalResolution | Gets the vertical resolution in DPI.
WidthPixels | Gets the width of the image in pixels.
WidthPoints | Gets the width of the image in points. 1 point is 1/72 inch.

See Also

ImageSize Class | Aspose.Words.Drawing Namespace | ImageSize


HeightPixels Property

Aspose.Words

ImageSize.HeightPixels Property

Gets the height of the image in pixels.

[Visual Basic]
Public ReadOnly Property HeightPixels As Integer
[C#]
public int HeightPixels {get;}

Example

Shows how to access and use a shape's ImageSize property.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape into the document which contains an image taken from our local file system
Shape shape = builder.InsertImage(ImageDir + "Aspose.Words.gif");

// If the shape contains an image, its ImageData property will be valid, and it will contain an ImageSize object
ImageSize imageSize = shape.ImageData.ImageSize;

// The ImageSize object contains raw information about the image within the shape
Assert.AreEqual(200, imageSize.HeightPixels);
Assert.AreEqual(200, imageSize.WidthPixels);

const double delta = 0.05;
Assert.AreEqual(95.98d, imageSize.HorizontalResolution, delta);
Assert.AreEqual(95.98d, imageSize.VerticalResolution, delta);

// These values are read-only
// If we want to transform the image, we need to change the size of the shape that contains it
// We can still use values within ImageSize as a reference
// In the example below, we will get the shape to display the image in twice its original size
shape.Width = imageSize.WidthPoints * 2;
shape.Height = imageSize.HeightPoints * 2;

doc.Save(ArtifactsDir + "Image.ImageSize.docx");

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


HeightPoints Property

Aspose.Words

ImageSize.HeightPoints Property

Gets the height of the image in points. 1 point is 1/72 inch.

[Visual Basic]
Public ReadOnly Property HeightPoints As Double
[C#]
public double HeightPoints {get;}

Example

Shows how to resize an image shape.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inserted at 100% scale.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// It is easy to change the shape size. In this case, make it 50% relative to the current shape size.
shape.Width = shape.Width * 0.5;
shape.Height = shape.Height * 0.5;

// However, we can also go back to the original image size and scale from there, say 110%.
ImageSize imageSize = shape.ImageData.ImageSize;
shape.Width = imageSize.WidthPoints * 1.1;
shape.Height = imageSize.HeightPoints * 1.1;

builder.Document.Save(ArtifactsDir + "Image.ScaleImage.doc");

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


HorizontalResolution Property

Aspose.Words

ImageSize.HorizontalResolution Property

Gets the horizontal resolution in DPI.

[Visual Basic]
Public ReadOnly Property HorizontalResolution As Double
[C#]
public double HorizontalResolution {get;}

Example

Shows how to access and use a shape's ImageSize property.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape into the document which contains an image taken from our local file system
Shape shape = builder.InsertImage(ImageDir + "Aspose.Words.gif");

// If the shape contains an image, its ImageData property will be valid, and it will contain an ImageSize object
ImageSize imageSize = shape.ImageData.ImageSize;

// The ImageSize object contains raw information about the image within the shape
Assert.AreEqual(200, imageSize.HeightPixels);
Assert.AreEqual(200, imageSize.WidthPixels);

const double delta = 0.05;
Assert.AreEqual(95.98d, imageSize.HorizontalResolution, delta);
Assert.AreEqual(95.98d, imageSize.VerticalResolution, delta);

// These values are read-only
// If we want to transform the image, we need to change the size of the shape that contains it
// We can still use values within ImageSize as a reference
// In the example below, we will get the shape to display the image in twice its original size
shape.Width = imageSize.WidthPoints * 2;
shape.Height = imageSize.HeightPoints * 2;

doc.Save(ArtifactsDir + "Image.ImageSize.docx");

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


VerticalResolution Property

Aspose.Words

ImageSize.VerticalResolution Property

Gets the vertical resolution in DPI.

[Visual Basic]
Public ReadOnly Property VerticalResolution As Double
[C#]
public double VerticalResolution {get;}

Example

Shows how to access and use a shape's ImageSize property.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape into the document which contains an image taken from our local file system
Shape shape = builder.InsertImage(ImageDir + "Aspose.Words.gif");

// If the shape contains an image, its ImageData property will be valid, and it will contain an ImageSize object
ImageSize imageSize = shape.ImageData.ImageSize;

// The ImageSize object contains raw information about the image within the shape
Assert.AreEqual(200, imageSize.HeightPixels);
Assert.AreEqual(200, imageSize.WidthPixels);

const double delta = 0.05;
Assert.AreEqual(95.98d, imageSize.HorizontalResolution, delta);
Assert.AreEqual(95.98d, imageSize.VerticalResolution, delta);

// These values are read-only
// If we want to transform the image, we need to change the size of the shape that contains it
// We can still use values within ImageSize as a reference
// In the example below, we will get the shape to display the image in twice its original size
shape.Width = imageSize.WidthPoints * 2;
shape.Height = imageSize.HeightPoints * 2;

doc.Save(ArtifactsDir + "Image.ImageSize.docx");

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


WidthPixels Property

Aspose.Words

ImageSize.WidthPixels Property

Gets the width of the image in pixels.

[Visual Basic]
Public ReadOnly Property WidthPixels As Integer
[C#]
public int WidthPixels {get;}

Example

Shows how to access and use a shape's ImageSize property.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape into the document which contains an image taken from our local file system
Shape shape = builder.InsertImage(ImageDir + "Aspose.Words.gif");

// If the shape contains an image, its ImageData property will be valid, and it will contain an ImageSize object
ImageSize imageSize = shape.ImageData.ImageSize;

// The ImageSize object contains raw information about the image within the shape
Assert.AreEqual(200, imageSize.HeightPixels);
Assert.AreEqual(200, imageSize.WidthPixels);

const double delta = 0.05;
Assert.AreEqual(95.98d, imageSize.HorizontalResolution, delta);
Assert.AreEqual(95.98d, imageSize.VerticalResolution, delta);

// These values are read-only
// If we want to transform the image, we need to change the size of the shape that contains it
// We can still use values within ImageSize as a reference
// In the example below, we will get the shape to display the image in twice its original size
shape.Width = imageSize.WidthPoints * 2;
shape.Height = imageSize.HeightPoints * 2;

doc.Save(ArtifactsDir + "Image.ImageSize.docx");

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


WidthPoints Property

Aspose.Words

ImageSize.WidthPoints Property

Gets the width of the image in points. 1 point is 1/72 inch.

[Visual Basic]
Public ReadOnly Property WidthPoints As Double
[C#]
public double WidthPoints {get;}

Example

Shows how to resize an image shape.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inserted at 100% scale.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// It is easy to change the shape size. In this case, make it 50% relative to the current shape size.
shape.Width = shape.Width * 0.5;
shape.Height = shape.Height * 0.5;

// However, we can also go back to the original image size and scale from there, say 110%.
ImageSize imageSize = shape.ImageData.ImageSize;
shape.Width = imageSize.WidthPoints * 1.1;
shape.Height = imageSize.HeightPoints * 1.1;

builder.Document.Save(ArtifactsDir + "Image.ScaleImage.doc");

See Also

ImageSize Class | Aspose.Words.Drawing Namespace


ImageType Enumeration

Specifies the type (format) of an image in a Microsoft Word document.

[Visual Basic]
Public Enum ImageType
[C#]
public enum ImageType

Remarks

Example

Shows how to add an image to a shape and check its type

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);

        // The image started off as an animated .gif but it gets converted to a .png since there cannot be animated images in documents
        Shape imgShape = builder.InsertImage(image);
        Assert.AreEqual(ImageType.Png, imgShape.ImageData.ImageType);
    }
}

Members

Member Name | Description | Value
NoImage | The is no image data. | 0
Unknown | An unknown image type or image type that cannot be directly stored inside a Microsoft Word document. | 1
Emf | Windows Enhanced Metafile. | 2
Wmf | Windows Metafile. | 3
Pict | Macintosh PICT. An existing image will be preserved in a document, but inserting new PICT images into a document is not supported. | 4
Jpeg | JPEG JFIF. | 5
Png | Portable Network Graphics. | 6
Bmp | Windows Bitmap. | 7

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | ImageType


JoinStyle Enumeration

Line join style.

[Visual Basic]
Public Enum JoinStyle
[C#]
public enum JoinStyle

Remarks

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

Members

Member Name | Description | Value
Bevel | Join edges by a straight line. | 0
Miter | Extend edges until they join. | 1
Round | Draw an arc between the two edges. | 2

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | JoinStyle


LayoutFlow Enumeration

Determines the flow of the text layout in a textbox.

[Visual Basic]
Public Enum LayoutFlow
[C#]
public enum LayoutFlow

Remarks

Example

Shows how to add text to a textbox and change its orientation

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Shape textbox = new Shape(doc, ShapeType.TextBox)
{
    Width = 100,
    Height = 100,
    TextBox = { LayoutFlow = LayoutFlow.BottomToTop }
};

textbox.AppendChild(new Paragraph(doc));
builder.InsertNode(textbox);

builder.MoveTo(textbox.FirstParagraph);
builder.Write("This text is flipped 90 degrees to the left.");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

Members

Member Name | Description | Value
Horizontal | Text is displayed horizontally. | 0
TopToBottomIdeographic | Ideographic text is displayed vertically. | 1
BottomToTop | Text is displayed vertically. | 2
TopToBottom | Text is displayed vertically. | 3
HorizontalIdeographic | Ideographic text is displayed horizontally. | 4
Vertical | Text is displayed vertically. | 5

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | LayoutFlow


OleFormat Class

Provides access to the data of an OLE object or ActiveX control.

For a list of all members of this type, see OleFormat Members.

System.Object
Aspose.Words.Drawing.OleFormat

[Visual Basic]
Public Class OleFormat
[C#]
public class OleFormat

Remarks

Use the OleFormat property to access the data of an OLE object. You do not create instances of the OleFormat class directly.

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OleFormat Members | Aspose.Words.Drawing Namespace | OleFormat


OleFormat Members

OleFormat overview

Public Instance Properties

AutoUpdate | Specifies whether the link to the OLE object is automatically updated or not in Microsoft Word.
Clsid | Gets the CLSID of the OLE object.
IconCaption | Gets icon caption of OLE object. In case of OLE object is not embedded as icon or caption couldn't be retrieved returns empty string.
IsLink | Returns true if the OLE object is linked (when SourceFullName is specified).
IsLocked | Specifies whether the link to the OLE object is locked from updates.
OleControl | Gets OleControl objects if this OLE object is an ActiveX control. Otherwise this property is null.
OleIcon | Gets the draw aspect of the OLE object. When true, the OLE object is displayed as an icon. When false, the OLE object is displayed as content.
OlePackage | Provide access to OlePackage if OLE object is an OLE Package. Returns null otherwise.
ProgId | Gets or sets the ProgID of the OLE object.
SourceFullName | Gets or sets the path and name of the source file for the linked OLE object.
SourceItem | Gets or sets a string that is used to identify the portion of the source file that is being linked.
SuggestedExtension | Gets the file extension suggested for the current embedded object if you want to save it into a file.
SuggestedFileName | Gets the file name suggested for the current embedded object if you want to save it into a file.

Public Instance Methods

GetOleEntry | Gets OLE object data entry.
Save | Overloaded. Saves the data of the embedded object into the specified stream.

See Also

OleFormat Class | Aspose.Words.Drawing Namespace | OleFormat


OleFormat Properties

The properties of the OleFormat class are listed below. For a complete list of OleFormat class members, see the OleFormat Members topic.

Public Instance Properties

AutoUpdate | Specifies whether the link to the OLE object is automatically updated or not in Microsoft Word.
Clsid | Gets the CLSID of the OLE object.
IconCaption | Gets icon caption of OLE object. In case of OLE object is not embedded as icon or caption couldn't be retrieved returns empty string.
IsLink | Returns true if the OLE object is linked (when SourceFullName is specified).
IsLocked | Specifies whether the link to the OLE object is locked from updates.
OleControl | Gets OleControl objects if this OLE object is an ActiveX control. Otherwise this property is null.
OleIcon | Gets the draw aspect of the OLE object. When true, the OLE object is displayed as an icon. When false, the OLE object is displayed as content.
OlePackage | Provide access to OlePackage if OLE object is an OLE Package. Returns null otherwise.
ProgId | Gets or sets the ProgID of the OLE object.
SourceFullName | Gets or sets the path and name of the source file for the linked OLE object.
SourceItem | Gets or sets a string that is used to identify the portion of the source file that is being linked.
SuggestedExtension | Gets the file extension suggested for the current embedded object if you want to save it into a file.
SuggestedFileName | Gets the file name suggested for the current embedded object if you want to save it into a file.

See Also

OleFormat Class | Aspose.Words.Drawing Namespace | OleFormat


AutoUpdate Property

Aspose.Words

OleFormat.AutoUpdate Property

Specifies whether the link to the OLE object is automatically updated or not in Microsoft Word.

[Visual Basic]
Public Property AutoUpdate As Boolean
[C#]
public bool AutoUpdate {get; set;}

Remarks

The default value is false.

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


Clsid Property

Aspose.Words

OleFormat.Clsid Property

Gets the CLSID of the OLE object.

[Visual Basic]
Public ReadOnly Property Clsid As Guid
[C#]
public Guid Clsid {get;}

Example

Shows how to access an OLE control embedded in a document and its child controls.

[C#]

// Open a document that contains a Microsoft Forms OLE control with child controls
Document doc = new Document(MyDir + "Shape.Ole.ControlCollection.docm");

// Get the shape that contains the control
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

Assert.AreEqual("6e182020-f460-11ce-9bcd-00aa00608e01", shape.OleFormat.Clsid.ToString());

Forms2OleControl oleControl = (Forms2OleControl)shape.OleFormat.OleControl;

// Some controls contain child controls
Forms2OleControlCollection oleControlCollection = oleControl.ChildNodes;

// In this case, the child controls are 3 option buttons
Assert.AreEqual(3, oleControlCollection.Count);

Assert.AreEqual("C#", oleControlCollection[0].Caption);
Assert.AreEqual("1", oleControlCollection[0].Value);

Assert.AreEqual("Visual Basic", oleControlCollection[1].Caption);
Assert.AreEqual("0", oleControlCollection[1].Value);

Assert.AreEqual("Delphi", oleControlCollection[2].Caption);
Assert.AreEqual("0", oleControlCollection[2].Value);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


IconCaption Property

Aspose.Words

OleFormat.IconCaption Property

Gets icon caption of OLE object.

In case of OLE object is not embedded as icon or caption couldn't be retrieved returns empty string.

[Visual Basic]
Public ReadOnly Property IconCaption As String
[C#]
public string IconCaption {get;}

Example

Shows how to insert linked and unlinked OLE objects.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Embed a Microsoft Visio drawing as an OLE object into the document
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", false, false, null);

// Insert a link to the file in the local file system and display it as an icon
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", true, true, null);

// Both the OLE objects are stored within shapes
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// If the shape is an OLE object, it will have a valid OleFormat property
// We can use it check if it is linked or displayed as an icon, among other things
OleFormat oleFormat = shapes[0].OleFormat;
Assert.AreEqual(false, oleFormat.IsLink);
Assert.AreEqual(false, oleFormat.OleIcon);

oleFormat = shapes[1].OleFormat;
Assert.AreEqual(true, oleFormat.IsLink);
Assert.AreEqual(true, oleFormat.OleIcon);

// Get the name or the source file and verify that the whole file is linked
Assert.True(oleFormat.SourceFullName.EndsWith(@"Images\visio2010.vsd"));
Assert.AreEqual("", oleFormat.SourceItem);

Assert.AreEqual("Packager", oleFormat.IconCaption);

doc.Save(ArtifactsDir + "Shape.OleLinks.docx");

// We can get a stream with the OLE data entry, if the object has this
using (MemoryStream stream = oleFormat.GetOleEntry("\x0001CompObj"))
{
    byte[] oleEntryBytes = stream.ToArray();
    Assert.AreEqual(76, oleEntryBytes.Length);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


IsLink Property

Aspose.Words

OleFormat.IsLink Property

Returns true if the OLE object is linked (when SourceFullName is specified).

[Visual Basic]
Public ReadOnly Property IsLink As Boolean
[C#]
public bool IsLink {get;}

Example

Shows how to insert linked and unlinked OLE objects.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Embed a Microsoft Visio drawing as an OLE object into the document
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", false, false, null);

// Insert a link to the file in the local file system and display it as an icon
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", true, true, null);

// Both the OLE objects are stored within shapes
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// If the shape is an OLE object, it will have a valid OleFormat property
// We can use it check if it is linked or displayed as an icon, among other things
OleFormat oleFormat = shapes[0].OleFormat;
Assert.AreEqual(false, oleFormat.IsLink);
Assert.AreEqual(false, oleFormat.OleIcon);

oleFormat = shapes[1].OleFormat;
Assert.AreEqual(true, oleFormat.IsLink);
Assert.AreEqual(true, oleFormat.OleIcon);

// Get the name or the source file and verify that the whole file is linked
Assert.True(oleFormat.SourceFullName.EndsWith(@"Images\visio2010.vsd"));
Assert.AreEqual("", oleFormat.SourceItem);

Assert.AreEqual("Packager", oleFormat.IconCaption);

doc.Save(ArtifactsDir + "Shape.OleLinks.docx");

// We can get a stream with the OLE data entry, if the object has this
using (MemoryStream stream = oleFormat.GetOleEntry("\x0001CompObj"))
{
    byte[] oleEntryBytes = stream.ToArray();
    Assert.AreEqual(76, oleEntryBytes.Length);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


IsLocked Property

Aspose.Words

OleFormat.IsLocked Property

Specifies whether the link to the OLE object is locked from updates.

[Visual Basic]
Public Property IsLocked As Boolean
[C#]
public bool IsLocked {get; set;}

Remarks

The default value is false.

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


OleControl Property

Aspose.Words

OleFormat.OleControl Property

Gets OleControl objects if this OLE object is an ActiveX control. Otherwise this property is null.

[Visual Basic]
Public ReadOnly Property OleControl As OleControl
[C#]
public OleControl OleControl {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


OleIcon Property

Aspose.Words

OleFormat.OleIcon Property

Gets the draw aspect of the OLE object. When true, the OLE object is displayed as an icon. When false, the OLE object is displayed as content.

[Visual Basic]
Public ReadOnly Property OleIcon As Boolean
[C#]
public bool OleIcon {get;}

Remarks

Aspose.Words does not allow to set this property to avoid confusion. If you were able to change the draw aspect in Aspose.Words, Microsoft Word would still display the OLE object in its original draw aspect until you edit or update the OLE object in Microsoft Word.

Example

Shows how to insert linked and unlinked OLE objects.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Embed a Microsoft Visio drawing as an OLE object into the document
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", false, false, null);

// Insert a link to the file in the local file system and display it as an icon
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", true, true, null);

// Both the OLE objects are stored within shapes
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// If the shape is an OLE object, it will have a valid OleFormat property
// We can use it check if it is linked or displayed as an icon, among other things
OleFormat oleFormat = shapes[0].OleFormat;
Assert.AreEqual(false, oleFormat.IsLink);
Assert.AreEqual(false, oleFormat.OleIcon);

oleFormat = shapes[1].OleFormat;
Assert.AreEqual(true, oleFormat.IsLink);
Assert.AreEqual(true, oleFormat.OleIcon);

// Get the name or the source file and verify that the whole file is linked
Assert.True(oleFormat.SourceFullName.EndsWith(@"Images\visio2010.vsd"));
Assert.AreEqual("", oleFormat.SourceItem);

Assert.AreEqual("Packager", oleFormat.IconCaption);

doc.Save(ArtifactsDir + "Shape.OleLinks.docx");

// We can get a stream with the OLE data entry, if the object has this
using (MemoryStream stream = oleFormat.GetOleEntry("\x0001CompObj"))
{
    byte[] oleEntryBytes = stream.ToArray();
    Assert.AreEqual(76, oleEntryBytes.Length);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


OlePackage Property

Aspose.Words

OleFormat.OlePackage Property

Provide access to OlePackage if OLE object is an OLE Package. Returns null otherwise.

[Visual Basic]
Public ReadOnly Property OlePackage As OlePackage
[C#]
public OlePackage OlePackage {get;}

Remarks

OLE Package is a legacy technology that allows to wrap any file format not present in the OLE registry of a Windows system into a generic package allowing to embed almost anything into a document. See OlePackage type for more info.

Example

Shows how insert ole object as ole package and set it file name and display name.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

byte[] zipFileBytes = File.ReadAllBytes(DatabaseDir + "cat001.zip");

using (MemoryStream stream = new MemoryStream(zipFileBytes))
{
    Shape shape = builder.InsertOleObject(stream, "Package", true, null);

    OlePackage setOlePackage = shape.OleFormat.OlePackage;
    setOlePackage.FileName = "Cat FileName.zip";
    setOlePackage.DisplayName = "Cat DisplayName.zip";

    doc.Save(ArtifactsDir + "Shape.InsertOlePackage.docx");
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


ProgId Property

Aspose.Words

OleFormat.ProgId Property

Gets or sets the ProgID of the OLE object.

[Visual Basic]
Public Property ProgId As String
[C#]
public string ProgId {get; set;}

Remarks

The ProgID property is not always present in Microsoft Word documents and cannot be relied upon.

Cannot be null.

The default value is an empty string.

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


SourceFullName Property

Aspose.Words

OleFormat.SourceFullName Property

Gets or sets the path and name of the source file for the linked OLE object.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Remarks

The default value is an empty string.

If SourceFullName is not an empty string, the OLE object is linked.

Example

Shows how to insert linked and unlinked OLE objects.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Embed a Microsoft Visio drawing as an OLE object into the document
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", false, false, null);

// Insert a link to the file in the local file system and display it as an icon
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", true, true, null);

// Both the OLE objects are stored within shapes
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// If the shape is an OLE object, it will have a valid OleFormat property
// We can use it check if it is linked or displayed as an icon, among other things
OleFormat oleFormat = shapes[0].OleFormat;
Assert.AreEqual(false, oleFormat.IsLink);
Assert.AreEqual(false, oleFormat.OleIcon);

oleFormat = shapes[1].OleFormat;
Assert.AreEqual(true, oleFormat.IsLink);
Assert.AreEqual(true, oleFormat.OleIcon);

// Get the name or the source file and verify that the whole file is linked
Assert.True(oleFormat.SourceFullName.EndsWith(@"Images\visio2010.vsd"));
Assert.AreEqual("", oleFormat.SourceItem);

Assert.AreEqual("Packager", oleFormat.IconCaption);

doc.Save(ArtifactsDir + "Shape.OleLinks.docx");

// We can get a stream with the OLE data entry, if the object has this
using (MemoryStream stream = oleFormat.GetOleEntry("\x0001CompObj"))
{
    byte[] oleEntryBytes = stream.ToArray();
    Assert.AreEqual(76, oleEntryBytes.Length);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


SourceItem Property

Aspose.Words

OleFormat.SourceItem Property

Gets or sets a string that is used to identify the portion of the source file that is being linked.

[Visual Basic]
Public Property SourceItem As String
[C#]
public string SourceItem {get; set;}

Remarks

The default value is an empty string.

For example, if the source file is a Microsoft Excel workbook, the SourceItem property might return "Workbook1!R3C1:R4C2" if the OLE object contains only a few cells from the worksheet.

Example

Shows how to insert linked and unlinked OLE objects.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Embed a Microsoft Visio drawing as an OLE object into the document
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", false, false, null);

// Insert a link to the file in the local file system and display it as an icon
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", true, true, null);

// Both the OLE objects are stored within shapes
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// If the shape is an OLE object, it will have a valid OleFormat property
// We can use it check if it is linked or displayed as an icon, among other things
OleFormat oleFormat = shapes[0].OleFormat;
Assert.AreEqual(false, oleFormat.IsLink);
Assert.AreEqual(false, oleFormat.OleIcon);

oleFormat = shapes[1].OleFormat;
Assert.AreEqual(true, oleFormat.IsLink);
Assert.AreEqual(true, oleFormat.OleIcon);

// Get the name or the source file and verify that the whole file is linked
Assert.True(oleFormat.SourceFullName.EndsWith(@"Images\visio2010.vsd"));
Assert.AreEqual("", oleFormat.SourceItem);

Assert.AreEqual("Packager", oleFormat.IconCaption);

doc.Save(ArtifactsDir + "Shape.OleLinks.docx");

// We can get a stream with the OLE data entry, if the object has this
using (MemoryStream stream = oleFormat.GetOleEntry("\x0001CompObj"))
{
    byte[] oleEntryBytes = stream.ToArray();
    Assert.AreEqual(76, oleEntryBytes.Length);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


SuggestedExtension Property

Aspose.Words

OleFormat.SuggestedExtension Property

Gets the file extension suggested for the current embedded object if you want to save it into a file.

[Visual Basic]
Public ReadOnly Property SuggestedExtension As String
[C#]
public string SuggestedExtension {get;}

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


SuggestedFileName Property

Aspose.Words

OleFormat.SuggestedFileName Property

Gets the file name suggested for the current embedded object if you want to save it into a file.

[Visual Basic]
Public ReadOnly Property SuggestedFileName As String
[C#]
public string SuggestedFileName {get;}

Example

Shows how to get suggested file name from the object.

[C#]

Document doc = new Document(MyDir + "Shape.SuggestedFileName.rtf");

// Gets the file name suggested for the current embedded object if you want to save it into a file
Shape oleShape = (Shape) doc.FirstSection.Body.GetChild(NodeType.Shape, 0, true);
String suggestedFileName = oleShape.OleFormat.SuggestedFileName;

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


OleFormat Methods

The methods of the OleFormat class are listed below. For a complete list of OleFormat class members, see the OleFormat Members topic.

Public Instance Methods

GetOleEntry | Gets OLE object data entry.
Save | Overloaded. Saves the data of the embedded object into the specified stream.

See Also

OleFormat Class | Aspose.Words.Drawing Namespace | OleFormat


OleFormat.GetOleEntry Method

Gets OLE object data entry.

[Visual Basic]
Public Function GetOleEntry( _
ByVal oleEntryName As String _
) As MemoryStream
[C#]
public MemoryStream GetOleEntry(
string oleEntryName
);

Parameters

oleEntryName
Case-sensitive name of the OLE data stream.

Return Value

An OLE data stream or null.

Example

Shows how to insert linked and unlinked OLE objects.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Embed a Microsoft Visio drawing as an OLE object into the document
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", false, false, null);

// Insert a link to the file in the local file system and display it as an icon
builder.InsertOleObject(ImageDir + "visio2010.vsd", "Package", true, true, null);

// Both the OLE objects are stored within shapes
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// If the shape is an OLE object, it will have a valid OleFormat property
// We can use it check if it is linked or displayed as an icon, among other things
OleFormat oleFormat = shapes[0].OleFormat;
Assert.AreEqual(false, oleFormat.IsLink);
Assert.AreEqual(false, oleFormat.OleIcon);

oleFormat = shapes[1].OleFormat;
Assert.AreEqual(true, oleFormat.IsLink);
Assert.AreEqual(true, oleFormat.OleIcon);

// Get the name or the source file and verify that the whole file is linked
Assert.True(oleFormat.SourceFullName.EndsWith(@"Images\visio2010.vsd"));
Assert.AreEqual("", oleFormat.SourceItem);

Assert.AreEqual("Packager", oleFormat.IconCaption);

doc.Save(ArtifactsDir + "Shape.OleLinks.docx");

// We can get a stream with the OLE data entry, if the object has this
using (MemoryStream stream = oleFormat.GetOleEntry("\x0001CompObj"))
{
    byte[] oleEntryBytes = stream.ToArray();
    Assert.AreEqual(76, oleEntryBytes.Length);
}

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


Save Method

Aspose.Words

OleFormat.Save Method

Saves the data of the embedded object into the specified stream.

Overload List

Saves the data of the embedded object into the specified stream.

public void Save(Stream);

Saves the data of the embedded object into a file with the specified name.

public void Save(string);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace


OleFormat.Save Method (Stream)

Saves the data of the embedded object into the specified stream.

[Visual Basic]
Overloads Public Sub Save( _
ByVal stream As Stream _
)
[C#]
public void Save(
Stream stream
);

Parameters

stream
Where to save the object data.

Remarks

It is the responsibility of the caller to dispose the stream.

Exceptions

Exception Type | Condition
InvalidOperationException | Throws if you attempt to save a linked object.

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace | OleFormat.Save Overload List


OleFormat.Save Method (String)

Saves the data of the embedded object into a file with the specified name.

[Visual Basic]
Overloads Public Sub Save( _
ByVal fileName As String _
)
[C#]
public void Save(
string fileName
);

Parameters

fileName
Name of the file to save the OLE object data.

Exceptions

Exception Type | Condition
InvalidOperationException | Throws if you attempt to save a linked object.

Example

Shows how to extract embedded OLE objects into files.

[C#]

Document doc = new Document(MyDir + "Shape.Ole.Spreadsheet.docm");

// The first shape will contain an OLE object
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// This object is a Microsoft Excel spreadsheet
OleFormat oleFormat = shape.OleFormat;
Assert.AreEqual("Excel.Sheet.12", oleFormat.ProgId);

// Our object is neither auto updating nor locked from updates
Assert.False(oleFormat.AutoUpdate);
Assert.AreEqual(false, oleFormat.IsLocked);

// If we want to extract the OLE object by saving it into our local file system, this property can tell us the relevant file extension
Assert.AreEqual(".xlsx", oleFormat.SuggestedExtension);

// We can save it via a stream
using (FileStream fs = new FileStream(ArtifactsDir + "OLE spreadsheet extracted via stream" + oleFormat.SuggestedExtension, FileMode.Create))
{
    oleFormat.Save(fs);
}

// We can also save it directly to a file
oleFormat.Save(ArtifactsDir + "OLE spreadsheet saved directly" + oleFormat.SuggestedExtension);

See Also

OleFormat Class | Aspose.Words.Drawing Namespace | OleFormat.Save Overload List


OlePackage Class

Allows to access OLE Package properties.

For a list of all members of this type, see OlePackage Members.

System.Object
Aspose.Words.Drawing.OlePackage

[Visual Basic]
Public Class OlePackage
[C#]
public class OlePackage

Remarks

OLE package is a legacy and "undocumented" way to store embedded object if OLE handler is unknown. Early Windows versions such as Windows 3.1, 95 and 98 had Packager.exe application which could be used to embed any type of data into document. Now this application is excluded from Windows but MS Word and other applications still use it to embed data if OLE handler is missing or unknown.

Example

Shows how insert ole object as ole package and set it file name and display name.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

byte[] zipFileBytes = File.ReadAllBytes(DatabaseDir + "cat001.zip");

using (MemoryStream stream = new MemoryStream(zipFileBytes))
{
    Shape shape = builder.InsertOleObject(stream, "Package", true, null);

    OlePackage setOlePackage = shape.OleFormat.OlePackage;
    setOlePackage.FileName = "Cat FileName.zip";
    setOlePackage.DisplayName = "Cat DisplayName.zip";

    doc.Save(ArtifactsDir + "Shape.InsertOlePackage.docx");
}

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OlePackage Members | Aspose.Words.Drawing Namespace


OlePackage Members

OlePackage overview

Public Instance Properties

DisplayName | Gets or sets OLE Package display name.
FileName | Gets or sets OLE Package file name.

See Also

OlePackage Class | Aspose.Words.Drawing Namespace


OlePackage Properties

The properties of the OlePackage class are listed below. For a complete list of OlePackage class members, see the OlePackage Members topic.

Public Instance Properties

DisplayName | Gets or sets OLE Package display name.
FileName | Gets or sets OLE Package file name.

See Also

OlePackage Class | Aspose.Words.Drawing Namespace


DisplayName Property

Aspose.Words

OlePackage.DisplayName Property

Gets or sets OLE Package display name.

[Visual Basic]
Public Property DisplayName As String
[C#]
public string DisplayName {get; set;}

Example

Shows how insert ole object as ole package and set it file name and display name.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

byte[] zipFileBytes = File.ReadAllBytes(DatabaseDir + "cat001.zip");

using (MemoryStream stream = new MemoryStream(zipFileBytes))
{
    Shape shape = builder.InsertOleObject(stream, "Package", true, null);

    OlePackage setOlePackage = shape.OleFormat.OlePackage;
    setOlePackage.FileName = "Cat FileName.zip";
    setOlePackage.DisplayName = "Cat DisplayName.zip";

    doc.Save(ArtifactsDir + "Shape.InsertOlePackage.docx");
}

See Also

OlePackage Class | Aspose.Words.Drawing Namespace


FileName Property

Aspose.Words

OlePackage.FileName Property

Gets or sets OLE Package file name.

[Visual Basic]
Public Property FileName As String
[C#]
public string FileName {get; set;}

Example

Shows how insert ole object as ole package and set it file name and display name.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

byte[] zipFileBytes = File.ReadAllBytes(DatabaseDir + "cat001.zip");

using (MemoryStream stream = new MemoryStream(zipFileBytes))
{
    Shape shape = builder.InsertOleObject(stream, "Package", true, null);

    OlePackage setOlePackage = shape.OleFormat.OlePackage;
    setOlePackage.FileName = "Cat FileName.zip";
    setOlePackage.DisplayName = "Cat DisplayName.zip";

    doc.Save(ArtifactsDir + "Shape.InsertOlePackage.docx");
}

See Also

OlePackage Class | Aspose.Words.Drawing Namespace


RelativeHorizontalPosition Enumeration

Specifies to what the horizontal position of a shape or text frame is relative.

[Visual Basic]
Public Enum RelativeHorizontalPosition
[C#]
public enum RelativeHorizontalPosition

Remarks

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");
Inserts a watermark image into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");

Members

Member Name | Description | Value
Margin | Specifies that the horizontal positioning shall be relative to the page margins. | 0
Page | The object is positioned relative to the left edge of the page. | 1
Column | The object is positioned relative to the left side of the column. | 2
Character | The object is positioned relative to the left side of the paragraph. | 3
LeftMargin | Specifies that the horizontal positioning shall be relative to the left margin of the page. | 4
RightMargin | Specifies that the horizontal positioning shall be relative to the right margin of the page. | 5
InsideMargin | Specifies that the horizontal positioning shall be relative to the inside margin of the current page (the left margin on odd pages, right on even pages). | 6
OutsideMargin | Specifies that the horizontal positioning shall be relative to the outside margin of the current page (the right margin on odd pages, left on even pages). | 7
Default | Default value is Column. | 2

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | RelativeHorizontalPosition


RelativeVerticalPosition Enumeration

Specifies to what the vertical position of a shape or text frame is relative.

[Visual Basic]
Public Enum RelativeVerticalPosition
[C#]
public enum RelativeVerticalPosition

Remarks

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");
Inserts a watermark image into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");

Members

Member Name | Description | Value
Margin | Specifies that the vertical positioning shall be relative to the page margins. | 0
Page | The object is positioned relative to the top edge of the page. | 1
Paragraph | The object is positioned relative to the top of the paragraph that contains the anchor. | 2
Line | Undocumented. | 3
TopMargin | Specifies that the vertical positioning shall be relative to the top margin of the current page. | 4
BottomMargin | Specifies that the vertical positioning shall be relative to the bottom margin of the current page. | 5
InsideMargin | Specifies that the vertical positioning shall be relative to the inside margin of the current page. | 6
OutsideMargin | Specifies that the vertical positioning shall be relative to the outside margin of the current page. | 7
TableDefault | Default value is Margin. | 0
TextFrameDefault | Default value is Paragraph. | 2

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | RelativeVerticalPosition


Shape Class

Represents an object in the drawing layer, such as an AutoShape, textbox, freeform, OLE object, ActiveX control, or picture.

For a list of all members of this type, see Shape Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Drawing.ShapeBase
Aspose.Words.Drawing.Shape

[Visual Basic]
NotInheritable Public Class Shape
Inherits ShapeBase
[C#]
public sealed class Shape : ShapeBase

Remarks

Using the Shape class you can create or modify shapes in a Microsoft Word document.

An important property of a shape is its ShapeType. Shapes of different types can have different capabilities in a Word document. For example, only image and OLE shapes can have images inside them. Most of the shapes can have text, but not all.

Shapes that can have text, can contain Paragraph and Table nodes as children.

Example

Shows how to delete all shapes from a document.

[C#]

// Here we get all shapes from the document node, but you can do this for any smaller
// node too, for example delete shapes from a single section or a paragraph.
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
shapes.Clear();

// There could also be group shapes, they have different node type, remove them all too.
NodeCollection groupShapes = doc.GetChildNodes(NodeType.GroupShape, true);
groupShapes.Clear();
Shows how to extract images from a document and save them as files.
[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}
Shows how to insert a floating image in the middle of a page.
[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Shape Members | Aspose.Words.Drawing Namespace | ShapeBase | GroupShape


Shape Members

Shape overview

Public Instance Constructors

Shape Constructor Creates a new shape object.

Public Instance Properties

AllowOverlap (inherited from ShapeBase) | Gets or sets a value that specifies whether this shape can overlap other shapes.
AlternativeText (inherited from ShapeBase) | Defines alternative text to be displayed instead of a graphic.
AnchorLocked (inherited from ShapeBase) | Specifies whether the shape's anchor is locked.
AspectRatioLocked (inherited from ShapeBase) | Specifies whether the shape's aspect ratio is locked.
BehindText (inherited from ShapeBase) | Specifies whether the shape is below or above text.
Bottom (inherited from ShapeBase) | Gets the position of the bottom edge of the containing block of the shape.
Bounds (inherited from ShapeBase) | Gets or sets the location and size of the containing block of the shape.
BoundsInPoints (inherited from ShapeBase) | Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.
BoundsWithEffects (inherited from ShapeBase) | Gets final extent that this shape object has after applying drawing effects. Value is measured in points.
CanHaveImage (inherited from ShapeBase) | Returns true if the shape type allows the shape to have an image.
Chart | Provides access to the chart properties if this shape has a Chart.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CoordOrigin (inherited from ShapeBase) | The coordinates at the top-left corner of the containing block of this shape.
CoordSize (inherited from ShapeBase) | The width and height of the coordinate space inside the containing block of this shape.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DistanceBottom (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the bottom edge of the shape.
DistanceLeft (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the left edge of the shape.
DistanceRight (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the right edge of the shape.
DistanceTop (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the top edge of the shape.
Document (inherited from Node) | Gets the document to which this node belongs.
ExtrusionEnabled | Returns true if an extrusion effect is enabled.
Fill | Defines a fill for a shape.
FillColor | Defines the brush color that fills the closed path of the shape.
Filled | Determines whether the closed path of the shape will be filled.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph in the shape.
FlipOrientation (inherited from ShapeBase) | Switches the orientation of a shape.
Font (inherited from ShapeBase) | Provides access to the font formatting of this object.
HasChart | Returns true if this Shape has a Chart.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HasImage | Returns true if the shape has image bytes or links an image.
HasSmartArt | Returns true if this Shape has a SmartArt object.
Height (inherited from ShapeBase) | Gets or sets the height of the containing block of the shape.
HorizontalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned horizontally.
HRef (inherited from ShapeBase) | Gets or sets the full hyperlink address for a shape.
ImageData | Provides access to the image of the shape. Returns null if the shape cannot have an image.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from ShapeBase) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsGroup (inherited from ShapeBase) | Returns true if this is a group shape.
IsHorizontalRule (inherited from ShapeBase) | Returns true if this shape is a horizontal rule.
IsImage (inherited from ShapeBase) | Returns true if this shape is an image shape.
IsInline (inherited from ShapeBase) | A quick way to determine if this shape is positioned inline with text.
IsInsertRevision (inherited from ShapeBase) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLayoutInCell (inherited from ShapeBase) | Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.
IsMoveFromRevision (inherited from ShapeBase) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from ShapeBase) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
IsSignatureLine (inherited from ShapeBase) | Indicates that shape is a SignatureLine.
IsTopLevel (inherited from ShapeBase) | Returns true if this shape is not a child of a group shape.
IsWordArt (inherited from ShapeBase) | Returns true if this shape is a WordArt object.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph in the shape.
Left (inherited from ShapeBase) | Gets or sets the position of the left edge of the containing block of the shape.
MarkupLanguage (inherited from ShapeBase) | Gets MarkupLanguage used for this graphic object.
Name (inherited from ShapeBase) | Gets or sets the optional shape name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns Shape.
OleFormat | Provides access to the OLE data of a shape. For a shape that is not an OLE object or ActiveX control, returns null.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from ShapeBase) | Returns the immediate parent paragraph.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned horizontally.
RelativeVerticalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned vertically.
Right (inherited from ShapeBase) | Gets the position of the right edge of the containing block of the shape.
Rotation (inherited from ShapeBase) | Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.
ScreenTip (inherited from ShapeBase) | Defines the text displayed when the mouse pointer moves over the shape.
ShadowEnabled | Returns true if a shadow effect is enabled.
ShapeType (inherited from ShapeBase) | Gets the shape type.
SignatureLine | Gets SignatureLine object if the shape is a signature line. Returns null otherwise.
SizeInPoints (inherited from ShapeBase) | Gets the size of the shape in points.
StoryType | Returns Textbox.
Stroke | Defines a stroke for a shape.
StrokeColor | Defines the color of a stroke.
Stroked | Defines whether the path will be stroked.
StrokeWeight | Defines the brush thickness that strokes the path of a shape in points.
Target (inherited from ShapeBase) | Gets or sets the target frame for the shape hyperlink.
TextBox | Defines attributes that specify how text is displayed in a shape.
TextPath | Defines the text of the text path (of a WordArt object).
Title (inherited from ShapeBase) | Gets or sets the title (caption) of the current shape object.
Top (inherited from ShapeBase) | Gets or sets the position of the top edge of the containing block of the shape.
VerticalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned vertically.
Width (inherited from ShapeBase) | Gets or sets the width of the containing block of the shape.
WrapSide (inherited from ShapeBase) | Specifies how the text is wrapped around the shape.
WrapType (inherited from ShapeBase) | Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.
ZOrder (inherited from ShapeBase) | Determines the display order of overlapping shapes.

Public Instance Methods

Accept | Accepts a visitor.
AdjustWithEffects (inherited from ShapeBase) | Adds to the source rectangle values of the effect extent and returns the final rectangle.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetShapeRenderer (inherited from ShapeBase) | Creates and returns an object that can be used to render this shape into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
LocalToParent (inherited from ShapeBase) | Converts a value from the local coordinate space into the coordinate space of the parent shape.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Shape Class | Aspose.Words.Drawing Namespace | ShapeBase | GroupShape


Shape Constructor

Creates a new shape object.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal shapeType As ShapeType _
)
[C#]
public Shape(
DocumentBase doc,
ShapeType shapeType
);

Parameters

doc
The owner document.
shapeType
The type of the shape to create.

Remarks

You should specify desired shape properties after you created a shape.

Example

Shows how to create and add an image to a document without using document builder.

[C#]

Document doc = new Document();

Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(MyDir + "Images/Hammer.wmf");
shape.Width = 100;
shape.Height = 100;

doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

doc.Save(ArtifactsDir + "Image.CreateImageDirectly.doc");
Creates a textbox with some text and different formatting options in a new document.
[C#]

// Create a blank document.
Document doc = new Document();

// Create a new shape of type TextBox
Shape textBox = new Shape(doc, ShapeType.TextBox);

// Set some settings of the textbox itself.
// Set the wrap of the textbox to inline
textBox.WrapType = WrapType.None;
// Set the horizontal and vertical alignment of the text inside the shape.
textBox.HorizontalAlignment = HorizontalAlignment.Center;
textBox.VerticalAlignment = VerticalAlignment.Top;

// Set the textbox height and width.
textBox.Height = 50;
textBox.Width = 200;

// Set the textbox in front of other shapes with a lower ZOrder
textBox.ZOrder = 2;

// Let's create a new paragraph for the textbox manually and align it in the center. Make sure we add the new nodes to the textbox as well.
textBox.AppendChild(new Paragraph(doc));
Paragraph para = textBox.FirstParagraph;
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Add some text to the paragraph.
Run run = new Run(doc);
run.Text = "Content in textbox";
para.AppendChild(run);

// Append the textbox to the first paragraph in the body.
doc.FirstSection.Body.FirstParagraph.AppendChild(textBox);

// Save the output
doc.Save(ArtifactsDir + "Shape.CreateTextBox.doc");

See Also

Shape Class | Aspose.Words.Drawing Namespace


Shape Properties

The properties of the Shape class are listed below. For a complete list of Shape class members, see the Shape Members topic.

Public Instance Properties

AllowOverlap (inherited from ShapeBase) | Gets or sets a value that specifies whether this shape can overlap other shapes.
AlternativeText (inherited from ShapeBase) | Defines alternative text to be displayed instead of a graphic.
AnchorLocked (inherited from ShapeBase) | Specifies whether the shape's anchor is locked.
AspectRatioLocked (inherited from ShapeBase) | Specifies whether the shape's aspect ratio is locked.
BehindText (inherited from ShapeBase) | Specifies whether the shape is below or above text.
Bottom (inherited from ShapeBase) | Gets the position of the bottom edge of the containing block of the shape.
Bounds (inherited from ShapeBase) | Gets or sets the location and size of the containing block of the shape.
BoundsInPoints (inherited from ShapeBase) | Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.
BoundsWithEffects (inherited from ShapeBase) | Gets final extent that this shape object has after applying drawing effects. Value is measured in points.
CanHaveImage (inherited from ShapeBase) | Returns true if the shape type allows the shape to have an image.
Chart | Provides access to the chart properties if this shape has a Chart.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CoordOrigin (inherited from ShapeBase) | The coordinates at the top-left corner of the containing block of this shape.
CoordSize (inherited from ShapeBase) | The width and height of the coordinate space inside the containing block of this shape.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DistanceBottom (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the bottom edge of the shape.
DistanceLeft (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the left edge of the shape.
DistanceRight (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the right edge of the shape.
DistanceTop (inherited from ShapeBase) | Returns or sets the distance (in points) between the document text and the top edge of the shape.
Document (inherited from Node) | Gets the document to which this node belongs.
ExtrusionEnabled | Returns true if an extrusion effect is enabled.
Fill | Defines a fill for a shape.
FillColor | Defines the brush color that fills the closed path of the shape.
Filled | Determines whether the closed path of the shape will be filled.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph in the shape.
FlipOrientation (inherited from ShapeBase) | Switches the orientation of a shape.
Font (inherited from ShapeBase) | Provides access to the font formatting of this object.
HasChart | Returns true if this Shape has a Chart.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HasImage | Returns true if the shape has image bytes or links an image.
HasSmartArt | Returns true if this Shape has a SmartArt object.
Height (inherited from ShapeBase) | Gets or sets the height of the containing block of the shape.
HorizontalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned horizontally.
HRef (inherited from ShapeBase) | Gets or sets the full hyperlink address for a shape.
ImageData | Provides access to the image of the shape. Returns null if the shape cannot have an image.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision (inherited from ShapeBase) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsGroup (inherited from ShapeBase) | Returns true if this is a group shape.
IsHorizontalRule (inherited from ShapeBase) | Returns true if this shape is a horizontal rule.
IsImage (inherited from ShapeBase) | Returns true if this shape is an image shape.
IsInline (inherited from ShapeBase) | A quick way to determine if this shape is positioned inline with text.
IsInsertRevision (inherited from ShapeBase) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLayoutInCell (inherited from ShapeBase) | Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.
IsMoveFromRevision (inherited from ShapeBase) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from ShapeBase) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
IsSignatureLine (inherited from ShapeBase) | Indicates that shape is a SignatureLine.
IsTopLevel (inherited from ShapeBase) | Returns true if this shape is not a child of a group shape.
IsWordArt (inherited from ShapeBase) | Returns true if this shape is a WordArt object.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph in the shape.
Left (inherited from ShapeBase) | Gets or sets the position of the left edge of the containing block of the shape.
MarkupLanguage (inherited from ShapeBase) | Gets MarkupLanguage used for this graphic object.
Name (inherited from ShapeBase) | Gets or sets the optional shape name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns Shape.
OleFormat | Provides access to the OLE data of a shape. For a shape that is not an OLE object or ActiveX control, returns null.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from ShapeBase) | Returns the immediate parent paragraph.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned horizontally.
RelativeVerticalPosition (inherited from ShapeBase) | Specifies relative to what the shape is positioned vertically.
Right (inherited from ShapeBase) | Gets the position of the right edge of the containing block of the shape.
Rotation (inherited from ShapeBase) | Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.
ScreenTip (inherited from ShapeBase) | Defines the text displayed when the mouse pointer moves over the shape.
ShadowEnabled | Returns true if a shadow effect is enabled.
ShapeType (inherited from ShapeBase) | Gets the shape type.
SignatureLine | Gets SignatureLine object if the shape is a signature line. Returns null otherwise.
SizeInPoints (inherited from ShapeBase) | Gets the size of the shape in points.
StoryType | Returns Textbox.
Stroke | Defines a stroke for a shape.
StrokeColor | Defines the color of a stroke.
Stroked | Defines whether the path will be stroked.
StrokeWeight | Defines the brush thickness that strokes the path of a shape in points.
Target (inherited from ShapeBase) | Gets or sets the target frame for the shape hyperlink.
TextBox | Defines attributes that specify how text is displayed in a shape.
TextPath | Defines the text of the text path (of a WordArt object).
Title (inherited from ShapeBase) | Gets or sets the title (caption) of the current shape object.
Top (inherited from ShapeBase) | Gets or sets the position of the top edge of the containing block of the shape.
VerticalAlignment (inherited from ShapeBase) | Specifies how the shape is positioned vertically.
Width (inherited from ShapeBase) | Gets or sets the width of the containing block of the shape.
WrapSide (inherited from ShapeBase) | Specifies how the text is wrapped around the shape.
WrapType (inherited from ShapeBase) | Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.
ZOrder (inherited from ShapeBase) | Determines the display order of overlapping shapes.

See Also

Shape Class | Aspose.Words.Drawing Namespace | ShapeBase | GroupShape


Chart Property

Aspose.Words

Shape.Chart Property

Provides access to the chart properties if this shape has a Chart.

[Visual Basic]
Public ReadOnly Property Chart As Chart
[C#]
public Chart Chart {get;}

Remarks

This property will return the Chart object only if HasChart property is true for this Shape, and will throw an exception otherwise.

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


ExtrusionEnabled Property

Aspose.Words

Shape.ExtrusionEnabled Property

Returns true if an extrusion effect is enabled.

[Visual Basic]
Public ReadOnly Property ExtrusionEnabled As Boolean
[C#]
public bool ExtrusionEnabled {get;}

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


Fill Property

Aspose.Words

Shape.Fill Property

Defines a fill for a shape.

[Visual Basic]
Public ReadOnly Property Fill As Fill
[C#]
public Fill Fill {get;}

Example

Demonstrates how to create shapes with fill.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln();
builder.Writeln();
builder.Writeln();
builder.Write("Some text under the shape.");

// Create a red balloon, semitransparent.
// The shape is floating and its coordinates are (0,0) by default, relative to the current paragraph.
Shape shape = new Shape(builder.Document, ShapeType.Balloon);
shape.FillColor = Color.Red;
shape.Fill.Opacity = 0.3;
shape.Width = 100;
shape.Height = 100;
shape.Top = -100;
builder.InsertNode(shape);

builder.Document.Save(ArtifactsDir + "Shape.Fill.doc");

See Also

Shape Class | Aspose.Words.Drawing Namespace


FillColor Property

Aspose.Words

Shape.FillColor Property

Defines the brush color that fills the closed path of the shape.

[Visual Basic]
Public Property FillColor As Color
[C#]
public Color FillColor {get; set;}

Remarks

This is a shortcut to the Color property.

The default value is White.

Example

Demonstrates how to create shapes with fill.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.Writeln();
builder.Writeln();
builder.Writeln();
builder.Write("Some text under the shape.");

// Create a red balloon, semitransparent.
// The shape is floating and its coordinates are (0,0) by default, relative to the current paragraph.
Shape shape = new Shape(builder.Document, ShapeType.Balloon);
shape.FillColor = Color.Red;
shape.Fill.Opacity = 0.3;
shape.Width = 100;
shape.Height = 100;
shape.Top = -100;
builder.InsertNode(shape);

builder.Document.Save(ArtifactsDir + "Shape.Fill.doc");

See Also

Shape Class | Aspose.Words.Drawing Namespace


Filled Property

Aspose.Words

Shape.Filled Property

Determines whether the closed path of the shape will be filled.

[Visual Basic]
Public Property Filled As Boolean
[C#]
public bool Filled {get; set;}

Remarks

This is a shortcut to the On property.

The default value is true.

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


FirstParagraph Property

Aspose.Words

Shape.FirstParagraph Property

Gets the first paragraph in the shape.

[Visual Basic]
Public ReadOnly Property FirstParagraph As Paragraph
[C#]
public Paragraph FirstParagraph {get;}

Example

Creates a textbox with some text and different formatting options in a new document.

[C#]

// Create a blank document.
Document doc = new Document();

// Create a new shape of type TextBox
Shape textBox = new Shape(doc, ShapeType.TextBox);

// Set some settings of the textbox itself.
// Set the wrap of the textbox to inline
textBox.WrapType = WrapType.None;
// Set the horizontal and vertical alignment of the text inside the shape.
textBox.HorizontalAlignment = HorizontalAlignment.Center;
textBox.VerticalAlignment = VerticalAlignment.Top;

// Set the textbox height and width.
textBox.Height = 50;
textBox.Width = 200;

// Set the textbox in front of other shapes with a lower ZOrder
textBox.ZOrder = 2;

// Let's create a new paragraph for the textbox manually and align it in the center. Make sure we add the new nodes to the textbox as well.
textBox.AppendChild(new Paragraph(doc));
Paragraph para = textBox.FirstParagraph;
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Add some text to the paragraph.
Run run = new Run(doc);
run.Text = "Content in textbox";
para.AppendChild(run);

// Append the textbox to the first paragraph in the body.
doc.FirstSection.Body.FirstParagraph.AppendChild(textBox);

// Save the output
doc.Save(ArtifactsDir + "Shape.CreateTextBox.doc");

See Also

Shape Class | Aspose.Words.Drawing Namespace


HasChart Property

Aspose.Words

Shape.HasChart Property

Returns true if this Shape has a Chart.

[Visual Basic]
Public ReadOnly Property HasChart As Boolean
[C#]
public bool HasChart {get;}

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


HasImage Property

Aspose.Words

Shape.HasImage Property

Returns true if the shape has image bytes or links an image.

[Visual Basic]
Public ReadOnly Property HasImage As Boolean
[C#]
public bool HasImage {get;}

Example

Shows how to extract images from a document and save them as files.

[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}
Shows how to delete all images from a document.
[C#]

// Here we get all shapes from the document node, but you can do this for any smaller
// node too, for example delete shapes from a single section or a paragraph.
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

// We cannot delete shape nodes while we enumerate through the collection.
// One solution is to add nodes that we want to delete to a temporary array and delete afterwards.
ArrayList shapesToDelete = new ArrayList();
foreach (Shape shape in shapes.OfType<Shape>())
{
    // Several shape types can have an image including image shapes and OLE objects.
    if (shape.HasImage)
        shapesToDelete.Add(shape);
}

// Now we can delete shapes.
foreach (Shape shape in shapesToDelete)
    shape.Remove();

See Also

Shape Class | Aspose.Words.Drawing Namespace


HasSmartArt Property

Aspose.Words

Shape.HasSmartArt Property

Returns true if this Shape has a SmartArt object.

[Visual Basic]
Public ReadOnly Property HasSmartArt As Boolean
[C#]
public bool HasSmartArt {get;}

See Also

Shape Class | Aspose.Words.Drawing Namespace


ImageData Property

Aspose.Words

Shape.ImageData Property

Provides access to the image of the shape. Returns null if the shape cannot have an image.

[Visual Basic]
Public ReadOnly Property ImageData As ImageData
[C#]
public ImageData ImageData {get;}

Example

Shows how to extract images from a document and save them as files.

[C#]

public void ExtractImagesToFiles()
{
    Document doc = new Document(MyDir + "Image.SampleImages.doc");

    NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
    int imageIndex = 0;
    foreach (Shape shape in shapes.OfType<Shape>())
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format("Image.ExportImages.{0}{1}", imageIndex,
                FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(ArtifactsDir + imageFileName);
            imageIndex++;
        }
    }
}
Shows how to insert a linked image into a document.
[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "Images/Hammer.wmf";

builder.Write("Image linked, not stored in the document: ");

Shape linkedOnly = new Shape(builder.Document, ShapeType.Image);
linkedOnly.WrapType = WrapType.Inline;
linkedOnly.ImageData.SourceFullName = imageFileName;

builder.InsertNode(linkedOnly);
builder.Writeln();

builder.Write("Image linked and stored in the document: ");

Shape linkedAndStored = new Shape(builder.Document, ShapeType.Image);
linkedAndStored.WrapType = WrapType.Inline;
linkedAndStored.ImageData.SourceFullName = imageFileName;
linkedAndStored.ImageData.SetImage(imageFileName);

builder.InsertNode(linkedAndStored);
builder.Writeln();

builder.Write("Image stored in the document, but not linked: ");

Shape stored = new Shape(builder.Document, ShapeType.Image);
stored.WrapType = WrapType.Inline;
stored.ImageData.SetImage(imageFileName);

builder.InsertNode(stored);
builder.Writeln();

builder.Document.Save(ArtifactsDir + "Image.CreateLinkedImage.doc");

See Also

Shape Class | Aspose.Words.Drawing Namespace


LastParagraph Property

Aspose.Words

Shape.LastParagraph Property

Gets the last paragraph in the shape.

[Visual Basic]
Public ReadOnly Property LastParagraph As Paragraph
[C#]
public Paragraph LastParagraph {get;}

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

Shape Class | Aspose.Words.Drawing Namespace


NodeType Property

Aspose.Words

Shape.NodeType Property

Returns Shape.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Shape Class | Aspose.Words.Drawing Namespace


OleFormat Property

Aspose.Words

Shape.OleFormat Property

Provides access to the OLE data of a shape. For a shape that is not an OLE object or ActiveX control, returns null.

[Visual Basic]
Public ReadOnly Property OleFormat As OleFormat
[C#]
public OleFormat OleFormat {get;}

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


ShadowEnabled Property

Aspose.Words

Shape.ShadowEnabled Property

Returns true if a shadow effect is enabled.

[Visual Basic]
Public ReadOnly Property ShadowEnabled As Boolean
[C#]
public bool ShadowEnabled {get;}

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


SignatureLine Property

Aspose.Words

Shape.SignatureLine Property

Gets SignatureLine object if the shape is a signature line. Returns null otherwise.

[Visual Basic]
Public ReadOnly Property SignatureLine As SignatureLine
[C#]
public SignatureLine SignatureLine {get;}

Remarks

You can insert new SignatureLines into the document using InsertSignatureLine and

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

Shape Class | Aspose.Words.Drawing Namespace | InsertSignatureLine


StoryType Property

Aspose.Words

Shape.StoryType Property

Returns Textbox.

[Visual Basic]
Public ReadOnly Property StoryType As StoryType
[C#]
public StoryType StoryType {get;}

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


Stroke Property

Aspose.Words

Shape.Stroke Property

Defines a stroke for a shape.

[Visual Basic]
Public ReadOnly Property Stroke As Stroke
[C#]
public Stroke Stroke {get;}

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Shape Class | Aspose.Words.Drawing Namespace


StrokeColor Property

Aspose.Words

Shape.StrokeColor Property

Defines the color of a stroke.

[Visual Basic]
Public Property StrokeColor As Color
[C#]
public Color StrokeColor {get; set;}

Remarks

This is a shortcut to the Color property.

The default value is Black.

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


Stroked Property

Aspose.Words

Shape.Stroked Property

Defines whether the path will be stroked.

[Visual Basic]
Public Property Stroked As Boolean
[C#]
public bool Stroked {get; set;}

Remarks

This is a shortcut to the On property.

The default value is true.

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


StrokeWeight Property

Aspose.Words

Shape.StrokeWeight Property

Defines the brush thickness that strokes the path of a shape in points.

[Visual Basic]
Public Property StrokeWeight As Double
[C#]
public double StrokeWeight {get; set;}

Remarks

This is a shortcut to the Weight property.

The default value is 0.75.

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


TextBox Property

Aspose.Words

Shape.TextBox Property

Defines attributes that specify how text is displayed in a shape.

[Visual Basic]
Public ReadOnly Property TextBox As TextBox
[C#]
public TextBox TextBox {get;}

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

Shape Class | Aspose.Words.Drawing Namespace


TextPath Property

Aspose.Words

Shape.TextPath Property

Defines the text of the text path (of a WordArt object).

[Visual Basic]
Public ReadOnly Property TextPath As TextPath
[C#]
public TextPath TextPath {get;}

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


Shape Methods

The methods of the Shape class are listed below. For a complete list of Shape class members, see the Shape Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AdjustWithEffects (inherited from ShapeBase) | Adds to the source rectangle values of the effect extent and returns the final rectangle.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetShapeRenderer (inherited from ShapeBase) | Creates and returns an object that can be used to render this shape into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
LocalToParent (inherited from ShapeBase) | Converts a value from the local coordinate space into the coordinate space of the parent shape.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Shape Class | Aspose.Words.Drawing Namespace | ShapeBase | GroupShape


Shape.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitShapeStart, then calls Accept for all child nodes of the shape and calls VisitShapeEnd at the end.

Example

Shows how to iterate over all the shapes in a document.

[C#]

public void VisitShapes()
{
    // Open a document that contains shapes
    Document doc = new Document(MyDir + "Shape.Revisions.docx");

    // Create a ShapeVisitor and get the document to accept it
    ShapeVisitor shapeVisitor = new ShapeVisitor();
    doc.Accept(shapeVisitor);

    // Print all the information that the visitor has collected
    Console.WriteLine(shapeVisitor.GetText());
}

/// <summary>
/// DocumentVisitor implementation that collects information about visited shapes into a StringBuilder, to be printed to the console
/// </summary>
private class ShapeVisitor : DocumentVisitor
{
    public ShapeVisitor()
    {
        mShapesVisited = 0;
        mTextIndentLevel = 0;
        mStringBuilder = new StringBuilder();
    }

    /// <summary>
    /// Appends a line to the StringBuilder with one prepended tab character for each indent level
    /// </summary>
    private void AppendLine(string text)
    {
        for (int i = 0; i < mTextIndentLevel; i++)
        {
            mStringBuilder.Append('\t');
        }

        mStringBuilder.AppendLine(text);
    }

    /// <summary>
    /// Return all the text that the StringBuilder has accumulated
    /// </summary>
    public string GetText()
    {
        return $"Shapes visited: {mShapesVisited}\n{mStringBuilder}";
    }

    /// <summary>
    /// Called when the start of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        AppendLine($"Shape found: {shape.ShapeType}");

        mTextIndentLevel++;

        if (shape.HasChart)
            AppendLine($"Has chart: {shape.Chart.Title.Text}");

        AppendLine($"Extrusion enabled: {shape.ExtrusionEnabled}");
        AppendLine($"Shadow enabled: {shape.ShadowEnabled}");
        AppendLine($"StoryType: {shape.StoryType}");

        if (shape.Stroked)
        {
            Assert.AreEqual(shape.Stroke.Color, shape.StrokeColor);
            AppendLine($"Stroke colors: {shape.Stroke.Color}, {shape.Stroke.Color2}");
            AppendLine($"Stroke weight: {shape.StrokeWeight}");

        }

        if (shape.Filled)
            AppendLine($"Filled: {shape.FillColor}");

        if (shape.OleFormat != null)
            AppendLine($"Ole found of type: {shape.OleFormat.ProgId}");

        if (shape.SignatureLine != null)
            AppendLine($"Found signature line for: {shape.SignatureLine.Signer}, {shape.SignatureLine.SignerTitle}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a Shape node is visited
    /// </summary>
    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mTextIndentLevel--;
        mShapesVisited++;
        AppendLine($"End of {shape.ShapeType}");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the start of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        AppendLine($"Shape group found: {groupShape.ShapeType}");
        mTextIndentLevel++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the end of a GroupShape node is visited
    /// </summary>
    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mTextIndentLevel--;
        AppendLine($"End of {groupShape.ShapeType}");

        return VisitorAction.Continue;
    }

    private int mShapesVisited;
    private int mTextIndentLevel;
    private readonly StringBuilder mStringBuilder;
}

See Also

Shape Class | Aspose.Words.Drawing Namespace


ShapeBase Class

Base class for objects in the drawing layer, such as an AutoShape, freeform, OLE object, ActiveX control, or picture.

For a list of all members of this type, see ShapeBase Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Drawing.ShapeBase
Aspose.Words.Drawing.GroupShape
Aspose.Words.Drawing.Shape

[Visual Basic]
MustInherit Public Class ShapeBase
Inherits CompositeNode
[C#]
public abstract class ShapeBase : CompositeNode

Remarks

This is an abstract class. The two derived classes that you can instantiate are Shape and GroupShape.

A shape is a node in the document tree.

If the shape is a child of a Paragraph object, then the shape is said to be "top-level". Top-level shapes are measured and positioned in points.

A shape can also occur as a child of a GroupShape object when several shapes are grouped. Child shapes of a group shape are positioned in the coordinate space and units defined by the CoordSize and CoordOrigin properties of the parent group shape.

A shape can be positioned inline with text or floating. The positioning method is controlled using the WrapType property.

When a shape is floating, it is positioned relative to something (e.g the current paragraph, the margin or the page). The relative positioning of the shape is specified using the RelativeHorizontalPosition and RelativeVerticalPosition properties.

A floating shape be positioned explicitly using the Left and Top properties or aligned relative to some other object using the HorizontalAlignment and VerticalAlignment properties.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ShapeBase Members | Aspose.Words.Drawing Namespace | Shape | GroupShape


ShapeBase Members

ShapeBase overview

Public Instance Properties

AllowOverlap | Gets or sets a value that specifies whether this shape can overlap other shapes.
AlternativeText | Defines alternative text to be displayed instead of a graphic.
AnchorLocked | Specifies whether the shape's anchor is locked.
AspectRatioLocked | Specifies whether the shape's aspect ratio is locked.
BehindText | Specifies whether the shape is below or above text.
Bottom | Gets the position of the bottom edge of the containing block of the shape.
Bounds | Gets or sets the location and size of the containing block of the shape.
BoundsInPoints | Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.
BoundsWithEffects | Gets final extent that this shape object has after applying drawing effects. Value is measured in points.
CanHaveImage | Returns true if the shape type allows the shape to have an image.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CoordOrigin | The coordinates at the top-left corner of the containing block of this shape.
CoordSize | The width and height of the coordinate space inside the containing block of this shape.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DistanceBottom | Returns or sets the distance (in points) between the document text and the bottom edge of the shape.
DistanceLeft | Returns or sets the distance (in points) between the document text and the left edge of the shape.
DistanceRight | Returns or sets the distance (in points) between the document text and the right edge of the shape.
DistanceTop | Returns or sets the distance (in points) between the document text and the top edge of the shape.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FlipOrientation | Switches the orientation of a shape.
Font | Provides access to the font formatting of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Height | Gets or sets the height of the containing block of the shape.
HorizontalAlignment | Specifies how the shape is positioned horizontally.
HRef | Gets or sets the full hyperlink address for a shape.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsGroup | Returns true if this is a group shape.
IsHorizontalRule | Returns true if this shape is a horizontal rule.
IsImage | Returns true if this shape is an image shape.
IsInline | A quick way to determine if this shape is positioned inline with text.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLayoutInCell | Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
IsSignatureLine | Indicates that shape is a SignatureLine.
IsTopLevel | Returns true if this shape is not a child of a group shape.
IsWordArt | Returns true if this shape is a WordArt object.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Left | Gets or sets the position of the left edge of the containing block of the shape.
MarkupLanguage | Gets MarkupLanguage used for this graphic object.
Name | Gets or sets the optional shape name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Returns the immediate parent paragraph.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalPosition | Specifies relative to what the shape is positioned horizontally.
RelativeVerticalPosition | Specifies relative to what the shape is positioned vertically.
Right | Gets the position of the right edge of the containing block of the shape.
Rotation | Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.
ScreenTip | Defines the text displayed when the mouse pointer moves over the shape.
ShapeType | Gets the shape type.
SizeInPoints | Gets the size of the shape in points.
Target | Gets or sets the target frame for the shape hyperlink.
Title | Gets or sets the title (caption) of the current shape object.
Top | Gets or sets the position of the top edge of the containing block of the shape.
VerticalAlignment | Specifies how the shape is positioned vertically.
Width | Gets or sets the width of the containing block of the shape.
WrapSide | Specifies how the text is wrapped around the shape.
WrapType | Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.
ZOrder | Determines the display order of overlapping shapes.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AdjustWithEffects | Adds to the source rectangle values of the effect extent and returns the final rectangle.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetShapeRenderer | Creates and returns an object that can be used to render this shape into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
LocalToParent | Converts a value from the local coordinate space into the coordinate space of the parent shape.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace | Shape | GroupShape


ShapeBase Properties

The properties of the ShapeBase class are listed below. For a complete list of ShapeBase class members, see the ShapeBase Members topic.

Public Instance Properties

AllowOverlap | Gets or sets a value that specifies whether this shape can overlap other shapes.
AlternativeText | Defines alternative text to be displayed instead of a graphic.
AnchorLocked | Specifies whether the shape's anchor is locked.
AspectRatioLocked | Specifies whether the shape's aspect ratio is locked.
BehindText | Specifies whether the shape is below or above text.
Bottom | Gets the position of the bottom edge of the containing block of the shape.
Bounds | Gets or sets the location and size of the containing block of the shape.
BoundsInPoints | Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.
BoundsWithEffects | Gets final extent that this shape object has after applying drawing effects. Value is measured in points.
CanHaveImage | Returns true if the shape type allows the shape to have an image.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
CoordOrigin | The coordinates at the top-left corner of the containing block of this shape.
CoordSize | The width and height of the coordinate space inside the containing block of this shape.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DistanceBottom | Returns or sets the distance (in points) between the document text and the bottom edge of the shape.
DistanceLeft | Returns or sets the distance (in points) between the document text and the left edge of the shape.
DistanceRight | Returns or sets the distance (in points) between the document text and the right edge of the shape.
DistanceTop | Returns or sets the distance (in points) between the document text and the top edge of the shape.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FlipOrientation | Switches the orientation of a shape.
Font | Provides access to the font formatting of this object.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Height | Gets or sets the height of the containing block of the shape.
HorizontalAlignment | Specifies how the shape is positioned horizontally.
HRef | Gets or sets the full hyperlink address for a shape.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsDeleteRevision | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsGroup | Returns true if this is a group shape.
IsHorizontalRule | Returns true if this shape is a horizontal rule.
IsImage | Returns true if this shape is an image shape.
IsInline | A quick way to determine if this shape is positioned inline with text.
IsInsertRevision | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLayoutInCell | Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.
IsMoveFromRevision | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
IsSignatureLine | Indicates that shape is a SignatureLine.
IsTopLevel | Returns true if this shape is not a child of a group shape.
IsWordArt | Returns true if this shape is a WordArt object.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Left | Gets or sets the position of the left edge of the containing block of the shape.
MarkupLanguage | Gets MarkupLanguage used for this graphic object.
Name | Gets or sets the optional shape name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from Node) | Gets the type of this node.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Returns the immediate parent paragraph.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalPosition | Specifies relative to what the shape is positioned horizontally.
RelativeVerticalPosition | Specifies relative to what the shape is positioned vertically.
Right | Gets the position of the right edge of the containing block of the shape.
Rotation | Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.
ScreenTip | Defines the text displayed when the mouse pointer moves over the shape.
ShapeType | Gets the shape type.
SizeInPoints | Gets the size of the shape in points.
Target | Gets or sets the target frame for the shape hyperlink.
Title | Gets or sets the title (caption) of the current shape object.
Top | Gets or sets the position of the top edge of the containing block of the shape.
VerticalAlignment | Specifies how the shape is positioned vertically.
Width | Gets or sets the width of the containing block of the shape.
WrapSide | Specifies how the text is wrapped around the shape.
WrapType | Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.
ZOrder | Determines the display order of overlapping shapes.

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace | Shape | GroupShape


AllowOverlap Property

Aspose.Words

ShapeBase.AllowOverlap Property

Gets or sets a value that specifies whether this shape can overlap other shapes.

[Visual Basic]
Public Property AllowOverlap As Boolean
[C#]
public bool AllowOverlap {get; set;}

Remarks

This property affects behavior of the shape in Microsoft Word. Aspose.Words ignores the value of this property.

This property is applicable only to top level shapes.

The default value is true.

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


AlternativeText Property

Aspose.Words

ShapeBase.AlternativeText Property

Defines alternative text to be displayed instead of a graphic.

[Visual Basic]
Public Property AlternativeText As String
[C#]
public string AlternativeText {get; set;}

Remarks

The default value is an empty string.

Example

Shows how to insert shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a cube and set its name
Shape shape = builder.InsertShape(ShapeType.Cube, 150, 150);
shape.Name = "MyCube";

// We can also set the alt text like this
// This text will be found in Format AutoShape > Alt Text
shape.AlternativeText = "Alt text for MyCube.";

// Insert a text box
shape = builder.InsertShape(ShapeType.TextBox, 300, 50);
shape.Font.Name = "Times New Roman";

// Move the builder into the text box and write text
builder.MoveTo(shape.LastParagraph);
builder.Write("Hello world!");

// Move the builder out of the text box back into the main document
builder.MoveTo(shape.ParentParagraph);

// Insert a shape with an image
shape = builder.InsertImage(Image.FromFile(ImageDir + "Aspose.Words.gif"));
Assert.True(shape.CanHaveImage);
Assert.True(shape.HasImage);

// Rotate the image
shape.Rotation = 45.0;

doc.Save(ArtifactsDir + "Shape.InsertShapes.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


AnchorLocked Property

Aspose.Words

ShapeBase.AnchorLocked Property

Specifies whether the shape's anchor is locked.

[Visual Basic]
Public Property AnchorLocked As Boolean
[C#]
public bool AnchorLocked {get; set;}

Remarks

The default value is false.

Has effect only for top level shapes.

This property affects behavior of the shape's anchor in Microsoft Word. When the anchor is not locked, moving the shape in Microsoft Word can move the shape's anchor too.

Example

Shows how to create and work with a group of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Every GroupShape is top level
GroupShape group = new GroupShape(doc);
Assert.True(group.IsGroup);
Assert.True(group.IsTopLevel);

// And it is a floating shape too, so we can set its coordinates independently of the text
Assert.AreEqual(WrapType.None, group.WrapType);

// Make it a floating shape
group.WrapType = WrapType.None;

// Top level shapes can have this property changed
group.AnchorLocked = true;

// Set the XY coordinates of the shape group and the size of its containing block, as it appears on the page
group.Bounds = new RectangleF(100, 50, 200, 100);

// Set the scale of the inner coordinates of the shape group
// These values mean that the bottom right corner of the 200x100 outer block we set before
// will be at x = 2000 and y = 1000, or 2000 units from the left and 1000 units from the top
group.CoordSize = new Size(2000, 1000);

// The coordinate origin of a shape group is x = 0, y = 0 by default, which is the top left corner
// If we insert a child shape and set its distance from the left to 2000 and the distance from the top to 1000,
// its origin will be at the bottom right corner of the shape group
// We can offset the coordinate origin by setting the CoordOrigin attribute
// In this instance, we move the origin to the centre of the shape group
group.CoordOrigin = new Point(-1000, -500);

// Populate the shape group with child shapes
// First, insert a rectangle
Shape subShape = new Shape(doc, ShapeType.Rectangle);
subShape.Width = 500;
subShape.Height = 700;

// Place its top left corner at the parent group's coordinate origin, which is currently at its centre
subShape.Left = 0;
subShape.Top = 0;

// Add the rectangle to the group
group.AppendChild(subShape);

// Insert a triangle
subShape = new Shape(doc, ShapeType.Triangle);
subShape.Width = 400;
subShape.Height = 400;

// Place its origin at the bottom right corner of the group
subShape.Left = 1000;
subShape.Top = 500;

// The offset between this child shape and parent group can be seen here
Assert.AreEqual(new PointF(1000, 500), subShape.LocalToParent(new PointF(0, 0)));

// Add the triangle to the group
group.AppendChild(subShape);

// Child shapes of a group shape are not top level
Assert.False(subShape.IsTopLevel);

// Finally, insert the group into the document and save
builder.InsertNode(group);
doc.Save(ArtifactsDir + "Shape.InsertGroupShape.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


AspectRatioLocked Property

Aspose.Words

ShapeBase.AspectRatioLocked Property

Specifies whether the shape's aspect ratio is locked.

[Visual Basic]
Public Property AspectRatioLocked As Boolean
[C#]
public bool AspectRatioLocked {get; set;}

Remarks

The default value depends on the ShapeType, for the ShapeType.Image it is true but for the other shape types it is false.

Has effect for top level shapes only.

Example

Shows how to set "AspectRatioLocked" for the shape object

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

// Get shape object from the document and set AspectRatioLocked(it is possible to get/set AspectRatioLocked for child shapes (mimic MS Word behavior),
// but AspectRatioLocked has effect only for top level shapes!)
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
shape.AspectRatioLocked = isLocked;

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


BehindText Property

Aspose.Words

ShapeBase.BehindText Property

Specifies whether the shape is below or above text.

[Visual Basic]
Public Property BehindText As Boolean
[C#]
public bool BehindText {get; set;}

Remarks

Has effect only for top level shapes.

The default value is false.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace | ZOrder


Bottom Property

Aspose.Words

ShapeBase.Bottom Property

Gets the position of the bottom edge of the containing block of the shape.

[Visual Basic]
Public ReadOnly Property Bottom As Double
[C#]
public double Bottom {get;}

Remarks

For a top-level shape, the value is in points and relative to the shape anchor.

For shapes in a group, the value is in the coordinate space and units of the parent group.

Example

Shows how to insert a floating image and specify its position and size.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Bounds Property

Aspose.Words

ShapeBase.Bounds Property

Gets or sets the location and size of the containing block of the shape.

[Visual Basic]
Public Property Bounds As RectangleF
[C#]
public RectangleF Bounds {get; set;}

Remarks

Ignores aspect ratio lock upon setting.

For a top-level shape, the value is in points and relative to the shape anchor.

For shapes in a group, the value is in the coordinate space and units of the parent group.

Example

Shows how to create line shapes and set specific location and size.

[C#]

Document doc = new Document();

// The lines will cross the whole page.
float pageWidth = (float) doc.FirstSection.PageSetup.PageWidth;
float pageHeight = (float) doc.FirstSection.PageSetup.PageHeight;

// This line goes from top left to bottom right by default.
Shape lineA = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineA.BoundsInPoints);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    FlipOrientation = FlipOrientation.Horizontal,
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineB.BoundsInPoints);

// Add lines to the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(ArtifactsDir + "Shape.LineFlipOrientation.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


BoundsInPoints Property

Aspose.Words

ShapeBase.BoundsInPoints Property

Gets the location and size of the containing block of the shape in points, relative to the anchor of the topmost shape.

[Visual Basic]
Public ReadOnly Property BoundsInPoints As RectangleF
[C#]
public RectangleF BoundsInPoints {get;}

Example

Shows how to create line shapes and set specific location and size.

[C#]

Document doc = new Document();

// The lines will cross the whole page.
float pageWidth = (float) doc.FirstSection.PageSetup.PageWidth;
float pageHeight = (float) doc.FirstSection.PageSetup.PageHeight;

// This line goes from top left to bottom right by default.
Shape lineA = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineA.BoundsInPoints);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    FlipOrientation = FlipOrientation.Horizontal,
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineB.BoundsInPoints);

// Add lines to the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(ArtifactsDir + "Shape.LineFlipOrientation.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


BoundsWithEffects Property

Aspose.Words

ShapeBase.BoundsWithEffects Property

Gets final extent that this shape object has after applying drawing effects. Value is measured in points.

[Visual Basic]
Public ReadOnly Property BoundsWithEffects As RectangleF
[C#]
public RectangleF BoundsWithEffects {get;}

Example

Shows how to check how a shape's bounds are affected by shape effects.

[C#]

// Open a document that contains two shapes and get its shape collection
Document doc = new Document(MyDir + "Shape.AdjustWithEffects.docx");
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// The two shapes are identical in terms of dimensions and shape type
Assert.AreEqual(shapes[0].Width, shapes[1].Width);
Assert.AreEqual(shapes[0].Height, shapes[1].Height);
Assert.AreEqual(shapes[0].ShapeType, shapes[1].ShapeType);

// However, the first shape has no effects, while the second one has a shadow and thick outline
Assert.AreEqual(0.0, shapes[0].StrokeWeight);
Assert.AreEqual(20.0, shapes[1].StrokeWeight);
Assert.False(shapes[0].ShadowEnabled);
Assert.True(shapes[1].ShadowEnabled);

// These effects make the size of the second shape's silhouette bigger than that of the first
// Even though the size of the rectangle that shows up when we click on these shapes in Microsoft Word is the same,
// the practical outer bounds of the second shape are affected by the shadow and outline and are bigger
// We can use the AdjustWithEffects method to see exactly how much bigger they are

// The first shape has no outline or effects
Shape shape = shapes[0];

// Create a RectangleF object, which represents a rectangle, which we could potentially use as the coordinates and bounds for a shape
RectangleF rectangleF = new RectangleF(200, 200, 1000, 1000);

// Run this method to get the size of the rectangle adjusted for all of our shape's effects
RectangleF rectangleFOut = shape.AdjustWithEffects(rectangleF);

// Since the shape has no border-changing effects, its boundary dimensions are unaffected
Assert.AreEqual(200, rectangleFOut.X);
Assert.AreEqual(200, rectangleFOut.Y);
Assert.AreEqual(1000, rectangleFOut.Width);
Assert.AreEqual(1000, rectangleFOut.Height);

// The final extent of the first shape, in points
Assert.AreEqual(0, shape.BoundsWithEffects.X);
Assert.AreEqual(0, shape.BoundsWithEffects.Y);
Assert.AreEqual(147, shape.BoundsWithEffects.Width);
Assert.AreEqual(147, shape.BoundsWithEffects.Height);

// Do the same with the second shape
shape = shapes[1];
rectangleF = new RectangleF(200, 200, 1000, 1000);
rectangleFOut = shape.AdjustWithEffects(rectangleF);

// The shape's x/y coordinates (top left corner location) have been pushed back by the thick outline
Assert.AreEqual(171.5, rectangleFOut.X);
Assert.AreEqual(167, rectangleFOut.Y);

// The width and height were also affected by the outline and shadow
Assert.AreEqual(1045, rectangleFOut.Width);
Assert.AreEqual(1132, rectangleFOut.Height);

// These values are also affected by effects
Assert.AreEqual(-28.5, shape.BoundsWithEffects.X);
Assert.AreEqual(-33, shape.BoundsWithEffects.Y);
Assert.AreEqual(192, shape.BoundsWithEffects.Width);
Assert.AreEqual(279, shape.BoundsWithEffects.Height);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


CanHaveImage Property

Aspose.Words

ShapeBase.CanHaveImage Property

Returns true if the shape type allows the shape to have an image.

[Visual Basic]
Public ReadOnly Property CanHaveImage As Boolean
[C#]
public bool CanHaveImage {get;}

Remarks

Although Microsoft Word has a special shape type for images, it appears that in Microsoft Word documents any shape except a group shape can have an image, therefore this property returns true for all shapes except GroupShape.

Example

Shows how to insert shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a cube and set its name
Shape shape = builder.InsertShape(ShapeType.Cube, 150, 150);
shape.Name = "MyCube";

// We can also set the alt text like this
// This text will be found in Format AutoShape > Alt Text
shape.AlternativeText = "Alt text for MyCube.";

// Insert a text box
shape = builder.InsertShape(ShapeType.TextBox, 300, 50);
shape.Font.Name = "Times New Roman";

// Move the builder into the text box and write text
builder.MoveTo(shape.LastParagraph);
builder.Write("Hello world!");

// Move the builder out of the text box back into the main document
builder.MoveTo(shape.ParentParagraph);

// Insert a shape with an image
shape = builder.InsertImage(Image.FromFile(ImageDir + "Aspose.Words.gif"));
Assert.True(shape.CanHaveImage);
Assert.True(shape.HasImage);

// Rotate the image
shape.Rotation = 45.0;

doc.Save(ArtifactsDir + "Shape.InsertShapes.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


CoordOrigin Property

Aspose.Words

ShapeBase.CoordOrigin Property

The coordinates at the top-left corner of the containing block of this shape.

[Visual Basic]
Public Property CoordOrigin As Point
[C#]
public Point CoordOrigin {get; set;}

Remarks

The default value is (0,0).

Example

Shows how to create and work with a group of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Every GroupShape is top level
GroupShape group = new GroupShape(doc);
Assert.True(group.IsGroup);
Assert.True(group.IsTopLevel);

// And it is a floating shape too, so we can set its coordinates independently of the text
Assert.AreEqual(WrapType.None, group.WrapType);

// Make it a floating shape
group.WrapType = WrapType.None;

// Top level shapes can have this property changed
group.AnchorLocked = true;

// Set the XY coordinates of the shape group and the size of its containing block, as it appears on the page
group.Bounds = new RectangleF(100, 50, 200, 100);

// Set the scale of the inner coordinates of the shape group
// These values mean that the bottom right corner of the 200x100 outer block we set before
// will be at x = 2000 and y = 1000, or 2000 units from the left and 1000 units from the top
group.CoordSize = new Size(2000, 1000);

// The coordinate origin of a shape group is x = 0, y = 0 by default, which is the top left corner
// If we insert a child shape and set its distance from the left to 2000 and the distance from the top to 1000,
// its origin will be at the bottom right corner of the shape group
// We can offset the coordinate origin by setting the CoordOrigin attribute
// In this instance, we move the origin to the centre of the shape group
group.CoordOrigin = new Point(-1000, -500);

// Populate the shape group with child shapes
// First, insert a rectangle
Shape subShape = new Shape(doc, ShapeType.Rectangle);
subShape.Width = 500;
subShape.Height = 700;

// Place its top left corner at the parent group's coordinate origin, which is currently at its centre
subShape.Left = 0;
subShape.Top = 0;

// Add the rectangle to the group
group.AppendChild(subShape);

// Insert a triangle
subShape = new Shape(doc, ShapeType.Triangle);
subShape.Width = 400;
subShape.Height = 400;

// Place its origin at the bottom right corner of the group
subShape.Left = 1000;
subShape.Top = 500;

// The offset between this child shape and parent group can be seen here
Assert.AreEqual(new PointF(1000, 500), subShape.LocalToParent(new PointF(0, 0)));

// Add the triangle to the group
group.AppendChild(subShape);

// Child shapes of a group shape are not top level
Assert.False(subShape.IsTopLevel);

// Finally, insert the group into the document and save
builder.InsertNode(group);
doc.Save(ArtifactsDir + "Shape.InsertGroupShape.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


CoordSize Property

Aspose.Words

ShapeBase.CoordSize Property

The width and height of the coordinate space inside the containing block of this shape.

[Visual Basic]
Public Property CoordSize As Size
[C#]
public Size CoordSize {get; set;}

Remarks

The default value is (1000, 1000).

Example

Shows how to create and work with a group of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Every GroupShape is top level
GroupShape group = new GroupShape(doc);
Assert.True(group.IsGroup);
Assert.True(group.IsTopLevel);

// And it is a floating shape too, so we can set its coordinates independently of the text
Assert.AreEqual(WrapType.None, group.WrapType);

// Make it a floating shape
group.WrapType = WrapType.None;

// Top level shapes can have this property changed
group.AnchorLocked = true;

// Set the XY coordinates of the shape group and the size of its containing block, as it appears on the page
group.Bounds = new RectangleF(100, 50, 200, 100);

// Set the scale of the inner coordinates of the shape group
// These values mean that the bottom right corner of the 200x100 outer block we set before
// will be at x = 2000 and y = 1000, or 2000 units from the left and 1000 units from the top
group.CoordSize = new Size(2000, 1000);

// The coordinate origin of a shape group is x = 0, y = 0 by default, which is the top left corner
// If we insert a child shape and set its distance from the left to 2000 and the distance from the top to 1000,
// its origin will be at the bottom right corner of the shape group
// We can offset the coordinate origin by setting the CoordOrigin attribute
// In this instance, we move the origin to the centre of the shape group
group.CoordOrigin = new Point(-1000, -500);

// Populate the shape group with child shapes
// First, insert a rectangle
Shape subShape = new Shape(doc, ShapeType.Rectangle);
subShape.Width = 500;
subShape.Height = 700;

// Place its top left corner at the parent group's coordinate origin, which is currently at its centre
subShape.Left = 0;
subShape.Top = 0;

// Add the rectangle to the group
group.AppendChild(subShape);

// Insert a triangle
subShape = new Shape(doc, ShapeType.Triangle);
subShape.Width = 400;
subShape.Height = 400;

// Place its origin at the bottom right corner of the group
subShape.Left = 1000;
subShape.Top = 500;

// The offset between this child shape and parent group can be seen here
Assert.AreEqual(new PointF(1000, 500), subShape.LocalToParent(new PointF(0, 0)));

// Add the triangle to the group
group.AppendChild(subShape);

// Child shapes of a group shape are not top level
Assert.False(subShape.IsTopLevel);

// Finally, insert the group into the document and save
builder.InsertNode(group);
doc.Save(ArtifactsDir + "Shape.InsertGroupShape.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


DistanceBottom Property

Aspose.Words

ShapeBase.DistanceBottom Property

Returns or sets the distance (in points) between the document text and the bottom edge of the shape.

[Visual Basic]
Public Property DistanceBottom As Double
[C#]
public double DistanceBottom {get; set;}

Remarks

The default value is 0.

Has effect only for top level shapes.

Example

Shows how to set the wrapping distance for text that surrounds a shape.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a rectangle and get the text to wrap tightly around its bounds
Shape shape = builder.InsertShape(ShapeType.Rectangle, 150, 150);
shape.WrapType = WrapType.Tight;

// Set the minimum distance between the shape and surrounding text
shape.DistanceTop = 40.0;
shape.DistanceBottom = 40.0;
shape.DistanceLeft = 40.0;
shape.DistanceRight = 40.0;

// Move the shape closer to the centre of the page
shape.Left = 100.0;
shape.Top = 100.0;

// Rotate the shape
shape.Rotation = 60.0;

// Add text that the shape will push out of the way
for (int i = 0; i < 500; i++)
{
    builder.Write("text ");
}

doc.Save(ArtifactsDir + "Shape.ShapeCoords.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


DistanceLeft Property

Aspose.Words

ShapeBase.DistanceLeft Property

Returns or sets the distance (in points) between the document text and the left edge of the shape.

[Visual Basic]
Public Property DistanceLeft As Double
[C#]
public double DistanceLeft {get; set;}

Remarks

The default value is 1/8 inch.

Has effect only for top level shapes.

Example

Shows how to set the wrapping distance for text that surrounds a shape.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a rectangle and get the text to wrap tightly around its bounds
Shape shape = builder.InsertShape(ShapeType.Rectangle, 150, 150);
shape.WrapType = WrapType.Tight;

// Set the minimum distance between the shape and surrounding text
shape.DistanceTop = 40.0;
shape.DistanceBottom = 40.0;
shape.DistanceLeft = 40.0;
shape.DistanceRight = 40.0;

// Move the shape closer to the centre of the page
shape.Left = 100.0;
shape.Top = 100.0;

// Rotate the shape
shape.Rotation = 60.0;

// Add text that the shape will push out of the way
for (int i = 0; i < 500; i++)
{
    builder.Write("text ");
}

doc.Save(ArtifactsDir + "Shape.ShapeCoords.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


DistanceRight Property

Aspose.Words

ShapeBase.DistanceRight Property

Returns or sets the distance (in points) between the document text and the right edge of the shape.

[Visual Basic]
Public Property DistanceRight As Double
[C#]
public double DistanceRight {get; set;}

Remarks

The default value is 1/8 inch.

Has effect only for top level shapes.

Example

Shows how to set the wrapping distance for text that surrounds a shape.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a rectangle and get the text to wrap tightly around its bounds
Shape shape = builder.InsertShape(ShapeType.Rectangle, 150, 150);
shape.WrapType = WrapType.Tight;

// Set the minimum distance between the shape and surrounding text
shape.DistanceTop = 40.0;
shape.DistanceBottom = 40.0;
shape.DistanceLeft = 40.0;
shape.DistanceRight = 40.0;

// Move the shape closer to the centre of the page
shape.Left = 100.0;
shape.Top = 100.0;

// Rotate the shape
shape.Rotation = 60.0;

// Add text that the shape will push out of the way
for (int i = 0; i < 500; i++)
{
    builder.Write("text ");
}

doc.Save(ArtifactsDir + "Shape.ShapeCoords.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


DistanceTop Property

Aspose.Words

ShapeBase.DistanceTop Property

Returns or sets the distance (in points) between the document text and the top edge of the shape.

[Visual Basic]
Public Property DistanceTop As Double
[C#]
public double DistanceTop {get; set;}

Remarks

The default value is 0.

Has effect only for top level shapes.

Example

Shows how to set the wrapping distance for text that surrounds a shape.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a rectangle and get the text to wrap tightly around its bounds
Shape shape = builder.InsertShape(ShapeType.Rectangle, 150, 150);
shape.WrapType = WrapType.Tight;

// Set the minimum distance between the shape and surrounding text
shape.DistanceTop = 40.0;
shape.DistanceBottom = 40.0;
shape.DistanceLeft = 40.0;
shape.DistanceRight = 40.0;

// Move the shape closer to the centre of the page
shape.Left = 100.0;
shape.Top = 100.0;

// Rotate the shape
shape.Rotation = 60.0;

// Add text that the shape will push out of the way
for (int i = 0; i < 500; i++)
{
    builder.Write("text ");
}

doc.Save(ArtifactsDir + "Shape.ShapeCoords.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


FlipOrientation Property

Aspose.Words

ShapeBase.FlipOrientation Property

Switches the orientation of a shape.

[Visual Basic]
Public Property FlipOrientation As FlipOrientation
[C#]
public FlipOrientation FlipOrientation {get; set;}

Remarks

The default value is None.

Example

Shows how to create line shapes and set specific location and size.

[C#]

Document doc = new Document();

// The lines will cross the whole page.
float pageWidth = (float) doc.FirstSection.PageSetup.PageWidth;
float pageHeight = (float) doc.FirstSection.PageSetup.PageHeight;

// This line goes from top left to bottom right by default.
Shape lineA = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineA.BoundsInPoints);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line)
{
    Bounds = new RectangleF(0, 0, pageWidth, pageHeight),
    FlipOrientation = FlipOrientation.Horizontal,
    RelativeHorizontalPosition = RelativeHorizontalPosition.Page,
    RelativeVerticalPosition = RelativeVerticalPosition.Page
};

Assert.AreEqual(new RectangleF(0, 0, pageWidth, pageHeight), lineB.BoundsInPoints);

// Add lines to the document.
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(ArtifactsDir + "Shape.LineFlipOrientation.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Font Property

Aspose.Words

ShapeBase.Font Property

Provides access to the font formatting of this object.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Example

Shows how to insert shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a cube and set its name
Shape shape = builder.InsertShape(ShapeType.Cube, 150, 150);
shape.Name = "MyCube";

// We can also set the alt text like this
// This text will be found in Format AutoShape > Alt Text
shape.AlternativeText = "Alt text for MyCube.";

// Insert a text box
shape = builder.InsertShape(ShapeType.TextBox, 300, 50);
shape.Font.Name = "Times New Roman";

// Move the builder into the text box and write text
builder.MoveTo(shape.LastParagraph);
builder.Write("Hello world!");

// Move the builder out of the text box back into the main document
builder.MoveTo(shape.ParentParagraph);

// Insert a shape with an image
shape = builder.InsertImage(Image.FromFile(ImageDir + "Aspose.Words.gif"));
Assert.True(shape.CanHaveImage);
Assert.True(shape.HasImage);

// Rotate the image
shape.Rotation = 45.0;

doc.Save(ArtifactsDir + "Shape.InsertShapes.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Height Property

Aspose.Words

ShapeBase.Height Property

Gets or sets the height of the containing block of the shape.

[Visual Basic]
Public Property Height As Double
[C#]
public double Height {get; set;}

Remarks

For a top-level shape, the value is in points.

For shapes in a group, the value is in the coordinate space and units of the parent group.

The default value is 0.

Example

Shows how to resize an image shape.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inserted at 100% scale.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// It is easy to change the shape size. In this case, make it 50% relative to the current shape size.
shape.Width = shape.Width * 0.5;
shape.Height = shape.Height * 0.5;

// However, we can also go back to the original image size and scale from there, say 110%.
ImageSize imageSize = shape.ImageData.ImageSize;
shape.Width = imageSize.WidthPoints * 1.1;
shape.Height = imageSize.HeightPoints * 1.1;

builder.Document.Save(ArtifactsDir + "Image.ScaleImage.doc");
Shows how to insert a floating image and specify its position and size.
[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


HorizontalAlignment Property

Aspose.Words

ShapeBase.HorizontalAlignment Property

Specifies how the shape is positioned horizontally.

[Visual Basic]
Public Property HorizontalAlignment As HorizontalAlignment
[C#]
public HorizontalAlignment HorizontalAlignment {get; set;}

Remarks

The default value is None.

Has effect only for top level floating shapes.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


HRef Property

Aspose.Words

ShapeBase.HRef Property

Gets or sets the full hyperlink address for a shape.

[Visual Basic]
Public Property HRef As String
[C#]
public string HRef {get; set;}

Remarks

The default value is an empty string.

Below are examples of valid values for this property:

Full URI: https://www.aspose.com/.

Full file name: C:\\My Documents\\SalesReport.doc.

Relative URI: ../../../resource.txt

Relative file name: ..\\My Documents\\SalesReport.doc.

Bookmark within another document: https://www.aspose.com/Products/Default.aspx#Suites

Bookmark within this document: #BookmakName.

Example

Shows how to insert an image with a hyperlink.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

Shape shape = builder.InsertImage(MyDir + "Images/Hammer.wmf");
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx";
shape.Target = "New Window";
shape.ScreenTip = "Aspose.Words Support Forums";

builder.Document.Save(ArtifactsDir + "Image.InsertImageWithHyperlink.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsDeleteRevision Property

Aspose.Words

ShapeBase.IsDeleteRevision Property

Returns true if this object was deleted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsDeleteRevision As Boolean
[C#]
public bool IsDeleteRevision {get;}

Example

Shows how to work with revision shapes.

[C#]

// Open a blank document
Document doc = new Document();

// Insert an inline shape without tracking revisions
Assert.False(doc.TrackRevisions);
Shape shape = new Shape(doc, ShapeType.Cube);
shape.WrapType = WrapType.Inline;
shape.Width = 100.0;
shape.Height = 100.0;
doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

// Start tracking revisions and then insert another shape
doc.StartTrackRevisions("John Doe");

shape = new Shape(doc, ShapeType.Sun);
shape.WrapType = WrapType.Inline;
shape.Width = 100.0;
shape.Height = 100.0;
doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

// Get the document's shape collection which includes just the two shapes we added
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// Remove the first shape
shapes[0].Remove();

// Because we removed that shape while changes were being tracked, the shape counts as a delete revision
Assert.AreEqual(ShapeType.Cube, shapes[0].ShapeType);
Assert.True(shapes[0].IsDeleteRevision);

// And we inserted another shape while tracking changes, so that shape will count as an insert revision
Assert.AreEqual(ShapeType.Sun, shapes[1].ShapeType);
Assert.True(shapes[1].IsInsertRevision);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsGroup Property

Aspose.Words

ShapeBase.IsGroup Property

Returns true if this is a group shape.

[Visual Basic]
Public ReadOnly Property IsGroup As Boolean
[C#]
public bool IsGroup {get;}

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsHorizontalRule Property

Aspose.Words

ShapeBase.IsHorizontalRule Property

Returns true if this shape is a horizontal rule.

[Visual Basic]
Public ReadOnly Property IsHorizontalRule As Boolean
[C#]
public bool IsHorizontalRule {get;}

Example

Shows how to insert horizontal rule shape in a document.

[C#]

// Use a document builder to insert a horizontal rule
DocumentBuilder builder = new DocumentBuilder();
builder.InsertHorizontalRule();

// Get the rule from the document's shape collection and verify it
Shape horizontalRule = (Shape)builder.Document.GetChild(NodeType.Shape, 0, true);
Assert.True(horizontalRule.IsHorizontalRule);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsImage Property

Aspose.Words

ShapeBase.IsImage Property

Returns true if this shape is an image shape.

[Visual Basic]
Public ReadOnly Property IsImage As Boolean
[C#]
public bool IsImage {get;}

Example

Opens an HTML document with images from a stream using a base URI.

[C#]

Document doc = new Document();
// We are opening this HTML file:
//    <html>
//    <body>
//    <p>Simple file.</p>
//    <p><img src="Aspose.Words.gif" width="80" height="60"></p>
//    </body>
//    </html>
String fileName = MyDir + "Document.OpenFromStreamWithBaseUri.html";
// Open the stream.
using (Stream stream = File.OpenRead(fileName))
{
    // Open the document. Note the Document constructor detects HTML format automatically.
    // Pass the URI of the base folder so any images with relative URIs in the HTML document can be found.
    LoadOptions loadOptions = new LoadOptions();
    loadOptions.BaseUri = MyDir;

    doc = new Document(stream, loadOptions);
}

// Save in the DOC format.
doc.Save(ArtifactsDir + "Document.OpenFromStreamWithBaseUri.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsInline Property

Aspose.Words

ShapeBase.IsInline Property

A quick way to determine if this shape is positioned inline with text.

[Visual Basic]
Public ReadOnly Property IsInline As Boolean
[C#]
public bool IsInline {get;}

Remarks

Has effect only for top level shapes.

Example

Shows how to test if a shape in the document is inline or floating.

[C#]

Document doc = new Document(MyDir + "Shape.DeleteAllShapes.doc");

foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{
    if (shape.IsInline)
        Console.WriteLine("Shape is inline.");
    else
        Console.WriteLine("Shape is floating.");
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsInsertRevision Property

Aspose.Words

ShapeBase.IsInsertRevision Property

Returns true if this object was inserted in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsInsertRevision As Boolean
[C#]
public bool IsInsertRevision {get;}

Example

Shows how to work with revision shapes.

[C#]

// Open a blank document
Document doc = new Document();

// Insert an inline shape without tracking revisions
Assert.False(doc.TrackRevisions);
Shape shape = new Shape(doc, ShapeType.Cube);
shape.WrapType = WrapType.Inline;
shape.Width = 100.0;
shape.Height = 100.0;
doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

// Start tracking revisions and then insert another shape
doc.StartTrackRevisions("John Doe");

shape = new Shape(doc, ShapeType.Sun);
shape.WrapType = WrapType.Inline;
shape.Width = 100.0;
shape.Height = 100.0;
doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

// Get the document's shape collection which includes just the two shapes we added
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// Remove the first shape
shapes[0].Remove();

// Because we removed that shape while changes were being tracked, the shape counts as a delete revision
Assert.AreEqual(ShapeType.Cube, shapes[0].ShapeType);
Assert.True(shapes[0].IsDeleteRevision);

// And we inserted another shape while tracking changes, so that shape will count as an insert revision
Assert.AreEqual(ShapeType.Sun, shapes[1].ShapeType);
Assert.True(shapes[1].IsInsertRevision);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsLayoutInCell Property

Aspose.Words

ShapeBase.IsLayoutInCell Property

Gets or sets a flag indicating whether the shape is displayed inside a table or outside of it.

[Visual Basic]
Public Property IsLayoutInCell As Boolean
[C#]
public bool IsLayoutInCell {get; set;}

Remarks

The default value is true.

Has effect only for top level shapes, the property WrapType of which is set to value other than Inline.

Example

Shows how to display the shape, inside a table or outside of it.

[C#]

Document doc = new Document(MyDir + "Shape.LayoutInCell.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);
int num = 1;

foreach (Run run in runs.OfType<Run>())
{
    Shape watermark = new Shape(doc, ShapeType.TextPlainText);
    watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
    watermark.IsLayoutInCell =
        true; // False - display the shape outside of table cell, True - display the shape outside of table cell

    watermark.Width = 30;
    watermark.Height = 30;
    watermark.HorizontalAlignment = HorizontalAlignment.Center;
    watermark.VerticalAlignment = VerticalAlignment.Center;

    watermark.Rotation = -40;
    watermark.Fill.Color = Color.Gainsboro;
    watermark.StrokeColor = Color.Gainsboro;

    watermark.TextPath.Text = string.Format("{0}", num);
    watermark.TextPath.FontFamily = "Arial";

    watermark.Name = string.Format("WaterMark_{0}", Guid.NewGuid());
    watermark.WrapType =
        WrapType.None; // Property will take effect only if the WrapType property is set to something other than WrapType.Inline
    watermark.BehindText = true;

    builder.MoveTo(run);
    builder.InsertNode(watermark);

    num = num + 1;
}

// Behaviour of MS Word on working with shapes in table cells is changed in the last versions.
// Adding the following line is needed to make the shape displayed in center of a page.
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2010);

doc.Save(ArtifactsDir + "Shape.LayoutInCell.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsMoveFromRevision Property

Aspose.Words

ShapeBase.IsMoveFromRevision Property

Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveFromRevision As Boolean
[C#]
public bool IsMoveFromRevision {get;}

Example

Shows how to identify move revision shapes.

[C#]

// Open a document that contains a move revision
// A move revision is when we, while changes are tracked, cut(not copy)-and-paste or highlight and drag text from one place to another
// If inline shapes are caught up in the text movement, they will count as move revisions as well
// Moving a floating shape will not count as a move revision
Document doc = new Document(MyDir + "Shape.Revisions.docx");

// The document has one shape that was moved, but shape move revisions will have two instances of that shape
// One will be the shape at its arrival destination and the other will be the shape at its original location
List<Shape> nc = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, nc.Count);

// This is the move to revision, also the shape at its arrival destination
Assert.False(nc[0].IsMoveFromRevision);
Assert.True(nc[0].IsMoveToRevision);

// This is the move from revision, which is the shape at its original location
Assert.True(nc[1].IsMoveFromRevision);
Assert.False(nc[1].IsMoveToRevision);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsMoveToRevision Property

Aspose.Words

ShapeBase.IsMoveToRevision Property

Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.

[Visual Basic]
Public ReadOnly Property IsMoveToRevision As Boolean
[C#]
public bool IsMoveToRevision {get;}

Example

Shows how to identify move revision shapes.

[C#]

// Open a document that contains a move revision
// A move revision is when we, while changes are tracked, cut(not copy)-and-paste or highlight and drag text from one place to another
// If inline shapes are caught up in the text movement, they will count as move revisions as well
// Moving a floating shape will not count as a move revision
Document doc = new Document(MyDir + "Shape.Revisions.docx");

// The document has one shape that was moved, but shape move revisions will have two instances of that shape
// One will be the shape at its arrival destination and the other will be the shape at its original location
List<Shape> nc = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, nc.Count);

// This is the move to revision, also the shape at its arrival destination
Assert.False(nc[0].IsMoveFromRevision);
Assert.True(nc[0].IsMoveToRevision);

// This is the move from revision, which is the shape at its original location
Assert.True(nc[1].IsMoveFromRevision);
Assert.False(nc[1].IsMoveToRevision);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsSignatureLine Property

Aspose.Words

ShapeBase.IsSignatureLine Property

Indicates that shape is a SignatureLine.

[Visual Basic]
Public ReadOnly Property IsSignatureLine As Boolean
[C#]
public bool IsSignatureLine {get;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsTopLevel Property

Aspose.Words

ShapeBase.IsTopLevel Property

Returns true if this shape is not a child of a group shape.

[Visual Basic]
Public ReadOnly Property IsTopLevel As Boolean
[C#]
public bool IsTopLevel {get;}

Example

Shows how to create and work with a group of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Every GroupShape is top level
GroupShape group = new GroupShape(doc);
Assert.True(group.IsGroup);
Assert.True(group.IsTopLevel);

// And it is a floating shape too, so we can set its coordinates independently of the text
Assert.AreEqual(WrapType.None, group.WrapType);

// Make it a floating shape
group.WrapType = WrapType.None;

// Top level shapes can have this property changed
group.AnchorLocked = true;

// Set the XY coordinates of the shape group and the size of its containing block, as it appears on the page
group.Bounds = new RectangleF(100, 50, 200, 100);

// Set the scale of the inner coordinates of the shape group
// These values mean that the bottom right corner of the 200x100 outer block we set before
// will be at x = 2000 and y = 1000, or 2000 units from the left and 1000 units from the top
group.CoordSize = new Size(2000, 1000);

// The coordinate origin of a shape group is x = 0, y = 0 by default, which is the top left corner
// If we insert a child shape and set its distance from the left to 2000 and the distance from the top to 1000,
// its origin will be at the bottom right corner of the shape group
// We can offset the coordinate origin by setting the CoordOrigin attribute
// In this instance, we move the origin to the centre of the shape group
group.CoordOrigin = new Point(-1000, -500);

// Populate the shape group with child shapes
// First, insert a rectangle
Shape subShape = new Shape(doc, ShapeType.Rectangle);
subShape.Width = 500;
subShape.Height = 700;

// Place its top left corner at the parent group's coordinate origin, which is currently at its centre
subShape.Left = 0;
subShape.Top = 0;

// Add the rectangle to the group
group.AppendChild(subShape);

// Insert a triangle
subShape = new Shape(doc, ShapeType.Triangle);
subShape.Width = 400;
subShape.Height = 400;

// Place its origin at the bottom right corner of the group
subShape.Left = 1000;
subShape.Top = 500;

// The offset between this child shape and parent group can be seen here
Assert.AreEqual(new PointF(1000, 500), subShape.LocalToParent(new PointF(0, 0)));

// Add the triangle to the group
group.AppendChild(subShape);

// Child shapes of a group shape are not top level
Assert.False(subShape.IsTopLevel);

// Finally, insert the group into the document and save
builder.InsertNode(group);
doc.Save(ArtifactsDir + "Shape.InsertGroupShape.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


IsWordArt Property

Aspose.Words

ShapeBase.IsWordArt Property

Returns true if this shape is a WordArt object.

[Visual Basic]
Public ReadOnly Property IsWordArt As Boolean
[C#]
public bool IsWordArt {get;}

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Left Property

Aspose.Words

ShapeBase.Left Property

Gets or sets the position of the left edge of the containing block of the shape.

[Visual Basic]
Public Property Left As Double
[C#]
public double Left {get; set;}

Remarks

For a top-level shape, the value is in points and relative to the shape anchor.

For shapes in a group, the value is in the coordinate space and units of the parent group.

The default value is 0.

Has effect only for floating shapes.

Example

Shows how to insert a floating image and specify its position and size.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


MarkupLanguage Property

Aspose.Words

ShapeBase.MarkupLanguage Property

Gets MarkupLanguage used for this graphic object.

[Visual Basic]
Public ReadOnly Property MarkupLanguage As ShapeMarkupLanguage
[C#]
public ShapeMarkupLanguage MarkupLanguage {get;}

Example

Shows how get markup language for shape object in document

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertImage(ImageDir + "dotnet-logo.png");

// Loop through all single shapes inside document.
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{

    Console.WriteLine("Shape: " + shape.MarkupLanguage);
    Console.WriteLine("ShapeSize: " + shape.SizeInPoints);
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Name Property

Aspose.Words

ShapeBase.Name Property

Gets or sets the optional shape name.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

Default is empty string.

Cannot be null, but can be an empty string.

Example

Shows how to insert shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a cube and set its name
Shape shape = builder.InsertShape(ShapeType.Cube, 150, 150);
shape.Name = "MyCube";

// We can also set the alt text like this
// This text will be found in Format AutoShape > Alt Text
shape.AlternativeText = "Alt text for MyCube.";

// Insert a text box
shape = builder.InsertShape(ShapeType.TextBox, 300, 50);
shape.Font.Name = "Times New Roman";

// Move the builder into the text box and write text
builder.MoveTo(shape.LastParagraph);
builder.Write("Hello world!");

// Move the builder out of the text box back into the main document
builder.MoveTo(shape.ParentParagraph);

// Insert a shape with an image
shape = builder.InsertImage(Image.FromFile(ImageDir + "Aspose.Words.gif"));
Assert.True(shape.CanHaveImage);
Assert.True(shape.HasImage);

// Rotate the image
shape.Rotation = 45.0;

doc.Save(ArtifactsDir + "Shape.InsertShapes.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ParentParagraph Property

Aspose.Words

ShapeBase.ParentParagraph Property

Returns the immediate parent paragraph.

[Visual Basic]
Public ReadOnly Property ParentParagraph As Paragraph
[C#]
public Paragraph ParentParagraph {get;}

Remarks

For child shapes of a group shape and child shapes of an Office Math object always returns null.

Example

Shows how to insert shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a cube and set its name
Shape shape = builder.InsertShape(ShapeType.Cube, 150, 150);
shape.Name = "MyCube";

// We can also set the alt text like this
// This text will be found in Format AutoShape > Alt Text
shape.AlternativeText = "Alt text for MyCube.";

// Insert a text box
shape = builder.InsertShape(ShapeType.TextBox, 300, 50);
shape.Font.Name = "Times New Roman";

// Move the builder into the text box and write text
builder.MoveTo(shape.LastParagraph);
builder.Write("Hello world!");

// Move the builder out of the text box back into the main document
builder.MoveTo(shape.ParentParagraph);

// Insert a shape with an image
shape = builder.InsertImage(Image.FromFile(ImageDir + "Aspose.Words.gif"));
Assert.True(shape.CanHaveImage);
Assert.True(shape.HasImage);

// Rotate the image
shape.Rotation = 45.0;

doc.Save(ArtifactsDir + "Shape.InsertShapes.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


RelativeHorizontalPosition Property

Aspose.Words

ShapeBase.RelativeHorizontalPosition Property

Specifies relative to what the shape is positioned horizontally.

[Visual Basic]
Public Property RelativeHorizontalPosition As RelativeHorizontalPosition
[C#]
public RelativeHorizontalPosition RelativeHorizontalPosition {get; set;}

Remarks

The default value is Column.

Has effect only for top level floating shapes.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


RelativeVerticalPosition Property

Aspose.Words

ShapeBase.RelativeVerticalPosition Property

Specifies relative to what the shape is positioned vertically.

[Visual Basic]
Public Property RelativeVerticalPosition As RelativeVerticalPosition
[C#]
public RelativeVerticalPosition RelativeVerticalPosition {get; set;}

Remarks

The default value is Paragraph.

Has effect only for top level floating shapes.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Right Property

Aspose.Words

ShapeBase.Right Property

Gets the position of the right edge of the containing block of the shape.

[Visual Basic]
Public ReadOnly Property Right As Double
[C#]
public double Right {get;}

Remarks

For a top-level shape, the value is in points and relative to the shape anchor.

For shapes in a group, the value is in the coordinate space and units of the parent group.

Example

Shows how to insert a floating image and specify its position and size.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Rotation Property

Aspose.Words

ShapeBase.Rotation Property

Defines the angle (in degrees) that a shape is rotated. Positive value corresponds to clockwise rotation angle.

[Visual Basic]
Public Property Rotation As Double
[C#]
public double Rotation {get; set;}

Remarks

The default value is 0.

Example

Shows how to insert shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a cube and set its name
Shape shape = builder.InsertShape(ShapeType.Cube, 150, 150);
shape.Name = "MyCube";

// We can also set the alt text like this
// This text will be found in Format AutoShape > Alt Text
shape.AlternativeText = "Alt text for MyCube.";

// Insert a text box
shape = builder.InsertShape(ShapeType.TextBox, 300, 50);
shape.Font.Name = "Times New Roman";

// Move the builder into the text box and write text
builder.MoveTo(shape.LastParagraph);
builder.Write("Hello world!");

// Move the builder out of the text box back into the main document
builder.MoveTo(shape.ParentParagraph);

// Insert a shape with an image
shape = builder.InsertImage(Image.FromFile(ImageDir + "Aspose.Words.gif"));
Assert.True(shape.CanHaveImage);
Assert.True(shape.HasImage);

// Rotate the image
shape.Rotation = 45.0;

doc.Save(ArtifactsDir + "Shape.InsertShapes.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ScreenTip Property

Aspose.Words

ShapeBase.ScreenTip Property

Defines the text displayed when the mouse pointer moves over the shape.

[Visual Basic]
Public Property ScreenTip As String
[C#]
public string ScreenTip {get; set;}

Remarks

The default value is an empty string.

Example

Shows how to insert an image with a hyperlink.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

Shape shape = builder.InsertImage(MyDir + "Images/Hammer.wmf");
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx";
shape.Target = "New Window";
shape.ScreenTip = "Aspose.Words Support Forums";

builder.Document.Save(ArtifactsDir + "Image.InsertImageWithHyperlink.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ShapeType Property

Aspose.Words

ShapeBase.ShapeType Property

Gets the shape type.

[Visual Basic]
Public ReadOnly Property ShapeType As ShapeType
[C#]
public ShapeType ShapeType {get;}

Example

Shows how to create a group of shapes, and let it accept a visitor

[C#]

public void GroupOfShapes()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Shape balloon = new Shape(doc, ShapeType.Balloon)
    {
        Width = 200,
        Height = 200,
        Stroke = { Color = Color.Red }
    };

    Shape cube = new Shape(doc, ShapeType.Cube)
    {
        Width = 100,
        Height = 100,
        Stroke = { Color = Color.Blue }
    };

    GroupShape group = new GroupShape(doc);
    group.AppendChild(balloon);
    group.AppendChild(cube);

    Assert.True(group.IsGroup);

    builder.InsertNode(group);

    ShapeInfoPrinter printer = new ShapeInfoPrinter();
    group.Accept(printer);

    Console.WriteLine(printer.GetText());
}

/// <summary>
/// Visitor that prints shape group contents information to the console.
/// </summary>
public class ShapeInfoPrinter : DocumentVisitor
{
    public ShapeInfoPrinter()
    {
        mBuilder = new StringBuilder();
    }

    public string GetText()
    {
        return mBuilder.ToString();
    }

    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        mBuilder.AppendLine("Shape group started:");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitGroupShapeEnd(GroupShape groupShape)
    {
        mBuilder.AppendLine("End of shape group");
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeStart(Shape shape)
    {
        mBuilder.AppendLine("\tShape - " + shape.ShapeType + ":");
        mBuilder.AppendLine("\t\tWidth: " + shape.Width);
        mBuilder.AppendLine("\t\tHeight: " + shape.Height);
        mBuilder.AppendLine("\t\tStroke color: " + shape.Stroke.Color);
        mBuilder.AppendLine("\t\tFill color: " + shape.Fill.Color);
        return VisitorAction.Continue;
    }

    public override VisitorAction VisitShapeEnd(Shape shape)
    {
        mBuilder.AppendLine("\tEnd of shape");
        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


SizeInPoints Property

Aspose.Words

ShapeBase.SizeInPoints Property

Gets the size of the shape in points.

[Visual Basic]
Public ReadOnly Property SizeInPoints As SizeF
[C#]
public SizeF SizeInPoints {get;}

Example

Shows how get markup language for shape object in document

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertImage(ImageDir + "dotnet-logo.png");

// Loop through all single shapes inside document.
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{

    Console.WriteLine("Shape: " + shape.MarkupLanguage);
    Console.WriteLine("ShapeSize: " + shape.SizeInPoints);
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Target Property

Aspose.Words

ShapeBase.Target Property

Gets or sets the target frame for the shape hyperlink.

[Visual Basic]
Public Property Target As String
[C#]
public string Target {get; set;}

Remarks

The default value is an empty string.

Example

Shows how to insert an image with a hyperlink.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

Shape shape = builder.InsertImage(MyDir + "Images/Hammer.wmf");
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx";
shape.Target = "New Window";
shape.ScreenTip = "Aspose.Words Support Forums";

builder.Document.Save(ArtifactsDir + "Image.InsertImageWithHyperlink.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Title Property

Aspose.Words

ShapeBase.Title Property

Gets or sets the title (caption) of the current shape object.

[Visual Basic]
Public Property Title As String
[C#]
public string Title {get; set;}

Remarks

Default is empty string.

Cannot be null, but can be an empty string.

Example

Shows how to get or set title of shape object.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create test shape.
Shape shape = new Shape(doc, ShapeType.Cube);
shape.Width = 431.5;
shape.Height = 346.35;
shape.Title = "Alt Text Title";

builder.InsertNode(shape);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
Console.WriteLine("Shape text: " + shape.Title);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Top Property

Aspose.Words

ShapeBase.Top Property

Gets or sets the position of the top edge of the containing block of the shape.

[Visual Basic]
Public Property Top As Double
[C#]
public double Top {get; set;}

Remarks

For a top-level shape, the value is in points and relative to the shape anchor.

For shapes in a group, the value is in the coordinate space and units of the parent group.

The default value is 0.

Has effect only for floating shapes.

Example

Shows how to insert a floating image and specify its position and size.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


VerticalAlignment Property

Aspose.Words

ShapeBase.VerticalAlignment Property

Specifies how the shape is positioned vertically.

[Visual Basic]
Public Property VerticalAlignment As VerticalAlignment
[C#]
public VerticalAlignment VerticalAlignment {get; set;}

Remarks

The default value is None.

Has effect only for top level floating shapes.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


Width Property

Aspose.Words

ShapeBase.Width Property

Gets or sets the width of the containing block of the shape.

[Visual Basic]
Public Property Width As Double
[C#]
public double Width {get; set;}

Remarks

For a top-level shape, the value is in points.

For shapes in a group, the value is in the coordinate space and units of the parent group.

The default value is 0.

Example

Shows how to resize an image shape.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inserted at 100% scale.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// It is easy to change the shape size. In this case, make it 50% relative to the current shape size.
shape.Width = shape.Width * 0.5;
shape.Height = shape.Height * 0.5;

// However, we can also go back to the original image size and scale from there, say 110%.
ImageSize imageSize = shape.ImageData.ImageSize;
shape.Width = imageSize.WidthPoints * 1.1;
shape.Height = imageSize.HeightPoints * 1.1;

builder.Document.Save(ArtifactsDir + "Image.ScaleImage.doc");
Shows how to insert a floating image and specify its position and size.
[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;

// Make position relative to the page.
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Set the shape's coordinates, from the top left corner of the page
shape.Left = 100;
shape.Top = 80;

// Set the shape's height
shape.Height = 125.0;

// The width will be scaled to the height and the dimensions of the real image
Assert.AreEqual(125.0, shape.Width);

// The Bottom and Right members contain the locations of the bottom and right edges of the image
Assert.AreEqual(shape.Top + shape.Height, shape.Bottom);
Assert.AreEqual(shape.Left + shape.Width, shape.Right);

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPositionSize.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


WrapSide Property

Aspose.Words

ShapeBase.WrapSide Property

Specifies how the text is wrapped around the shape.

[Visual Basic]
Public Property WrapSide As WrapSide
[C#]
public WrapSide WrapSide {get; set;}

Remarks

The default value is Both.

Has effect only for top level shapes.

Example

Shows how to replace all textboxes with images.

[C#]

Document doc = new Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

// This gets a live collection of all shape nodes in the document.
NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

// Since we will be adding/removing nodes, it is better to copy all collection
// into a fixed size array, otherwise iterator will be invalidated.
Node[] shapes = shapeCollection.ToArray();

foreach (Shape shape in shapes.OfType<Shape>())
{
    // Filter out all shapes that we don't need.
    if (shape.ShapeType.Equals(ShapeType.TextBox))
    {
        // Create a new shape that will replace the existing shape.
        Shape image = new Shape(doc, ShapeType.Image);

        // Load the image into the new shape.
        image.ImageData.SetImage(ImageDir + "Hammer.wmf");

        // Make new shape's position to match the old shape.
        image.Left = shape.Left;
        image.Top = shape.Top;
        image.Width = shape.Width;
        image.Height = shape.Height;
        image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
        image.RelativeVerticalPosition = shape.RelativeVerticalPosition;
        image.HorizontalAlignment = shape.HorizontalAlignment;
        image.VerticalAlignment = shape.VerticalAlignment;
        image.WrapType = shape.WrapType;
        image.WrapSide = shape.WrapSide;

        // Insert new shape after the old shape and remove the old shape.
        shape.ParentNode.InsertAfter(image, shape);
        shape.Remove();
    }
}

doc.Save(ArtifactsDir + "Shape.ReplaceTextboxesWithImages.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


WrapType Property

Aspose.Words

ShapeBase.WrapType Property

Defines whether the shape is inline or floating. For floating shapes defines the wrapping mode for text around the shape.

[Visual Basic]
Public Property WrapType As WrapType
[C#]
public WrapType WrapType {get; set;}

Remarks

The default value is None.

Has effect only for top level shapes.

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");
Creates a textbox with some text and different formatting options in a new document.
[C#]

// Create a blank document.
Document doc = new Document();

// Create a new shape of type TextBox
Shape textBox = new Shape(doc, ShapeType.TextBox);

// Set some settings of the textbox itself.
// Set the wrap of the textbox to inline
textBox.WrapType = WrapType.None;
// Set the horizontal and vertical alignment of the text inside the shape.
textBox.HorizontalAlignment = HorizontalAlignment.Center;
textBox.VerticalAlignment = VerticalAlignment.Top;

// Set the textbox height and width.
textBox.Height = 50;
textBox.Width = 200;

// Set the textbox in front of other shapes with a lower ZOrder
textBox.ZOrder = 2;

// Let's create a new paragraph for the textbox manually and align it in the center. Make sure we add the new nodes to the textbox as well.
textBox.AppendChild(new Paragraph(doc));
Paragraph para = textBox.FirstParagraph;
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Add some text to the paragraph.
Run run = new Run(doc);
run.Text = "Content in textbox";
para.AppendChild(run);

// Append the textbox to the first paragraph in the body.
doc.FirstSection.Body.FirstParagraph.AppendChild(textBox);

// Save the output
doc.Save(ArtifactsDir + "Shape.CreateTextBox.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ZOrder Property

Aspose.Words

ShapeBase.ZOrder Property

Determines the display order of overlapping shapes.

[Visual Basic]
Public Property ZOrder As Integer
[C#]
public int ZOrder {get; set;}

Remarks

Has effect only for top level shapes.

The default value is 0.

The number represents the stacking precedence. A shape with a higher number will be displayed as if it were overlapping (in "front" of) a shape with a lower number.

The order of overlapping shapes is independent for shapes in the header and in the main text of the document.

The display order of child shapes in a group shape is determined by their order inside the group shape.

Example

Creates a textbox with some text and different formatting options in a new document.

[C#]

// Create a blank document.
Document doc = new Document();

// Create a new shape of type TextBox
Shape textBox = new Shape(doc, ShapeType.TextBox);

// Set some settings of the textbox itself.
// Set the wrap of the textbox to inline
textBox.WrapType = WrapType.None;
// Set the horizontal and vertical alignment of the text inside the shape.
textBox.HorizontalAlignment = HorizontalAlignment.Center;
textBox.VerticalAlignment = VerticalAlignment.Top;

// Set the textbox height and width.
textBox.Height = 50;
textBox.Width = 200;

// Set the textbox in front of other shapes with a lower ZOrder
textBox.ZOrder = 2;

// Let's create a new paragraph for the textbox manually and align it in the center. Make sure we add the new nodes to the textbox as well.
textBox.AppendChild(new Paragraph(doc));
Paragraph para = textBox.FirstParagraph;
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Add some text to the paragraph.
Run run = new Run(doc);
run.Text = "Content in textbox";
para.AppendChild(run);

// Append the textbox to the first paragraph in the body.
doc.FirstSection.Body.FirstParagraph.AppendChild(textBox);

// Save the output
doc.Save(ArtifactsDir + "Shape.CreateTextBox.doc");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace | BehindText


ShapeBase Methods

The methods of the ShapeBase class are listed below. For a complete list of ShapeBase class members, see the ShapeBase Members topic.

Public Instance Methods

Accept (inherited from Node) | Accepts a visitor.
AdjustWithEffects | Adds to the source rectangle values of the effect extent and returns the final rectangle.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetShapeRenderer | Creates and returns an object that can be used to render this shape into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
LocalToParent | Converts a value from the local coordinate space into the coordinate space of the parent shape.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace | Shape | GroupShape


ShapeBase.AdjustWithEffects Method

Adds to the source rectangle values of the effect extent and returns the final rectangle.

[Visual Basic]
Public Function AdjustWithEffects( _
ByVal source As RectangleF _
) As RectangleF
[C#]
public RectangleF AdjustWithEffects(
RectangleF source
);

Example

Shows how to check how a shape's bounds are affected by shape effects.

[C#]

// Open a document that contains two shapes and get its shape collection
Document doc = new Document(MyDir + "Shape.AdjustWithEffects.docx");
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(2, shapes.Count);

// The two shapes are identical in terms of dimensions and shape type
Assert.AreEqual(shapes[0].Width, shapes[1].Width);
Assert.AreEqual(shapes[0].Height, shapes[1].Height);
Assert.AreEqual(shapes[0].ShapeType, shapes[1].ShapeType);

// However, the first shape has no effects, while the second one has a shadow and thick outline
Assert.AreEqual(0.0, shapes[0].StrokeWeight);
Assert.AreEqual(20.0, shapes[1].StrokeWeight);
Assert.False(shapes[0].ShadowEnabled);
Assert.True(shapes[1].ShadowEnabled);

// These effects make the size of the second shape's silhouette bigger than that of the first
// Even though the size of the rectangle that shows up when we click on these shapes in Microsoft Word is the same,
// the practical outer bounds of the second shape are affected by the shadow and outline and are bigger
// We can use the AdjustWithEffects method to see exactly how much bigger they are

// The first shape has no outline or effects
Shape shape = shapes[0];

// Create a RectangleF object, which represents a rectangle, which we could potentially use as the coordinates and bounds for a shape
RectangleF rectangleF = new RectangleF(200, 200, 1000, 1000);

// Run this method to get the size of the rectangle adjusted for all of our shape's effects
RectangleF rectangleFOut = shape.AdjustWithEffects(rectangleF);

// Since the shape has no border-changing effects, its boundary dimensions are unaffected
Assert.AreEqual(200, rectangleFOut.X);
Assert.AreEqual(200, rectangleFOut.Y);
Assert.AreEqual(1000, rectangleFOut.Width);
Assert.AreEqual(1000, rectangleFOut.Height);

// The final extent of the first shape, in points
Assert.AreEqual(0, shape.BoundsWithEffects.X);
Assert.AreEqual(0, shape.BoundsWithEffects.Y);
Assert.AreEqual(147, shape.BoundsWithEffects.Width);
Assert.AreEqual(147, shape.BoundsWithEffects.Height);

// Do the same with the second shape
shape = shapes[1];
rectangleF = new RectangleF(200, 200, 1000, 1000);
rectangleFOut = shape.AdjustWithEffects(rectangleF);

// The shape's x/y coordinates (top left corner location) have been pushed back by the thick outline
Assert.AreEqual(171.5, rectangleFOut.X);
Assert.AreEqual(167, rectangleFOut.Y);

// The width and height were also affected by the outline and shadow
Assert.AreEqual(1045, rectangleFOut.Width);
Assert.AreEqual(1132, rectangleFOut.Height);

// These values are also affected by effects
Assert.AreEqual(-28.5, shape.BoundsWithEffects.X);
Assert.AreEqual(-33, shape.BoundsWithEffects.Y);
Assert.AreEqual(192, shape.BoundsWithEffects.Width);
Assert.AreEqual(279, shape.BoundsWithEffects.Height);

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ShapeBase.GetShapeRenderer Method

Creates and returns an object that can be used to render this shape into an image.

[Visual Basic]
Public Function GetShapeRenderer() As ShapeRenderer
[C#]
public ShapeRenderer GetShapeRenderer();

Return Value

The renderer object for this shape.

Remarks

This method just invokes the ShapeRenderer constructor and passes this object as a parameter.

Example

Shows how to export shapes to files in the local file system using a shape renderer.

[C#]

// Open a document that contains shapes and get its shape collection
Document doc = new Document(MyDir + "Shape.VarietyOfShapes.docx");
List<Shape> shapes = doc.GetChildNodes(NodeType.Shape, true).Cast<Shape>().ToList();
Assert.AreEqual(7, shapes.Count);

// There are 7 shapes in the document, with one group shape with 2 child shapes
// The child shapes will be rendered but their parent group shape will be skipped, so we will see 6 output files
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{
    ShapeRenderer renderer = shape.GetShapeRenderer();
    ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png);
    renderer.Save(ArtifactsDir + $"Shape.ShapeRenderer {shape.Name}.png", options);
}

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ShapeBase.LocalToParent Method

Converts a value from the local coordinate space into the coordinate space of the parent shape.

[Visual Basic]
Public Function LocalToParent( _
ByVal value As PointF _
) As PointF
[C#]
public PointF LocalToParent(
PointF value
);

Example

Shows how to create and work with a group of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Every GroupShape is top level
GroupShape group = new GroupShape(doc);
Assert.True(group.IsGroup);
Assert.True(group.IsTopLevel);

// And it is a floating shape too, so we can set its coordinates independently of the text
Assert.AreEqual(WrapType.None, group.WrapType);

// Make it a floating shape
group.WrapType = WrapType.None;

// Top level shapes can have this property changed
group.AnchorLocked = true;

// Set the XY coordinates of the shape group and the size of its containing block, as it appears on the page
group.Bounds = new RectangleF(100, 50, 200, 100);

// Set the scale of the inner coordinates of the shape group
// These values mean that the bottom right corner of the 200x100 outer block we set before
// will be at x = 2000 and y = 1000, or 2000 units from the left and 1000 units from the top
group.CoordSize = new Size(2000, 1000);

// The coordinate origin of a shape group is x = 0, y = 0 by default, which is the top left corner
// If we insert a child shape and set its distance from the left to 2000 and the distance from the top to 1000,
// its origin will be at the bottom right corner of the shape group
// We can offset the coordinate origin by setting the CoordOrigin attribute
// In this instance, we move the origin to the centre of the shape group
group.CoordOrigin = new Point(-1000, -500);

// Populate the shape group with child shapes
// First, insert a rectangle
Shape subShape = new Shape(doc, ShapeType.Rectangle);
subShape.Width = 500;
subShape.Height = 700;

// Place its top left corner at the parent group's coordinate origin, which is currently at its centre
subShape.Left = 0;
subShape.Top = 0;

// Add the rectangle to the group
group.AppendChild(subShape);

// Insert a triangle
subShape = new Shape(doc, ShapeType.Triangle);
subShape.Width = 400;
subShape.Height = 400;

// Place its origin at the bottom right corner of the group
subShape.Left = 1000;
subShape.Top = 500;

// The offset between this child shape and parent group can be seen here
Assert.AreEqual(new PointF(1000, 500), subShape.LocalToParent(new PointF(0, 0)));

// Add the triangle to the group
group.AppendChild(subShape);

// Child shapes of a group shape are not top level
Assert.False(subShape.IsTopLevel);

// Finally, insert the group into the document and save
builder.InsertNode(group);
doc.Save(ArtifactsDir + "Shape.InsertGroupShape.docx");

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace


ShapeLineStyle Enumeration

Specifies the compound line style of a Shape.

[Visual Basic]
Public Enum ShapeLineStyle
[C#]
public enum ShapeLineStyle

Remarks

Example

Shows how change stroke properties

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new shape of type Rectangle
Shape rectangle = new Shape(doc, ShapeType.Rectangle);

//Change stroke properties
Stroke stroke = rectangle.Stroke;
stroke.On = true;
stroke.Weight = 5;
stroke.Color = Color.Red;
stroke.DashStyle = DashStyle.ShortDashDotDot;
stroke.JoinStyle = JoinStyle.Miter;
stroke.EndCap = EndCap.Square;
stroke.LineStyle = ShapeLineStyle.Triple;

//Insert shape object
builder.InsertNode(rectangle);

Members

Member Name | Description | Value
Single | Single line. | 0
Double | Double lines of equal width. | 1
ThickThin | Double lines, one thick, one thin. | 2
ThinThick | Double lines, one thin, one thick. | 3
Triple | Three lines, thin, thick, thin. | 4
Default | Default value is Single. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | LineStyle


ShapeMarkupLanguage Enumeration

Specifies Markup language used for the shape.

[Visual Basic]
Public Enum ShapeMarkupLanguage
Inherits
[C#]
public enum ShapeMarkupLanguage

Example

Shows conversion VML shapes to DML using ISO/IEC 29500:2008 Strict compliance level

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set Word2003 version for document, for inserting image as VML shape
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2003);

builder.InsertImage(ImageDir + "dotnet-logo.png");

// Loop through all single shapes inside document.
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{
    Console.WriteLine(shape.MarkupLanguage);
}

// Iso29500_2008 does not allow VML shapes
// You need to use OoxmlCompliance.Iso29500_2008_Strict for converting VML to DML shapes
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions
{
    Compliance = OoxmlCompliance.Iso29500_2008_Strict,
    SaveFormat = SaveFormat.Docx
};

Members

Member Name | Description | Value
Dml | Drawing Markup Language is used to define the shape. | 0
Vml | Vector Markup Language is used to define the shape. | 1

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace


ShapeType Enumeration

Specifies the type of shape in a Microsoft Word document.

[Visual Basic]
Public Enum ShapeType
[C#]
public enum ShapeType

Remarks

Example

Shows how to create and add an image to a document without using document builder.

[C#]

Document doc = new Document();

Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(MyDir + "Images/Hammer.wmf");
shape.Width = 100;
shape.Height = 100;

doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

doc.Save(ArtifactsDir + "Image.CreateImageDirectly.doc");

Members

Member Name | Description | Value
Image | The shape is an image. | 75
TextBox | The shape is a textbox. Note that shapes of many other types can also have text inside them too. A shape does not have to have this type to contain text. | 202
Group | The shape is a group shape. | -1
OleObject | The shape is an OLE object. You cannot create shapes of this type in the document. | -2
OleControl | The shape is an ActiveX control. You cannot create shapes of this type in the document. | 201
NonPrimitive | A shape drawn by user and consisting of multiple segments and/or vertices (curve, freeform or scribble). You cannot create shapes of this type in the document. | 0
Rectangle |  | 1
RoundRectangle |  | 2
Ellipse |  | 3
Diamond |  | 4
Triangle |  | 5
RightTriangle |  | 6
Parallelogram |  | 7
Trapezoid |  | 8
Hexagon |  | 9
Octagon |  | 10
Plus |  | 11
Star |  | 12
Arrow |  | 13
ThickArrow |  | 14
HomePlate |  | 15
Cube |  | 16
Balloon |  | 17
Seal |  | 18
Arc |  | 19
Line |  | 20
Plaque |  | 21
Can |  | 22
Donut |  | 23
TextSimple |  | 24
TextOctagon |  | 25
TextHexagon |  | 26
TextCurve |  | 27
TextWave |  | 28
TextRing |  | 29
TextOnCurve |  | 30
TextOnRing |  | 31
StraightConnector1 |  | 32
BentConnector2 |  | 33
BentConnector3 |  | 34
BentConnector4 |  | 35
BentConnector5 |  | 36
CurvedConnector2 |  | 37
CurvedConnector3 |  | 38
CurvedConnector4 |  | 39
CurvedConnector5 |  | 40
Callout1 |  | 41
Callout2 |  | 42
Callout3 |  | 43
AccentCallout1 |  | 44
AccentCallout2 |  | 45
AccentCallout3 |  | 46
BorderCallout1 |  | 47
BorderCallout2 |  | 48
BorderCallout3 |  | 49
AccentBorderCallout1 |  | 50
AccentBorderCallout2 |  | 51
AccentBorderCallout3 |  | 52
Ribbon |  | 53
Ribbon2 |  | 54
Chevron |  | 55
Pentagon |  | 56
NoSmoking |  | 57
Seal8 |  | 58
Seal16 |  | 59
Seal32 |  | 60
WedgeRectCallout |  | 61
WedgeRRectCallout |  | 62
WedgeEllipseCallout |  | 63
Wave |  | 64
FoldedCorner |  | 65
LeftArrow |  | 66
DownArrow |  | 67
UpArrow |  | 68
LeftRightArrow |  | 69
UpDownArrow |  | 70
IrregularSeal1 |  | 71
IrregularSeal2 |  | 72
LightningBolt |  | 73
Heart |  | 74
QuadArrow |  | 76
LeftArrowCallout |  | 77
RightArrowCallout |  | 78
UpArrowCallout |  | 79
DownArrowCallout |  | 80
LeftRightArrowCallout |  | 81
UpDownArrowCallout |  | 82
QuadArrowCallout |  | 83
Bevel |  | 84
LeftBracket |  | 85
RightBracket |  | 86
LeftBrace |  | 87
RightBrace |  | 88
LeftUpArrow |  | 89
BentUpArrow |  | 90
BentArrow |  | 91
Seal24 |  | 92
StripedRightArrow |  | 93
NotchedRightArrow |  | 94
BlockArc |  | 95
SmileyFace |  | 96
VerticalScroll |  | 97
HorizontalScroll |  | 98
CircularArrow |  | 99
CustomShape | This shape type seems to be set for shapes that are not part of the standard set of the auto shapes in Microsoft Word. For example, if you insert a new auto shape from ClipArt. You cannot create shapes of this type in the document. | 100
UturnArrow |  | 101
CurvedRightArrow |  | 102
CurvedLeftArrow |  | 103
CurvedUpArrow |  | 104
CurvedDownArrow |  | 105
CloudCallout |  | 106
EllipseRibbon |  | 107
EllipseRibbon2 |  | 108
FlowChartProcess |  | 109
FlowChartDecision |  | 110
FlowChartInputOutput |  | 111
FlowChartPredefinedProcess |  | 112
FlowChartInternalStorage |  | 113
FlowChartDocument |  | 114
FlowChartMultidocument |  | 115
FlowChartTerminator |  | 116
FlowChartPreparation |  | 117
FlowChartManualInput |  | 118
FlowChartManualOperation |  | 119
FlowChartConnector |  | 120
FlowChartPunchedCard |  | 121
FlowChartPunchedTape |  | 122
FlowChartSummingJunction |  | 123
FlowChartOr |  | 124
FlowChartCollate |  | 125
FlowChartSort |  | 126
FlowChartExtract |  | 127
FlowChartMerge |  | 128
FlowChartOfflineStorage |  | 129
FlowChartOnlineStorage |  | 130
FlowChartMagneticTape |  | 131
FlowChartMagneticDisk |  | 132
FlowChartMagneticDrum |  | 133
FlowChartDisplay |  | 134
FlowChartDelay |  | 135
TextPlainText | WordArt object. | 136
TextStop | WordArt object. | 137
TextTriangle | WordArt object. | 138
TextTriangleInverted | WordArt object. | 139
TextChevron | WordArt object. | 140
TextChevronInverted | WordArt object. | 141
TextRingInside | WordArt object. | 142
TextRingOutside | WordArt object. | 143
TextArchUpCurve | WordArt object. | 144
TextArchDownCurve | WordArt object. | 145
TextCircleCurve | WordArt object. | 146
TextButtonCurve | WordArt object. | 147
TextArchUpPour | WordArt object. | 148
TextArchDownPour | WordArt object. | 149
TextCirclePour | WordArt object. | 150
TextButtonPour | WordArt object. | 151
TextCurveUp | WordArt object. | 152
TextCurveDown | WordArt object. | 153
TextCascadeUp | WordArt object. | 154
TextCascadeDown | WordArt object. | 155
TextWave1 | WordArt object. | 156
TextWave2 | WordArt object. | 157
TextWave3 | WordArt object. | 158
TextWave4 | WordArt object. | 159
TextInflate | WordArt object. | 160
TextDeflate | WordArt object. | 161
TextInflateBottom | WordArt object. | 162
TextDeflateBottom | WordArt object. | 163
TextInflateTop | WordArt object. | 164
TextDeflateTop | WordArt object. | 165
TextDeflateInflate | WordArt object. | 166
TextDeflateInflateDeflate | WordArt object. | 167
TextFadeRight | WordArt object. | 168
TextFadeLeft | WordArt object. | 169
TextFadeUp | WordArt object. | 170
TextFadeDown | WordArt object. | 171
TextSlantUp | WordArt object. | 172
TextSlantDown | WordArt object. | 173
TextCanUp | WordArt object. | 174
TextCanDown | WordArt object. | 175
FlowChartAlternateProcess |  | 176
FlowChartOffpageConnector |  | 177
Callout90 |  | 178
AccentCallout90 |  | 179
BorderCallout90 |  | 180
AccentBorderCallout90 |  | 181
LeftRightUpArrow |  | 182
Sun |  | 183
Moon |  | 184
BracketPair |  | 185
BracePair |  | 186
Seal4 |  | 187
DoubleWave |  | 188
ActionButtonBlank |  | 189
ActionButtonHome |  | 190
ActionButtonHelp |  | 191
ActionButtonInformation |  | 192
ActionButtonForwardNext |  | 193
ActionButtonBackPrevious |  | 194
ActionButtonEnd |  | 195
ActionButtonBeginning |  | 196
ActionButtonReturn |  | 197
ActionButtonDocument |  | 198
ActionButtonSound |  | 199
ActionButtonMovie |  | 200
SingleCornerSnipped | Snip single corner rectangle object. | 203
TopCornersSnipped | Snip same side corner rectangle. | 204
DiagonalCornersSnipped | Snip diagonal corner rectangle. | 205
TopCornersOneRoundedOneSnipped | Snip and round single corner rectangle. | 206
SingleCornerRounded | Round single corner rectangle. | 207
TopCornersRounded | Round same side corner rectangle. | 208
DiagonalCornersRounded | Round diagonal corner rectangle. | 209
MinValue | Reserved for the system use. | -2

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | ShapeType


SignatureLine Class

Provides access to signature line properties.

For a list of all members of this type, see SignatureLine Members.

System.Object
Aspose.Words.Drawing.SignatureLine

[Visual Basic]
Public Class SignatureLine
[C#]
public class SignatureLine

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SignatureLine Members | Aspose.Words.Drawing Namespace


SignatureLine Members

SignatureLine overview

Public Instance Properties

AllowComments | Gets or sets a value indicating that the signer can add comments in the Sign dialog. Default value for this property is false.
DefaultInstructions | Gets or sets a value indicating that default instructions is shown in the Sign dialog. Default value for this property is true.
Email | Gets or sets suggested signer's e-mail address. Default value for this property is empty string (Empty).
Id | Gets or sets identifier for this signature line. This identifier can be associated with a digital signature, when signing document using DigitalSignatureUtil. This value must be unique and by default it is randomly generated new Guid (NewGuid).
Instructions | Gets or sets instructions to the signer that are displayed on signing the signature line. This property is ignored if DefaultInstructions is set. Default value for this property is empty string (Empty).
IsSigned | Indicates that signature line is signed by digital signature.
IsValid | Indicates that signature line is signed by digital signature and this digital signature is valid.
ProviderId | Gets or sets signature provider identifier for this signature line. Default value is "{00000000-0000-0000-0000-000000000000}".
ShowDate | Gets or sets a value indicating that sign date is shown in the signature line. Default value for this property is true.
Signer | Gets or sets suggested signer of the signature line. Default value for this property is empty string (Empty).
SignerTitle | Gets or sets suggested signer's title (for example, Manager). Default value for this property is empty string (Empty).

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


SignatureLine Properties

The properties of the SignatureLine class are listed below. For a complete list of SignatureLine class members, see the SignatureLine Members topic.

Public Instance Properties

AllowComments | Gets or sets a value indicating that the signer can add comments in the Sign dialog. Default value for this property is false.
DefaultInstructions | Gets or sets a value indicating that default instructions is shown in the Sign dialog. Default value for this property is true.
Email | Gets or sets suggested signer's e-mail address. Default value for this property is empty string (Empty).
Id | Gets or sets identifier for this signature line. This identifier can be associated with a digital signature, when signing document using DigitalSignatureUtil. This value must be unique and by default it is randomly generated new Guid (NewGuid).
Instructions | Gets or sets instructions to the signer that are displayed on signing the signature line. This property is ignored if DefaultInstructions is set. Default value for this property is empty string (Empty).
IsSigned | Indicates that signature line is signed by digital signature.
IsValid | Indicates that signature line is signed by digital signature and this digital signature is valid.
ProviderId | Gets or sets signature provider identifier for this signature line. Default value is "{00000000-0000-0000-0000-000000000000}".
ShowDate | Gets or sets a value indicating that sign date is shown in the signature line. Default value for this property is true.
Signer | Gets or sets suggested signer of the signature line. Default value for this property is empty string (Empty).
SignerTitle | Gets or sets suggested signer's title (for example, Manager). Default value for this property is empty string (Empty).

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


AllowComments Property

Aspose.Words

SignatureLine.AllowComments Property

Gets or sets a value indicating that the signer can add comments in the Sign dialog. Default value for this property is false.

[Visual Basic]
Public Property AllowComments As Boolean
[C#]
public bool AllowComments {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


DefaultInstructions Property

Aspose.Words

SignatureLine.DefaultInstructions Property

Gets or sets a value indicating that default instructions is shown in the Sign dialog. Default value for this property is true.

[Visual Basic]
Public Property DefaultInstructions As Boolean
[C#]
public bool DefaultInstructions {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


Email Property

Aspose.Words

SignatureLine.Email Property

Gets or sets suggested signer's e-mail address. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property Email As String
[C#]
public string Email {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


Id Property

Aspose.Words

SignatureLine.Id Property

Gets or sets identifier for this signature line.

This identifier can be associated with a digital signature, when signing document using DigitalSignatureUtil. This value must be unique and by default it is randomly generated new Guid (NewGuid).

[Visual Basic]
Public Property Id As Guid
[C#]
public Guid Id {get; set;}

Example

Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.

[C#]

[Description("WORDSNET-16868")]
        public static void SignSignatureLineUsingSignatureLineId()
        {
            string signPersonName = "Ron Williams";
            string srcDocumentPath = MyDir + "Document.docx";
            string dstDocumentPath = ArtifactsDir + "Document.Signed.docx";
            string certificatePath = MyDir + "morzal.pfx";
            string certificatePassword = "aw";

            // We need to create simple list with test signers for this example.
            CreateSignPersonData();
            Console.WriteLine("Test data successfully added!");

            // Get sign person object by name of the person who must sign a document.
            // This an example, in real use case you would return an object from a database.
            SignPersonTestClass signPersonInfo =
                (from c in gSignPersonList where c.Name == signPersonName select c).FirstOrDefault();

            if (signPersonInfo != null)
            {
                SignDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                Console.WriteLine("Document successfully signed!");
            }
            else
            {
                Console.WriteLine("Sign person does not exist, please check your parameters.");
            }

            // Now do something with a signed document, for example, save it to your database.
            // Use 'new Document(dstDocumentPath)' for loading a signed document.
        }

        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void SignDocument(string srcDocumentPath, string dstDocumentPath,
            SignPersonTestClass signPersonInfo, string certificatePath, string certificatePassword)
        {
            // Create new document instance based on a test file that we need to sign.
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);

            // Add info about responsible person who sign a document.
            SignatureLineOptions signatureLineOptions =
                new SignatureLineOptions { Signer = signPersonInfo.Name, SignerTitle = signPersonInfo.Position };

            // Add signature line for responsible person who sign a document.
            SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
            signatureLine.Id = signPersonInfo.PersonId;

            // Save a document with line signatures into temporary file for future signing.
            builder.Document.Save(dstDocumentPath);

            // Create holder of certificate instance based on your personal certificate.
            // This is the test certificate generated for this example.
            CertificateHolder certificateHolder = CertificateHolder.Create(certificatePath, certificatePassword);

            // Link our signature line with personal signature.
            SignOptions signOptions = new SignOptions
            {
                SignatureLineId = signPersonInfo.PersonId,
                SignatureLineImage = signPersonInfo.Image
            };

            // Sign a document which contains signature line with personal certificate.
            DigitalSignatureUtil.Sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }

#if !(NETSTANDARD2_0 || __MOBILE__)
        /// <summary>
        /// Converting image file to bytes array
        /// </summary>
        private static byte[] ImageToByteArray(Image imageIn)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                imageIn.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
#endif

        /// <summary>
        /// Create test data that contains info about sing persons
        /// </summary>
        private static void CreateSignPersonData()
        {
            gSignPersonList = new List<SignPersonTestClass>
            {
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes),
#else
                new SignPersonTestClass(Guid.NewGuid(), "Ron Williams", "Chief Executive Officer",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png"))),
#endif
#if NETSTANDARD2_0 || __MOBILE__
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance", SkiaSharp.SKBitmap.Decode(ImageDir + "LogoSmall.png").Bytes)
#else
                new SignPersonTestClass(Guid.NewGuid(), "Stephen Morse", "Head of Compliance",
                    ImageToByteArray(Image.FromFile(ImageDir + "LogoSmall.png")))
#endif
            };
        }

        private static List<SignPersonTestClass> gSignPersonList;

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


Instructions Property

Aspose.Words

SignatureLine.Instructions Property

Gets or sets instructions to the signer that are displayed on signing the signature line. This property is ignored if DefaultInstructions is set. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property Instructions As String
[C#]
public string Instructions {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


IsSigned Property

Aspose.Words

SignatureLine.IsSigned Property

Indicates that signature line is signed by digital signature.

[Visual Basic]
Public ReadOnly Property IsSigned As Boolean
[C#]
public bool IsSigned {get;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


IsValid Property

Aspose.Words

SignatureLine.IsValid Property

Indicates that signature line is signed by digital signature and this digital signature is valid.

[Visual Basic]
Public ReadOnly Property IsValid As Boolean
[C#]
public bool IsValid {get;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


ProviderId Property

Aspose.Words

SignatureLine.ProviderId Property

Gets or sets signature provider identifier for this signature line. Default value is "{00000000-0000-0000-0000-000000000000}".

[Visual Basic]
Public Property ProviderId As Guid
[C#]
public Guid ProviderId {get; set;}

Remarks

The cryptographic service provider (CSP) is an independent software module that actually performs cryptography algorithms for authentication, encoding, and encryption. MS Office reserves the value of {00000000-0000-0000-0000-000000000000} for its default signature provider.

The GUID of the additionally installed provider should be obtained from the documentation shipped with the provider.

In addition, all the installed cryptographic providers are enumerated in windows registry. It can be found in the following path: HKLM\SOFTWARE\Microsoft\Cryptography\Defaults\Provider. There is a key name "CP Service UUID" which corresponds to a GUID of signature provider.

Example

Shows how to sign document with personal certificate and specific signatire line.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

SignatureLineOptions signatureLineOptions = new SignatureLineOptions
{
    Signer = "vderyushev",
    SignerTitle = "QA",
    Email = "vderyushev@aspose.com",
    ShowDate = true,
    DefaultInstructions = false,
    Instructions = "You need more info about signature line",
    AllowComments = true
};

SignatureLine signatureLine = builder.InsertSignatureLine(signatureLineOptions).SignatureLine;
signatureLine.ProviderId = Guid.Parse("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2");

doc.Save(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx");

SignOptions signOptions = new SignOptions();
signOptions.SignatureLineId = signatureLine.Id;
signOptions.ProviderId = signatureLine.ProviderId;
signOptions.Comments = "Document was signed by vderyushev";
signOptions.SignTime = DateTime.Now;

CertificateHolder certHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

DigitalSignatureUtil.Sign(ArtifactsDir + "DocumentBuilder.SignatureLineProviderId In.docx", ArtifactsDir + "DocumentBuilder.SignatureLineProviderId Out.docx", certHolder, signOptions);

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


ShowDate Property

Aspose.Words

SignatureLine.ShowDate Property

Gets or sets a value indicating that sign date is shown in the signature line. Default value for this property is true.

[Visual Basic]
Public Property ShowDate As Boolean
[C#]
public bool ShowDate {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


Signer Property

Aspose.Words

SignatureLine.Signer Property

Gets or sets suggested signer of the signature line. Default value for this property is empty string (Empty).

[Visual Basic]
Public Property Signer As String
[C#]
public string Signer {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


SignerTitle Property

Aspose.Words

SignatureLine.SignerTitle Property

Gets or sets suggested signer's title (for example, Manager). Default value for this property is empty string (Empty).

[Visual Basic]
Public Property SignerTitle As String
[C#]
public string SignerTitle {get; set;}

Example

Shows how to create a line for a signature and insert it into a document.

[C#]

// Create a blank document and its DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The SignatureLineOptions will contain all the data that the signature line will display
SignatureLineOptions options = new SignatureLineOptions
{
    AllowComments = true,
    DefaultInstructions = true,
    Email = "john.doe@management.com",
    Instructions = "Please sign here",
    ShowDate = true,
    Signer = "John Doe",
    SignerTitle = "Senior Manager"
};

// Insert the signature line, applying our SignatureLineOptions
// We can control where the signature line will appear on the page using a combination of left/top indents and margin-relative positions
// Since we're placing the signature line at the bottom right of the page, we will need to use negative indents to move it into view
Shape shape = builder.InsertSignatureLine(options, RelativeHorizontalPosition.RightMargin, -170.0, RelativeVerticalPosition.BottomMargin, -60.0, WrapType.None);
Assert.True(shape.IsSignatureLine);

// The SignatureLine object is a member of the shape that contains it
SignatureLine signatureLine = shape.SignatureLine;

Assert.AreEqual("john.doe@management.com", signatureLine.Email);
Assert.AreEqual("John Doe", signatureLine.Signer);
Assert.AreEqual("Senior Manager", signatureLine.SignerTitle);
Assert.AreEqual("Please sign here", signatureLine.Instructions);
Assert.True(signatureLine.ShowDate);

Assert.True(signatureLine.AllowComments);
Assert.True(signatureLine.DefaultInstructions);

// We will be prompted to sign it when we open the document
Assert.False(signatureLine.IsSigned);

// The object may be valid, but the signature itself isn't until it is signed
Assert.False(signatureLine.IsValid);

doc.Save(ArtifactsDir + "Drawing.SignatureLine.docx");

See Also

SignatureLine Class | Aspose.Words.Drawing Namespace


Stroke Class

Defines a stroke for a shape.

For a list of all members of this type, see Stroke Members.

System.Object
Aspose.Words.Drawing.Stroke

[Visual Basic]
Public Class Stroke
[C#]
public class Stroke

Remarks

Use the Stroke property to access stroke properties of a shape. You do not create instances of the Stroke class directly.

Example

Shows how change stroke properties

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new shape of type Rectangle
Shape rectangle = new Shape(doc, ShapeType.Rectangle);

//Change stroke properties
Stroke stroke = rectangle.Stroke;
stroke.On = true;
stroke.Weight = 5;
stroke.Color = Color.Red;
stroke.DashStyle = DashStyle.ShortDashDotDot;
stroke.JoinStyle = JoinStyle.Miter;
stroke.EndCap = EndCap.Square;
stroke.LineStyle = ShapeLineStyle.Triple;

//Insert shape object
builder.InsertNode(rectangle);

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Stroke Members | Aspose.Words.Drawing Namespace | Stroke


Stroke Members

Stroke overview

Public Instance Properties

Color | Defines the color of a stroke.
Color2 | Defines a second color for a stroke.
DashStyle | Specifies the dot and dash pattern for a stroke.
EndArrowLength | Defines the arrowhead length for the end of a stroke.
EndArrowType | Defines the arrowhead for the end of a stroke.
EndArrowWidth | Defines the arrowhead width for the end of a stroke.
EndCap | Defines the cap style for the end of a stroke.
ImageBytes | Defines the image for a stroke image or pattern fill.
JoinStyle | Defines the join style of a polyline.
LineStyle | Defines the line style of the stroke.
On | Defines whether the path will be stroked.
Opacity | Defines the amount of transparency of a stroke. Valid range is from 0 to 1.
StartArrowLength | Defines the arrowhead length for the start of a stroke.
StartArrowType | Defines the arrowhead for the start of a stroke.
StartArrowWidth | Defines the arrowhead width for the start of a stroke.
Weight | Defines the brush thickness that strokes the path of a shape in points.

See Also

Stroke Class | Aspose.Words.Drawing Namespace | Stroke


Stroke Properties

The properties of the Stroke class are listed below. For a complete list of Stroke class members, see the Stroke Members topic.

Public Instance Properties

Color | Defines the color of a stroke.
Color2 | Defines a second color for a stroke.
DashStyle | Specifies the dot and dash pattern for a stroke.
EndArrowLength | Defines the arrowhead length for the end of a stroke.
EndArrowType | Defines the arrowhead for the end of a stroke.
EndArrowWidth | Defines the arrowhead width for the end of a stroke.
EndCap | Defines the cap style for the end of a stroke.
ImageBytes | Defines the image for a stroke image or pattern fill.
JoinStyle | Defines the join style of a polyline.
LineStyle | Defines the line style of the stroke.
On | Defines whether the path will be stroked.
Opacity | Defines the amount of transparency of a stroke. Valid range is from 0 to 1.
StartArrowLength | Defines the arrowhead length for the start of a stroke.
StartArrowType | Defines the arrowhead for the start of a stroke.
StartArrowWidth | Defines the arrowhead width for the start of a stroke.
Weight | Defines the brush thickness that strokes the path of a shape in points.

See Also

Stroke Class | Aspose.Words.Drawing Namespace | Stroke


Color Property

Aspose.Words

Stroke.Color Property

Defines the color of a stroke.

[Visual Basic]
Public Property Color As Color
[C#]
public Color Color {get; set;}

Remarks

The default value is Black.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


Color2 Property

Aspose.Words

Stroke.Color2 Property

Defines a second color for a stroke.

[Visual Basic]
Public Property Color2 As Color
[C#]
public Color Color2 {get; set;}

Remarks

The default value is White.

Example

Shows how to process shape stroke features from older versions of Microsoft Word.

[C#]

// Open a document which contains a rectangle with a thick, two-tone-patterned outline
// These features cannot be recreated in new versions of Microsoft Word, so we will open an older .doc file
Document doc = new Document(MyDir + "Shape.StrokePattern.doc");

// Get the first shape's stroke
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
Stroke s = shape.Stroke;

// Every stroke will have a Color attribute, but only strokes from older Word versions have a Color2 attribute,
// since the two-tone pattern line feature which requires the Color2 attribute is no longer supported
Assert.AreEqual(Color.FromArgb(255, 128, 0, 0), s.Color);
Assert.AreEqual(Color.FromArgb(255, 255, 255, 0), s.Color2);

// This attribute contains the image data for the pattern, which we can save to our local file system
Assert.NotNull(s.ImageBytes);
File.WriteAllBytes(ArtifactsDir + "Drawing.StrokePattern.png", s.ImageBytes);

See Also

Stroke Class | Aspose.Words.Drawing Namespace


DashStyle Property

Aspose.Words

Stroke.DashStyle Property

Specifies the dot and dash pattern for a stroke.

[Visual Basic]
Public Property DashStyle As DashStyle
[C#]
public DashStyle DashStyle {get; set;}

Remarks

The default value is Solid.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


EndArrowLength Property

Aspose.Words

Stroke.EndArrowLength Property

Defines the arrowhead length for the end of a stroke.

[Visual Basic]
Public Property EndArrowLength As ArrowLength
[C#]
public ArrowLength EndArrowLength {get; set;}

Remarks

The default value is Medium.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


EndArrowType Property

Aspose.Words

Stroke.EndArrowType Property

Defines the arrowhead for the end of a stroke.

[Visual Basic]
Public Property EndArrowType As ArrowType
[C#]
public ArrowType EndArrowType {get; set;}

Remarks

The default value is None.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


EndArrowWidth Property

Aspose.Words

Stroke.EndArrowWidth Property

Defines the arrowhead width for the end of a stroke.

[Visual Basic]
Public Property EndArrowWidth As ArrowWidth
[C#]
public ArrowWidth EndArrowWidth {get; set;}

Remarks

The default value is Medium.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


EndCap Property

Aspose.Words

Stroke.EndCap Property

Defines the cap style for the end of a stroke.

[Visual Basic]
Public Property EndCap As EndCap
[C#]
public EndCap EndCap {get; set;}

Remarks

The default value is Flat.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


ImageBytes Property

Aspose.Words

Stroke.ImageBytes Property

Defines the image for a stroke image or pattern fill.

[Visual Basic]
Public ReadOnly Property ImageBytes As Byte()
[C#]
public byte[] ImageBytes {get;}

Example

Shows how to process shape stroke features from older versions of Microsoft Word.

[C#]

// Open a document which contains a rectangle with a thick, two-tone-patterned outline
// These features cannot be recreated in new versions of Microsoft Word, so we will open an older .doc file
Document doc = new Document(MyDir + "Shape.StrokePattern.doc");

// Get the first shape's stroke
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
Stroke s = shape.Stroke;

// Every stroke will have a Color attribute, but only strokes from older Word versions have a Color2 attribute,
// since the two-tone pattern line feature which requires the Color2 attribute is no longer supported
Assert.AreEqual(Color.FromArgb(255, 128, 0, 0), s.Color);
Assert.AreEqual(Color.FromArgb(255, 255, 255, 0), s.Color2);

// This attribute contains the image data for the pattern, which we can save to our local file system
Assert.NotNull(s.ImageBytes);
File.WriteAllBytes(ArtifactsDir + "Drawing.StrokePattern.png", s.ImageBytes);

See Also

Stroke Class | Aspose.Words.Drawing Namespace


JoinStyle Property

Aspose.Words

Stroke.JoinStyle Property

Defines the join style of a polyline.

[Visual Basic]
Public Property JoinStyle As JoinStyle
[C#]
public JoinStyle JoinStyle {get; set;}

Remarks

The default value is Round.

Example

Shows how change stroke properties

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new shape of type Rectangle
Shape rectangle = new Shape(doc, ShapeType.Rectangle);

//Change stroke properties
Stroke stroke = rectangle.Stroke;
stroke.On = true;
stroke.Weight = 5;
stroke.Color = Color.Red;
stroke.DashStyle = DashStyle.ShortDashDotDot;
stroke.JoinStyle = JoinStyle.Miter;
stroke.EndCap = EndCap.Square;
stroke.LineStyle = ShapeLineStyle.Triple;

//Insert shape object
builder.InsertNode(rectangle);

See Also

Stroke Class | Aspose.Words.Drawing Namespace


LineStyle Property

Aspose.Words

Stroke.LineStyle Property

Defines the line style of the stroke.

[Visual Basic]
Public Property LineStyle As ShapeLineStyle
[C#]
public ShapeLineStyle LineStyle {get; set;}

Remarks

The default value is Single.

Example

Shows how change stroke properties

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new shape of type Rectangle
Shape rectangle = new Shape(doc, ShapeType.Rectangle);

//Change stroke properties
Stroke stroke = rectangle.Stroke;
stroke.On = true;
stroke.Weight = 5;
stroke.Color = Color.Red;
stroke.DashStyle = DashStyle.ShortDashDotDot;
stroke.JoinStyle = JoinStyle.Miter;
stroke.EndCap = EndCap.Square;
stroke.LineStyle = ShapeLineStyle.Triple;

//Insert shape object
builder.InsertNode(rectangle);

See Also

Stroke Class | Aspose.Words.Drawing Namespace


On Property

Aspose.Words

Stroke.On Property

Defines whether the path will be stroked.

[Visual Basic]
Public Property On As Boolean
[C#]
public bool On {get; set;}

Remarks

The default value is true.

Example

Shows how change stroke properties

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new shape of type Rectangle
Shape rectangle = new Shape(doc, ShapeType.Rectangle);

//Change stroke properties
Stroke stroke = rectangle.Stroke;
stroke.On = true;
stroke.Weight = 5;
stroke.Color = Color.Red;
stroke.DashStyle = DashStyle.ShortDashDotDot;
stroke.JoinStyle = JoinStyle.Miter;
stroke.EndCap = EndCap.Square;
stroke.LineStyle = ShapeLineStyle.Triple;

//Insert shape object
builder.InsertNode(rectangle);

See Also

Stroke Class | Aspose.Words.Drawing Namespace


Opacity Property

Aspose.Words

Stroke.Opacity Property

Defines the amount of transparency of a stroke. Valid range is from 0 to 1.

[Visual Basic]
Public Property Opacity As Double
[C#]
public double Opacity {get; set;}

Remarks

The default value is 1.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


StartArrowLength Property

Aspose.Words

Stroke.StartArrowLength Property

Defines the arrowhead length for the start of a stroke.

[Visual Basic]
Public Property StartArrowLength As ArrowLength
[C#]
public ArrowLength StartArrowLength {get; set;}

Remarks

The default value is Medium.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


StartArrowType Property

Aspose.Words

Stroke.StartArrowType Property

Defines the arrowhead for the start of a stroke.

[Visual Basic]
Public Property StartArrowType As ArrowType
[C#]
public ArrowType StartArrowType {get; set;}

Remarks

The default value is None.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


StartArrowWidth Property

Aspose.Words

Stroke.StartArrowWidth Property

Defines the arrowhead width for the start of a stroke.

[Visual Basic]
Public Property StartArrowWidth As ArrowWidth
[C#]
public ArrowWidth StartArrowWidth {get; set;}

Remarks

The default value is Medium.

Example

Shows to create a variety of shapes.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Draw a dotted horizontal half-transparent red line with an arrow on the left end and a diamond on the other
Shape arrow = new Shape(doc, ShapeType.Line);
arrow.Width = 200;
arrow.Stroke.Color = Color.Red;
arrow.Stroke.StartArrowType = ArrowType.Arrow;
arrow.Stroke.StartArrowLength = ArrowLength.Long;
arrow.Stroke.StartArrowWidth = ArrowWidth.Wide;
arrow.Stroke.EndArrowType = ArrowType.Diamond;
arrow.Stroke.EndArrowLength = ArrowLength.Long;
arrow.Stroke.EndArrowWidth = ArrowWidth.Wide;
arrow.Stroke.DashStyle = DashStyle.Dash;
arrow.Stroke.Opacity = 0.5;

Assert.AreEqual(JoinStyle.Miter, arrow.Stroke.JoinStyle);

builder.InsertNode(arrow);

// Draw a thick black diagonal line with rounded ends
Shape line = new Shape(doc, ShapeType.Line);
line.Top = 40;
line.Width = 200;
line.Height = 20;
line.StrokeWeight = 5.0;
line.Stroke.EndCap = EndCap.Round;

builder.InsertNode(line);

// Draw an arrow with a green fill
Shape filledInArrow = new Shape(doc, ShapeType.Arrow);
filledInArrow.Width = 200;
filledInArrow.Height = 40;
filledInArrow.Top = 100;
filledInArrow.Fill.Color = Color.Green;
filledInArrow.Fill.On = true;

builder.InsertNode(filledInArrow);

// Draw an arrow filled in with the Aspose logo and flip its orientation
Shape filledInArrowImg = new Shape(doc, ShapeType.Arrow);
filledInArrowImg.Width = 200;
filledInArrowImg.Height = 40;
filledInArrowImg.Top = 160;
filledInArrowImg.FlipOrientation = FlipOrientation.Both;

using (WebClient webClient = new WebClient())
{
    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);

    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageBytes))
    {
        Image image = Image.FromStream(stream);
        // When we flipped the orientation of our arrow, the image content was flipped too
        // If we want it to be displayed the right side up, we have to reverse the arrow flip on the image
        image.RotateFlip(RotateFlipType.RotateNoneFlipXY);

        filledInArrowImg.ImageData.SetImage(image);
        filledInArrowImg.Stroke.JoinStyle = JoinStyle.Round;

        builder.InsertNode(filledInArrowImg);
    }
}

doc.Save(ArtifactsDir + "Drawing.VariousShapes.docx");

See Also

Stroke Class | Aspose.Words.Drawing Namespace


Weight Property

Aspose.Words

Stroke.Weight Property

Defines the brush thickness that strokes the path of a shape in points.

[Visual Basic]
Public Property Weight As Double
[C#]
public double Weight {get; set;}

Remarks

The default value is 0.75.

Example

Shows how change stroke properties

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a new shape of type Rectangle
Shape rectangle = new Shape(doc, ShapeType.Rectangle);

//Change stroke properties
Stroke stroke = rectangle.Stroke;
stroke.On = true;
stroke.Weight = 5;
stroke.Color = Color.Red;
stroke.DashStyle = DashStyle.ShortDashDotDot;
stroke.JoinStyle = JoinStyle.Miter;
stroke.EndCap = EndCap.Square;
stroke.LineStyle = ShapeLineStyle.Triple;

//Insert shape object
builder.InsertNode(rectangle);

See Also

Stroke Class | Aspose.Words.Drawing Namespace


TextBox Class

Defines attributes that specify how a text is displayed inside a shape.

For a list of all members of this type, see TextBox Members.

System.Object
Aspose.Words.Drawing.TextBox

[Visual Basic]
Public Class TextBox
[C#]
public class TextBox

Remarks

Use the TextBox property to access text properties of a shape. You do not create instances of the TextBox class directly.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TextBox Members | Aspose.Words.Drawing Namespace | TextBox


TextBox Members

TextBox overview

Public Instance Properties

FitShapeToText | Determines whether Microsoft Word will grow the shape to fit text.
InternalMarginBottom | Specifies the inner bottom margin in points for a shape.
InternalMarginLeft | Specifies the inner left margin in points for a shape.
InternalMarginRight | Specifies the inner right margin in points for a shape.
InternalMarginTop | Specifies the inner top margin in points for a shape.
LayoutFlow | Determines the flow of the text layout in a shape.
Next | Returns or sets a TextBox that represents the next TextBox in a sequence of shapes.
Parent | Gets a parent shape for the TextBox.
Previous | Returns a TextBox that represents the previous TextBox in a sequence of shapes.
TextBoxWrapMode | Determines how text wraps inside a shape.
VerticalAnchor | Specifies the vertical alignment of the text within a shape.

Public Instance Methods

BreakForwardLink | Breaks the link to the next TextBox.
IsValidLinkTarget | Determines whether this TextBox can be linked to the target Textbox.

See Also

TextBox Class | Aspose.Words.Drawing Namespace | TextBox


TextBox Properties

The properties of the TextBox class are listed below. For a complete list of TextBox class members, see the TextBox Members topic.

Public Instance Properties

FitShapeToText | Determines whether Microsoft Word will grow the shape to fit text.
InternalMarginBottom | Specifies the inner bottom margin in points for a shape.
InternalMarginLeft | Specifies the inner left margin in points for a shape.
InternalMarginRight | Specifies the inner right margin in points for a shape.
InternalMarginTop | Specifies the inner top margin in points for a shape.
LayoutFlow | Determines the flow of the text layout in a shape.
Next | Returns or sets a TextBox that represents the next TextBox in a sequence of shapes.
Parent | Gets a parent shape for the TextBox.
Previous | Returns a TextBox that represents the previous TextBox in a sequence of shapes.
TextBoxWrapMode | Determines how text wraps inside a shape.
VerticalAnchor | Specifies the vertical alignment of the text within a shape.

See Also

TextBox Class | Aspose.Words.Drawing Namespace | TextBox


FitShapeToText Property

Aspose.Words

TextBox.FitShapeToText Property

Determines whether Microsoft Word will grow the shape to fit text.

[Visual Basic]
Public Property FitShapeToText As Boolean
[C#]
public bool FitShapeToText {get; set;}

Remarks

The default value is false.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


InternalMarginBottom Property

Aspose.Words

TextBox.InternalMarginBottom Property

Specifies the inner bottom margin in points for a shape.

[Visual Basic]
Public Property InternalMarginBottom As Double
[C#]
public double InternalMarginBottom {get; set;}

Remarks

The default value is 1/20 inch.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


InternalMarginLeft Property

Aspose.Words

TextBox.InternalMarginLeft Property

Specifies the inner left margin in points for a shape.

[Visual Basic]
Public Property InternalMarginLeft As Double
[C#]
public double InternalMarginLeft {get; set;}

Remarks

The default value is 1/10 inch.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


InternalMarginRight Property

Aspose.Words

TextBox.InternalMarginRight Property

Specifies the inner right margin in points for a shape.

[Visual Basic]
Public Property InternalMarginRight As Double
[C#]
public double InternalMarginRight {get; set;}

Remarks

The default value is 1/10 inch.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


InternalMarginTop Property

Aspose.Words

TextBox.InternalMarginTop Property

Specifies the inner top margin in points for a shape.

[Visual Basic]
Public Property InternalMarginTop As Double
[C#]
public double InternalMarginTop {get; set;}

Remarks

The default value is 1/20 inch.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


LayoutFlow Property

Aspose.Words

TextBox.LayoutFlow Property

Determines the flow of the text layout in a shape.

[Visual Basic]
Public Property LayoutFlow As LayoutFlow
[C#]
public LayoutFlow LayoutFlow {get; set;}

Remarks

The default value is Horizontal.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


Next Property

Aspose.Words

TextBox.Next Property

Returns or sets a TextBox that represents the next TextBox in a sequence of shapes.

[Visual Basic]
Public Property Next As TextBox
[C#]
public TextBox Next {get; set;}

See Also

TextBox Class | Aspose.Words.Drawing Namespace


Parent Property

Aspose.Words

TextBox.Parent Property

Gets a parent shape for the TextBox.

[Visual Basic]
Public ReadOnly Property Parent As Shape
[C#]
public Shape Parent {get;}

See Also

TextBox Class | Aspose.Words.Drawing Namespace


Previous Property

Aspose.Words

TextBox.Previous Property

Returns a TextBox that represents the previous TextBox in a sequence of shapes.

[Visual Basic]
Public ReadOnly Property Previous As TextBox
[C#]
public TextBox Previous {get;}

See Also

TextBox Class | Aspose.Words.Drawing Namespace


TextBoxWrapMode Property

Aspose.Words

TextBox.TextBoxWrapMode Property

Determines how text wraps inside a shape.

[Visual Basic]
Public Property TextBoxWrapMode As TextBoxWrapMode
[C#]
public TextBoxWrapMode TextBoxWrapMode {get; set;}

Remarks

The default value is Square.

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


VerticalAnchor Property

Aspose.Words

TextBox.VerticalAnchor Property

Specifies the vertical alignment of the text within a shape.

[Visual Basic]
Public Property VerticalAnchor As TextBoxAnchor
[C#]
public TextBoxAnchor VerticalAnchor {get; set;}

Remarks

The default value is Top.

Example

Shows how to change text position inside textbox shape.

[C#]

Document doc = new Document(MyDir + "Shape.GetTextBoxAndChangeAnchor.docx");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

Shape textbox = (Shape) shapes[0];
textbox.TextBox.VerticalAnchor = TextBoxAnchor.Bottom;

doc.Save(ArtifactsDir + "Shape.GetTextBoxAndChangeAnchor.docx");

See Also

TextBox Class | Aspose.Words.Drawing Namespace


TextBox Methods

The methods of the TextBox class are listed below. For a complete list of TextBox class members, see the TextBox Members topic.

Public Instance Methods

BreakForwardLink | Breaks the link to the next TextBox.
IsValidLinkTarget | Determines whether this TextBox can be linked to the target Textbox.

See Also

TextBox Class | Aspose.Words.Drawing Namespace | TextBox


TextBox.BreakForwardLink Method

Breaks the link to the next TextBox.

[Visual Basic]
Public Sub BreakForwardLink()
[C#]
public void BreakForwardLink();

Remarks

BreakForwardLink() doesn't break all other links in the current sequence of shapes. For example: 1-2-3-4 sequence and BreakForwardLink at the 2-nd textbox will create two sequences 1-2, 3-4.

See Also

TextBox Class | Aspose.Words.Drawing Namespace


TextBox.IsValidLinkTarget Method

Determines whether this TextBox can be linked to the target Textbox.

[Visual Basic]
Public Function IsValidLinkTarget( _
ByVal target As TextBox _
) As Boolean
[C#]
public bool IsValidLinkTarget(
TextBox target
);

See Also

TextBox Class | Aspose.Words.Drawing Namespace


TextBoxAnchor Enumeration

Specifies values used for shape text vertical alignment.

[Visual Basic]
Public Enum TextBoxAnchor
[C#]
public enum TextBoxAnchor

Example

Shows how to change text position inside textbox shape.

[C#]

Document doc = new Document(MyDir + "Shape.GetTextBoxAndChangeAnchor.docx");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

Shape textbox = (Shape) shapes[0];
textbox.TextBox.VerticalAnchor = TextBoxAnchor.Bottom;

doc.Save(ArtifactsDir + "Shape.GetTextBoxAndChangeAnchor.docx");

Members

Member Name | Description | Value
Top | Text is aligned to the top of the textbox. | 0
Middle | Text is aligned to the middle of the textbox. | 1
Bottom | Text is aligned to the bottom of the textbox. | 2
TopCentered | Text is aligned to the top centered of the textbox. | 3
MiddleCentered | Text is aligned to the middle centered of the textbox. | 4
BottomCentered | Text is aligned to the bottom centered of the textbox. | 5
TopBaseline | Text is aligned to the top baseline of the textbox. | 6
BottomBaseline | Text is aligned to the bottom baseline of the textbox. | 7
TopCenteredBaseline | Text is aligned to the top centered baseline of the textbox. | 8
BottomCenteredBaseline | Text is aligned to the bottom centered baseline of the textbox. | 9

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace


TextBoxWrapMode Enumeration

Specifies how text wraps inside a shape.

[Visual Basic]
Public Enum TextBoxWrapMode
[C#]
public enum TextBoxWrapMode

Example

Shows how to insert text boxes and arrange their text.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a shape that contains a TextBox
Shape textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
TextBox textBox = textBoxShape.TextBox;

// Move the document builder to inside the TextBox and write text
builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Vertical text");

// Text is displayed vertically, written top to bottom
textBox.LayoutFlow = LayoutFlow.TopToBottomIdeographic;

// Move the builder out of the shape and back into the main document body
builder.MoveTo(textBoxShape.ParentParagraph);

// Insert another TextBox
textBoxShape = builder.InsertShape(ShapeType.TextBox, 150, 100);
textBox = textBoxShape.TextBox;

// Apply these values to both these members to get the parent shape to defy the dimensions we set to fit tightly around the TextBox's text
textBox.FitShapeToText = true;
textBox.TextBoxWrapMode = TextBoxWrapMode.None;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text fit tightly inside textbox");

builder.MoveTo(textBoxShape.ParentParagraph);

textBoxShape = builder.InsertShape(ShapeType.TextBox, 100, 100);
textBox = textBoxShape.TextBox;

// Set margins for the textbox
textBox.InternalMarginTop = 15;
textBox.InternalMarginBottom = 15;
textBox.InternalMarginLeft = 15;
textBox.InternalMarginRight = 15;

builder.MoveTo(textBoxShape.LastParagraph);
builder.Write("Text placed according to textbox margins");

doc.Save(ArtifactsDir + "Drawing.TextBox.docx");

Members

Member Name | Description | Value
Square | Text wraps inside a shape. | 0
None | Text does not wrap inside a shape. | 2

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace


TextPath Class

Defines the text and formatting of the text path (of a WordArt object).

For a list of all members of this type, see TextPath Members.

System.Object
Aspose.Words.Drawing.TextPath

[Visual Basic]
Public Class TextPath
[C#]
public class TextPath

Remarks

Use the TextPath property to access WordArt properties of a shape. You do not create instances of the TextPath class directly.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TextPath Members | Aspose.Words.Drawing Namespace | TextPath


TextPath Members

TextPath overview

Public Instance Properties

Bold | True if the font is formatted as bold.
FitPath | Defines whether the text fits the path of a shape.
FitShape | Defines whether the text fits bounding box of a shape.
FontFamily | Defines the family of the textpath font.
Italic | True if the font is formatted as italic.
Kerning | Determines whether kerning is turned on.
On | Defines whether the text is displayed.
ReverseRows | Determines whether the layout order of rows is reversed.
RotateLetters | Determines whether the letters of the text are rotated.
SameLetterHeights | Determines whether all letters will be the same height regardless of initial case.
Shadow | Defines whether a shadow is applied to the text on a text path.
Size | Defines the size of the font in points.
SmallCaps | True if the font is formatted as small capital letters.
Spacing | Defines the amount of spacing for text. 1 means 100%.
StrikeThrough | True if the font is formatted as strikethrough text.
Text | Defines the text of the text path.
TextPathAlignment | Defines the alignment of text.
Trim | Determines whether extra space is removed above and below the text.
Underline | True if the font is underlined.
XScale | Determines whether a straight textpath will be used instead of the shape path.

See Also

TextPath Class | Aspose.Words.Drawing Namespace | TextPath


TextPath Properties

The properties of the TextPath class are listed below. For a complete list of TextPath class members, see the TextPath Members topic.

Public Instance Properties

Bold | True if the font is formatted as bold.
FitPath | Defines whether the text fits the path of a shape.
FitShape | Defines whether the text fits bounding box of a shape.
FontFamily | Defines the family of the textpath font.
Italic | True if the font is formatted as italic.
Kerning | Determines whether kerning is turned on.
On | Defines whether the text is displayed.
ReverseRows | Determines whether the layout order of rows is reversed.
RotateLetters | Determines whether the letters of the text are rotated.
SameLetterHeights | Determines whether all letters will be the same height regardless of initial case.
Shadow | Defines whether a shadow is applied to the text on a text path.
Size | Defines the size of the font in points.
SmallCaps | True if the font is formatted as small capital letters.
Spacing | Defines the amount of spacing for text. 1 means 100%.
StrikeThrough | True if the font is formatted as strikethrough text.
Text | Defines the text of the text path.
TextPathAlignment | Defines the alignment of text.
Trim | Determines whether extra space is removed above and below the text.
Underline | True if the font is underlined.
XScale | Determines whether a straight textpath will be used instead of the shape path.

See Also

TextPath Class | Aspose.Words.Drawing Namespace | TextPath


Bold Property

Aspose.Words

TextPath.Bold Property

True if the font is formatted as bold.

[Visual Basic]
Public Property Bold As Boolean
[C#]
public bool Bold {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


FitPath Property

Aspose.Words

TextPath.FitPath Property

Defines whether the text fits the path of a shape.

[Visual Basic]
Public Property FitPath As Boolean
[C#]
public bool FitPath {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


FitShape Property

Aspose.Words

TextPath.FitShape Property

Defines whether the text fits bounding box of a shape.

[Visual Basic]
Public Property FitShape As Boolean
[C#]
public bool FitShape {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


FontFamily Property

Aspose.Words

TextPath.FontFamily Property

Defines the family of the textpath font.

[Visual Basic]
Public Property FontFamily As String
[C#]
public string FontFamily {get; set;}

Remarks

The default value is Arial.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Italic Property

Aspose.Words

TextPath.Italic Property

True if the font is formatted as italic.

[Visual Basic]
Public Property Italic As Boolean
[C#]
public bool Italic {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Kerning Property

Aspose.Words

TextPath.Kerning Property

Determines whether kerning is turned on.

[Visual Basic]
Public Property Kerning As Boolean
[C#]
public bool Kerning {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


On Property

Aspose.Words

TextPath.On Property

Defines whether the text is displayed.

[Visual Basic]
Public Property On As Boolean
[C#]
public bool On {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


ReverseRows Property

Aspose.Words

TextPath.ReverseRows Property

Determines whether the layout order of rows is reversed.

[Visual Basic]
Public Property ReverseRows As Boolean
[C#]
public bool ReverseRows {get; set;}

Remarks

The default value is false.

If true, the layout order of rows is reversed. This attribute is used for vertical text layout.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


RotateLetters Property

Aspose.Words

TextPath.RotateLetters Property

Determines whether the letters of the text are rotated.

[Visual Basic]
Public Property RotateLetters As Boolean
[C#]
public bool RotateLetters {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


SameLetterHeights Property

Aspose.Words

TextPath.SameLetterHeights Property

Determines whether all letters will be the same height regardless of initial case.

[Visual Basic]
Public Property SameLetterHeights As Boolean
[C#]
public bool SameLetterHeights {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Shadow Property

Aspose.Words

TextPath.Shadow Property

Defines whether a shadow is applied to the text on a text path.

[Visual Basic]
Public Property Shadow As Boolean
[C#]
public bool Shadow {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Size Property

Aspose.Words

TextPath.Size Property

Defines the size of the font in points.

[Visual Basic]
Public Property Size As Double
[C#]
public double Size {get; set;}

Remarks

The default value is 36.

See Also

TextPath Class | Aspose.Words.Drawing Namespace


SmallCaps Property

Aspose.Words

TextPath.SmallCaps Property

True if the font is formatted as small capital letters.

[Visual Basic]
Public Property SmallCaps As Boolean
[C#]
public bool SmallCaps {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Spacing Property

Aspose.Words

TextPath.Spacing Property

Defines the amount of spacing for text. 1 means 100%.

[Visual Basic]
Public Property Spacing As Double
[C#]
public double Spacing {get; set;}

Remarks

The default value is 1.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


StrikeThrough Property

Aspose.Words

TextPath.StrikeThrough Property

True if the font is formatted as strikethrough text.

[Visual Basic]
Public Property StrikeThrough As Boolean
[C#]
public bool StrikeThrough {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Text Property

Aspose.Words

TextPath.Text Property

Defines the text of the text path.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Remarks

The default value is an empty string.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


TextPathAlignment Property

Aspose.Words

TextPath.TextPathAlignment Property

Defines the alignment of text.

[Visual Basic]
Public Property TextPathAlignment As TextPathAlignment
[C#]
public TextPathAlignment TextPathAlignment {get; set;}

Remarks

The default value is Center.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Trim Property

Aspose.Words

TextPath.Trim Property

Determines whether extra space is removed above and below the text.

[Visual Basic]
Public Property Trim As Boolean
[C#]
public bool Trim {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


Underline Property

Aspose.Words

TextPath.Underline Property

True if the font is underlined.

[Visual Basic]
Public Property Underline As Boolean
[C#]
public bool Underline {get; set;}

Remarks

The default value is false.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


XScale Property

Aspose.Words

TextPath.XScale Property

Determines whether a straight textpath will be used instead of the shape path.

[Visual Basic]
Public Property XScale As Boolean
[C#]
public bool XScale {get; set;}

Remarks

The default value is false.

If true, the text runs along a path from left to right along the x value of the lower boundary of the shape.

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

See Also

TextPath Class | Aspose.Words.Drawing Namespace


TextPathAlignment Enumeration

WordArt alignment.

[Visual Basic]
Public Enum TextPathAlignment
[C#]
public enum TextPathAlignment

Remarks

Example

Shows how to work with WordArt.

[C#]

public void InsertTextPaths()
{
    Document doc = new Document();

    // Insert a WordArt object and capture the shape that contains it in a variable
    Shape shape = AppendWordArt(doc, "Bold & Italic", "Arial", 240, 24, Color.White, Color.Black, ShapeType.TextPlainText);

    // View and verify various text formatting settings
    shape.TextPath.Bold = true;
    shape.TextPath.Italic = true;

    Assert.False(shape.TextPath.Underline);
    Assert.False(shape.TextPath.Shadow);
    Assert.False(shape.TextPath.StrikeThrough);
    Assert.False(shape.TextPath.ReverseRows);
    Assert.False(shape.TextPath.XScale);
    Assert.False(shape.TextPath.Trim);
    Assert.False(shape.TextPath.SmallCaps);

    Assert.AreEqual(36.0, shape.TextPath.Size);
    Assert.AreEqual("Bold & Italic", shape.TextPath.Text);
    Assert.AreEqual(ShapeType.TextPlainText, shape.ShapeType);

    // Toggle whether or not to display text
    shape = AppendWordArt(doc, "On set to true", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = true;

    shape = AppendWordArt(doc, "On set to false", "Calibri", 150, 24, Color.Yellow, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.On = false;

    // Apply kerning
    shape = AppendWordArt(doc, "Kerning: VAV", "Times New Roman", 90, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = true;

    shape = AppendWordArt(doc, "No kerning: VAV", "Times New Roman", 100, 24, Color.Orange, Color.Red, ShapeType.TextPlainText);
    shape.TextPath.Kerning = false;

    // Apply custom spacing, on a scale from 0.0 (none) to 1.0 (default)
    shape = AppendWordArt(doc, "Spacing set to 0.1", "Calibri", 120, 24, Color.BlueViolet, Color.Blue, ShapeType.TextCascadeDown);
    shape.TextPath.Spacing = 0.1;

    // Rotate letters 90 degrees to the left, text is still laid out horizontally
    shape = AppendWordArt(doc, "RotateLetters", "Calibri", 200, 36, Color.GreenYellow, Color.Green, ShapeType.TextWave);
    shape.TextPath.RotateLetters = true;

    // Set the x-height to equal the cap height
    shape = AppendWordArt(doc, "Same character height for lower and UPPER case", "Calibri", 300, 24, Color.DeepSkyBlue, Color.DodgerBlue, ShapeType.TextSlantUp);
    shape.TextPath.SameLetterHeights = true;

    // By default, the size of the text will scale to always fit the size of the containing shape, overriding the text size setting
    shape = AppendWordArt(doc, "FitShape on", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    Assert.True(shape.TextPath.FitShape);
    shape.TextPath.Size = 24.0;

    // If we set FitShape to false, the size of the text will defy the shape bounds and always keep the size value we set below
    // We can also set TextPathAlignment to align the text
    shape = AppendWordArt(doc, "FitShape off", "Calibri", 160, 24, Color.LightBlue, Color.Blue, ShapeType.TextPlainText);
    shape.TextPath.FitShape = false;
    shape.TextPath.Size = 24.0;
    shape.TextPath.TextPathAlignment = TextPathAlignment.Right;

    doc.Save(ArtifactsDir + "Drawing.TextPath.docx");
}

/// <summary>
/// Insert a new paragraph with a WordArt shape inside it
/// </summary>
private Shape AppendWordArt(Document doc, string text, string textFontFamily, double shapeWidth, double shapeHeight, Color wordArtFill, Color line, ShapeType wordArtShapeType)
{
    // Insert a new paragraph
    Paragraph para = (Paragraph)doc.FirstSection.Body.AppendChild(new Paragraph(doc));

    // Create an inline Shape, which will serve as a container for our WordArt, and append it to the paragraph
    // The shape can only be a valid WordArt shape if the ShapeType assigned here is a WordArt-designated ShapeType
    // These types will have "WordArt object" in the description and their enumerator names will start with "Text..."
    Shape shape = new Shape(doc, wordArtShapeType);
    shape.WrapType = WrapType.Inline;
    para.AppendChild(shape);

    // Set the shape's width and height
    shape.Width = shapeWidth;
    shape.Height = shapeHeight;

    // These color settings will apply to the letters of the displayed WordArt text
    shape.FillColor = wordArtFill;
    shape.StrokeColor = line;

    // The WordArt object is accessed here, and we will set the text and font like this
    shape.TextPath.Text = text;
    shape.TextPath.FontFamily = textFontFamily;

    return shape;
}

Members

Member Name | Description | Value
Stretch | Stretch each line of text to fit width. | 0
Center | Center text on width. | 1
Left | Left justify. | 2
Right | Right justify. | 3
LetterJustify | Spread letters out to fit width. | 4
WordJustify | Spread words out to fit width. | 5

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | TextPathAlignment


VerticalAlignment Enumeration

Specifies vertical alignment of a floating shape, text frame or a floating table.

[Visual Basic]
Public Enum VerticalAlignment
[C#]
public enum VerticalAlignment

Remarks

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");

Members

Member Name | Description | Value
None | The object is explicitly positioned, usually using its Top property. | 0
Top | Specifies that the object shall be at the top of the vertical alignment base. | 1
Center | Specifies that the object shall be centered with respect to the vertical alignment base. | 2
Bottom | Specifies that the object shall be at the bottom of the vertical alignment base. | 3
Inside | Specifies that the object shall be inside of the horizontal alignment base. | 4
Outside | Specifies that the object shall be outside of the vertical alignment base. | 5
Inline | Not documented. Seems to be a possible value for floating paragraphs and tables. | -1
Default | Same as None. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | VerticalAlignment


WrapSide Enumeration

Specifies what side(s) of the shape or picture the text wraps around.

[Visual Basic]
Public Enum WrapSide
[C#]
public enum WrapSide

Remarks

Example

Shows how to replace all textboxes with images.

[C#]

Document doc = new Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

// This gets a live collection of all shape nodes in the document.
NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

// Since we will be adding/removing nodes, it is better to copy all collection
// into a fixed size array, otherwise iterator will be invalidated.
Node[] shapes = shapeCollection.ToArray();

foreach (Shape shape in shapes.OfType<Shape>())
{
    // Filter out all shapes that we don't need.
    if (shape.ShapeType.Equals(ShapeType.TextBox))
    {
        // Create a new shape that will replace the existing shape.
        Shape image = new Shape(doc, ShapeType.Image);

        // Load the image into the new shape.
        image.ImageData.SetImage(ImageDir + "Hammer.wmf");

        // Make new shape's position to match the old shape.
        image.Left = shape.Left;
        image.Top = shape.Top;
        image.Width = shape.Width;
        image.Height = shape.Height;
        image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
        image.RelativeVerticalPosition = shape.RelativeVerticalPosition;
        image.HorizontalAlignment = shape.HorizontalAlignment;
        image.VerticalAlignment = shape.VerticalAlignment;
        image.WrapType = shape.WrapType;
        image.WrapSide = shape.WrapSide;

        // Insert new shape after the old shape and remove the old shape.
        shape.ParentNode.InsertAfter(image, shape);
        shape.Remove();
    }
}

doc.Save(ArtifactsDir + "Shape.ReplaceTextboxesWithImages.doc");

Members

Member Name | Description | Value
Both | The document text wraps on both sides of the shape. | 0
Left | The document text wraps on the left side of the shape only. There is a text free area on the right of the shape. | 1
Right | The document text wraps on the right side of the shape only. There is a text free area on the left side of the shape. | 2
Largest | The document text wraps on the side of the shape that is farthest from the page margin, leaving text free area on the other side of the shape. | 3
Default | Default value is Both. | 0

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | WrapSide


WrapType Enumeration

Specifies how text is wrapped around a shape or picture.

[Visual Basic]
Public Enum WrapType
[C#]
public enum WrapType

Remarks

Example

Shows how to insert a floating image in the middle of a page.

[C#]

// This creates a builder and also an empty document inside the builder.
DocumentBuilder builder = new DocumentBuilder();

// By default, the image is inline.
Shape shape = builder.InsertImage(MyDir + "Images/Aspose.Words.gif");

// Make the image float, put it behind text and center on the page.
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.HorizontalAlignment = HorizontalAlignment.Center;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;

builder.Document.Save(ArtifactsDir + "Image.CreateFloatingPageCenter.doc");
Inserts a watermark image into a document using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

Image image = Image.FromFile(ImageDir + "Watermark.png");

// Insert a floating picture.
Shape shape = builder.InsertImage(image);
shape.WrapType = WrapType.None;
shape.BehindText = true;

shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

// Calculate image left and top position so it appears in the center of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.doc");
Inserts a watermark image into a document using DocumentBuilder (.NetStandard 2.0).
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The best place for the watermark image is in the header or footer so it is shown on every page.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

using (SKBitmap image = SKBitmap.Decode(ImageDir + "Watermark.png"))
{
    // Insert a floating picture.
    Shape shape = builder.InsertImage(image);
    shape.WrapType = WrapType.None;
    shape.BehindText = true;

    shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;

    // Calculate image left and top position so it appears in the center of the page.
    shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
    shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;
}

doc.Save(ArtifactsDir + "DocumentBuilder.InsertWatermark.NetStandard2.doc");

Members

Member Name | Description | Value
None | No text wrapping around the shape. The shape is placed behind or in front of text. | 3
Inline | The shape remains on the same layer as text and treated as a character. | 0
TopBottom | The text stops at the top of the shape and restarts on the line below the shape. | 1
Square | Wraps text around all sides of the square bounding box of the shape. | 2
Tight | Wraps tightly around the edges of the shape, instead of wrapping around the bounding box. | 4
Through | Same as Tight, but wraps inside any parts of the shape that are open. | 5

Requirements

Namespace: Aspose.Words.Drawing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing Namespace | WrapType


Aspose.Words.Drawing.Charts

Aspose.Words

Aspose.Words.Drawing.Charts Namespace

The Aspose.Words.Drawing.Charts namespace provides classes that allow to access charts in Microsoft Word documents.

The chart supported are Word 2007 (or higher) DrawingML Charts.

Namespace hierarchy

Classes

Class | Description
AxisBound | Represents minimum or maximum bound of axis values.
AxisDisplayUnit | Provides access to the scaling options of the display units for the value axis.
AxisScaling | Represents the scaling options of the axis.
Chart | Provides access to the chart shape properties.
ChartAxis | Represents the axis options of the chart.
ChartDataLabel | Represents data label on a chart point or trendline.
ChartDataLabelCollection | Represents a collection of ChartDataLabel.
ChartDataPoint | Allows to specify formatting of a single data point on the chart.
ChartDataPointCollection | Represents collection of a ChartDataPoint.
ChartLegend | Represents chart legend properties.
ChartMarker | Represents a chart data marker.
ChartNumberFormat | Represents number formatting of the parent element.
ChartSeries | Represents chart series properties.
ChartSeriesCollection | Represents collection of a ChartSeries.
ChartTitle | Provides access to the chart title properties.

Interfaces

Interface | Description
IChartDataPoint | Contains properties of a single data point on the chart.

Enumerations

Enumeration | Description
AxisBuiltInUnit | Specifies the display units for an axis.
AxisCategoryType | Specifies type of a category axis.
AxisCrosses | Specifies the possible crossing points for an axis.
AxisScaleType | Specifies the possible scale types for an axis.
AxisTickLabelPosition | Specifies the possible positions for tick labels.
AxisTickMark | Specifies the possible positions for tick marks.
AxisTimeUnit | Specifies the unit of time for axes.
ChartAxisType | Specifies type of chart axis.
ChartType | Specifies type of a chart.
LegendPosition | Specifies the possible positions for a chart legend.
MarkerSymbol | Specifies marker symbol style.


AxisBound Class

Represents minimum or maximum bound of axis values.

For a list of all members of this type, see AxisBound Members.

System.Object
Aspose.Words.Drawing.Charts.AxisBound

[Visual Basic]
NotInheritable Public Class AxisBound
[C#]
public sealed class AxisBound

Remarks

Bound can be specified as a numeric, datetime or a special "auto" value.

The instances of this class are immutable.

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

AxisBound Members | Aspose.Words.Drawing.Charts Namespace | Minimum | Maximum


AxisBound Members

AxisBound overview

Public Instance Constructors

AxisBound Overloaded. Initializes a new instance of the AxisBound class.

Public Instance Properties

IsAuto | Returns a flag indicating that axis bound should be determined automatically.
Value | Returns numeric value of axis bound.
ValueAsDate | Returns value of axis bound represented as datetime.

Public Instance Methods

Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.
ToString | Returns a user-friendly string that displays the value of this object.

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace | Minimum | Maximum


AxisBound Constructor

Creates a new instance indicating that axis bound should be determined automatically by a word-processing application.

Overload List

Creates a new instance indicating that axis bound should be determined automatically by a word-processing application.

public AxisBound();

Creates an axis bound represented as datetime value.

public AxisBound(DateTime);

Creates an axis bound represented as a number.

public AxisBound(double);

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


AxisBound Constructor ()

Creates a new instance indicating that axis bound should be determined automatically by a word-processing application.

[Visual Basic]
Overloads Public Sub New()
[C#]
public AxisBound();

Example

Shows how to set custom axis bounds.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, remove default data and populate it with data from a ChartSeries
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();
chart.Series.Add("Series 1", new[] { 1.1, 5.4, 7.9, 3.5, 2.1, 9.7 }, new[] { 2.1, 0.3, 0.6, 3.3, 1.4, 1.9 });

// By default, the axis bounds are automatically defined so all the series data within the table is included
Assert.True(chart.AxisX.Scaling.Minimum.IsAuto);

// If we wish to set our own scale bounds, we need to replace them with new ones
// Both the axis rulers will go from 0 to 10
chart.AxisX.Scaling.Minimum = new AxisBound(0);
chart.AxisX.Scaling.Maximum = new AxisBound(10);
chart.AxisY.Scaling.Minimum = new AxisBound(0);
chart.AxisY.Scaling.Maximum = new AxisBound(10);

// These are custom and not defined automatically
Assert.False(chart.AxisX.Scaling.Minimum.IsAuto);
Assert.False(chart.AxisY.Scaling.Minimum.IsAuto);

// Create a line graph
chartShape = builder.InsertChart(ChartType.Line, 450, 300);
chart = chartShape.Chart;
chart.Series.Clear();

// Create a collection of dates, which will make up the X axis
DateTime[] dates = { new DateTime(1973, 5, 11),
    new DateTime(1981, 2, 4),
    new DateTime(1985, 9, 23),
    new DateTime(1989, 6, 28),
    new DateTime(1994, 12, 15)
};

// Assign a Y-value for each date
chart.Series.Add("Series 1", dates, new[] { 3.0, 4.7, 5.9, 7.1, 8.9 });

// These particular bounds will cut off categories from before 1980 and from 1990 and onwards
// This narrows the amount of categories and values in the viewport from 5 to 3
// Note that the graph still contains the out-of-range data because we can see the line tend towards it
chart.AxisX.Scaling.Minimum = new AxisBound(new DateTime(1980, 1, 1));
chart.AxisX.Scaling.Maximum = new AxisBound(new DateTime(1990, 1, 1));

doc.Save(ArtifactsDir + "Charts.AxisBound.docx");

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace | AxisBound Constructor Overload List


AxisBound Constructor (Double)

Creates an axis bound represented as a number.

[Visual Basic]
Overloads Public Sub New( _
ByVal value As Double _
)
[C#]
public AxisBound(
double value
);

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace | AxisBound Constructor Overload List


AxisBound Constructor (DateTime)

Creates an axis bound represented as datetime value.

[Visual Basic]
Overloads Public Sub New( _
ByVal datetime As Date _
)
[C#]
public AxisBound(
DateTime datetime
);

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace | AxisBound Constructor Overload List


AxisBound Properties

The properties of the AxisBound class are listed below. For a complete list of AxisBound class members, see the AxisBound Members topic.

Public Instance Properties

IsAuto | Returns a flag indicating that axis bound should be determined automatically.
Value | Returns numeric value of axis bound.
ValueAsDate | Returns value of axis bound represented as datetime.

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace | Minimum | Maximum


IsAuto Property

Aspose.Words

AxisBound.IsAuto Property

Returns a flag indicating that axis bound should be determined automatically.

[Visual Basic]
Public ReadOnly Property IsAuto As Boolean
[C#]
public bool IsAuto {get;}

Example

Shows how to set custom axis bounds.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, remove default data and populate it with data from a ChartSeries
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();
chart.Series.Add("Series 1", new[] { 1.1, 5.4, 7.9, 3.5, 2.1, 9.7 }, new[] { 2.1, 0.3, 0.6, 3.3, 1.4, 1.9 });

// By default, the axis bounds are automatically defined so all the series data within the table is included
Assert.True(chart.AxisX.Scaling.Minimum.IsAuto);

// If we wish to set our own scale bounds, we need to replace them with new ones
// Both the axis rulers will go from 0 to 10
chart.AxisX.Scaling.Minimum = new AxisBound(0);
chart.AxisX.Scaling.Maximum = new AxisBound(10);
chart.AxisY.Scaling.Minimum = new AxisBound(0);
chart.AxisY.Scaling.Maximum = new AxisBound(10);

// These are custom and not defined automatically
Assert.False(chart.AxisX.Scaling.Minimum.IsAuto);
Assert.False(chart.AxisY.Scaling.Minimum.IsAuto);

// Create a line graph
chartShape = builder.InsertChart(ChartType.Line, 450, 300);
chart = chartShape.Chart;
chart.Series.Clear();

// Create a collection of dates, which will make up the X axis
DateTime[] dates = { new DateTime(1973, 5, 11),
    new DateTime(1981, 2, 4),
    new DateTime(1985, 9, 23),
    new DateTime(1989, 6, 28),
    new DateTime(1994, 12, 15)
};

// Assign a Y-value for each date
chart.Series.Add("Series 1", dates, new[] { 3.0, 4.7, 5.9, 7.1, 8.9 });

// These particular bounds will cut off categories from before 1980 and from 1990 and onwards
// This narrows the amount of categories and values in the viewport from 5 to 3
// Note that the graph still contains the out-of-range data because we can see the line tend towards it
chart.AxisX.Scaling.Minimum = new AxisBound(new DateTime(1980, 1, 1));
chart.AxisX.Scaling.Maximum = new AxisBound(new DateTime(1990, 1, 1));

doc.Save(ArtifactsDir + "Charts.AxisBound.docx");

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


Value Property

Aspose.Words

AxisBound.Value Property

Returns numeric value of axis bound.

[Visual Basic]
Public ReadOnly Property Value As Double
[C#]
public double Value {get;}

Example

Shows how to set custom axis bounds.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, remove default data and populate it with data from a ChartSeries
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();
chart.Series.Add("Series 1", new[] { 1.1, 5.4, 7.9, 3.5, 2.1, 9.7 }, new[] { 2.1, 0.3, 0.6, 3.3, 1.4, 1.9 });

// By default, the axis bounds are automatically defined so all the series data within the table is included
Assert.True(chart.AxisX.Scaling.Minimum.IsAuto);

// If we wish to set our own scale bounds, we need to replace them with new ones
// Both the axis rulers will go from 0 to 10
chart.AxisX.Scaling.Minimum = new AxisBound(0);
chart.AxisX.Scaling.Maximum = new AxisBound(10);
chart.AxisY.Scaling.Minimum = new AxisBound(0);
chart.AxisY.Scaling.Maximum = new AxisBound(10);

// These are custom and not defined automatically
Assert.False(chart.AxisX.Scaling.Minimum.IsAuto);
Assert.False(chart.AxisY.Scaling.Minimum.IsAuto);

// Create a line graph
chartShape = builder.InsertChart(ChartType.Line, 450, 300);
chart = chartShape.Chart;
chart.Series.Clear();

// Create a collection of dates, which will make up the X axis
DateTime[] dates = { new DateTime(1973, 5, 11),
    new DateTime(1981, 2, 4),
    new DateTime(1985, 9, 23),
    new DateTime(1989, 6, 28),
    new DateTime(1994, 12, 15)
};

// Assign a Y-value for each date
chart.Series.Add("Series 1", dates, new[] { 3.0, 4.7, 5.9, 7.1, 8.9 });

// These particular bounds will cut off categories from before 1980 and from 1990 and onwards
// This narrows the amount of categories and values in the viewport from 5 to 3
// Note that the graph still contains the out-of-range data because we can see the line tend towards it
chart.AxisX.Scaling.Minimum = new AxisBound(new DateTime(1980, 1, 1));
chart.AxisX.Scaling.Maximum = new AxisBound(new DateTime(1990, 1, 1));

doc.Save(ArtifactsDir + "Charts.AxisBound.docx");

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


ValueAsDate Property

Aspose.Words

AxisBound.ValueAsDate Property

Returns value of axis bound represented as datetime.

[Visual Basic]
Public ReadOnly Property ValueAsDate As Date
[C#]
public DateTime ValueAsDate {get;}

Example

Shows how to set custom axis bounds.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, remove default data and populate it with data from a ChartSeries
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();
chart.Series.Add("Series 1", new[] { 1.1, 5.4, 7.9, 3.5, 2.1, 9.7 }, new[] { 2.1, 0.3, 0.6, 3.3, 1.4, 1.9 });

// By default, the axis bounds are automatically defined so all the series data within the table is included
Assert.True(chart.AxisX.Scaling.Minimum.IsAuto);

// If we wish to set our own scale bounds, we need to replace them with new ones
// Both the axis rulers will go from 0 to 10
chart.AxisX.Scaling.Minimum = new AxisBound(0);
chart.AxisX.Scaling.Maximum = new AxisBound(10);
chart.AxisY.Scaling.Minimum = new AxisBound(0);
chart.AxisY.Scaling.Maximum = new AxisBound(10);

// These are custom and not defined automatically
Assert.False(chart.AxisX.Scaling.Minimum.IsAuto);
Assert.False(chart.AxisY.Scaling.Minimum.IsAuto);

// Create a line graph
chartShape = builder.InsertChart(ChartType.Line, 450, 300);
chart = chartShape.Chart;
chart.Series.Clear();

// Create a collection of dates, which will make up the X axis
DateTime[] dates = { new DateTime(1973, 5, 11),
    new DateTime(1981, 2, 4),
    new DateTime(1985, 9, 23),
    new DateTime(1989, 6, 28),
    new DateTime(1994, 12, 15)
};

// Assign a Y-value for each date
chart.Series.Add("Series 1", dates, new[] { 3.0, 4.7, 5.9, 7.1, 8.9 });

// These particular bounds will cut off categories from before 1980 and from 1990 and onwards
// This narrows the amount of categories and values in the viewport from 5 to 3
// Note that the graph still contains the out-of-range data because we can see the line tend towards it
chart.AxisX.Scaling.Minimum = new AxisBound(new DateTime(1980, 1, 1));
chart.AxisX.Scaling.Maximum = new AxisBound(new DateTime(1990, 1, 1));

doc.Save(ArtifactsDir + "Charts.AxisBound.docx");

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


AxisBound Methods

The methods of the AxisBound class are listed below. For a complete list of AxisBound class members, see the AxisBound Members topic.

Public Instance Methods

Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.
ToString | Returns a user-friendly string that displays the value of this object.

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace | Minimum | Maximum


AxisBound.Equals Method

Determines whether the specified object is equal in value to the current object.

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


AxisBound.GetHashCode Method

Serves as a hash function for this type.

[Visual Basic]
Overrides Public Function GetHashCode() As Integer
[C#]
public override int GetHashCode();

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


AxisBound.ToString Method

Returns a user-friendly string that displays the value of this object.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();

See Also

AxisBound Class | Aspose.Words.Drawing.Charts Namespace


AxisBuiltInUnit Enumeration

Specifies the display units for an axis.

[Visual Basic]
Public Enum AxisBuiltInUnit
[C#]
public enum AxisBuiltInUnit

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

Members

Member Name | Description | Value
None | Specifies the values on the chart shall displayed as is. | 0
Custom | Specifies the values on the chart shall be divided by a user-defined divisor. This value is not supported by the new chart types of MS Office 2016. | 1
Billions | Specifies the values on the chart shall be divided by 1,000,000,000. | 2
HundredMillions | Specifies the values on the chart shall be divided by 100,000,000. | 3
Hundreds | Specifies the values on the chart shall be divided by 100. | 4
HundredThousands | Specifies the values on the chart shall be divided by 100,000. | 5
Millions | Specifies the values on the chart shall be divided by 1,000,000. | 6
TenMillions | Specifies the values on the chart shall be divided by 10,000,000. | 7
TenThousands | Specifies the values on the chart shall be divided by 10,000. | 8
Thousands | Specifies the values on the chart shall be divided by 1,000. | 9
Trillions | Specifies the values on the chart shall be divided by 1,000,000,000,0000. | 10
Percentage | Specifies the values on the chart shall be divided by 0.01. This value is supported only by the new chart types of MS Office 2016. | 11

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


AxisCategoryType Enumeration

Specifies type of a category axis.

[Visual Basic]
Public Enum AxisCategoryType
[C#]
public enum AxisCategoryType

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

Members

Member Name | Description | Value
Automatic | Specifies that type of a category axis is determined automatically based on data. | 0
Category | Specifies an axis of an arbitrary set of categories. | 1
Time | Specifies a time category axis. | 2

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


AxisCrosses Enumeration

Specifies the possible crossing points for an axis.

[Visual Basic]
Public Enum AxisCrosses
[C#]
public enum AxisCrosses

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

Members

Member Name | Description | Value
Automatic | The category axis crosses at the zero point of the value axis (if possible), or at the minimum value if the minimum is greater than zero, or at the maximum if the maximum is less than zero. | 0
Maximum | A perpendicular axis crosses at the maximum value of the axis. | 1
Minimum | A perpendicular axis crosses at the minimum value of the axis. | 2
Custom | A perpendicular axis crosses at the specified value of the axis. | 3

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


AxisDisplayUnit Class

Provides access to the scaling options of the display units for the value axis.

For a list of all members of this type, see AxisDisplayUnit Members.

System.Object
Aspose.Words.Drawing.Charts.AxisDisplayUnit

[Visual Basic]
Public Class AxisDisplayUnit
[C#]
public class AxisDisplayUnit

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

AxisDisplayUnit Members | Aspose.Words.Drawing.Charts Namespace


AxisDisplayUnit Members

AxisDisplayUnit overview

Public Instance Constructors

AxisDisplayUnit Constructor Initializes a new instance of the AxisDisplayUnit class.

Public Instance Properties

CustomUnit | Gets or sets a user-defined divisor to scale display units on the value axis.
Unit | Gets or sets the scaling value of the display units as one of the predefined values.

See Also

AxisDisplayUnit Class | Aspose.Words.Drawing.Charts Namespace


AxisDisplayUnit Constructor

Initializes a new instance of the AxisDisplayUnit class.

[Visual Basic]
Public Sub New()
[C#]
public AxisDisplayUnit();

See Also

AxisDisplayUnit Class | Aspose.Words.Drawing.Charts Namespace


AxisDisplayUnit Properties

The properties of the AxisDisplayUnit class are listed below. For a complete list of AxisDisplayUnit class members, see the AxisDisplayUnit Members topic.

Public Instance Properties

CustomUnit | Gets or sets a user-defined divisor to scale display units on the value axis.
Unit | Gets or sets the scaling value of the display units as one of the predefined values.

See Also

AxisDisplayUnit Class | Aspose.Words.Drawing.Charts Namespace


CustomUnit Property

Aspose.Words

AxisDisplayUnit.CustomUnit Property

Gets or sets a user-defined divisor to scale display units on the value axis.

[Visual Basic]
Public Property CustomUnit As Double
[C#]
public double CustomUnit {get; set;}

Remarks

The property is not supported by MS Office 2016 new charts. Default value is 1.

Setting this property sets the Unit property to Custom.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

AxisDisplayUnit Class | Aspose.Words.Drawing.Charts Namespace


Unit Property

Aspose.Words

AxisDisplayUnit.Unit Property

Gets or sets the scaling value of the display units as one of the predefined values.

[Visual Basic]
Public Property Unit As AxisBuiltInUnit
[C#]
public AxisBuiltInUnit Unit {get; set;}

Remarks

Default value is None. The Custom and Percentage values are not available in some chart types; see AxisBuiltInUnit for more information.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

AxisDisplayUnit Class | Aspose.Words.Drawing.Charts Namespace


AxisScaleType Enumeration

Specifies the possible scale types for an axis.

[Visual Basic]
Public Enum AxisScaleType
[C#]
public enum AxisScaleType

Example

Shows how to set up logarithmic axis scaling.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart and clear its default data series
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();

// Insert a series with X/Y coordinates for 5 points
chart.Series.Add("Series 1", new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }, new[] { 1.0, 20.0, 400.0, 8000.0, 160000.0 });

// The scaling of the X axis is linear by default, which means it will display "0, 1, 2, 3..."
Assert.AreEqual(AxisScaleType.Linear, chart.AxisX.Scaling.Type);

// Linear axis scaling is suitable for our X-values, but not our erratic Y-values
// We can set the scaling of the Y-axis to Logarithmic with a base of 20
// The Y-axis will now display "1, 20, 400, 8000...", which is ideal for accurate representation of this set of Y-values
chart.AxisY.Scaling.Type = AxisScaleType.Logarithmic;
chart.AxisY.Scaling.LogBase = 20.0;

doc.Save(ArtifactsDir + "Charts.AxisScaling.docx");

Members

Member Name | Description | Value
Linear | Linear scaling. | 0
Logarithmic | Logarithmic scaling. | 1

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


AxisScaling Class

Represents the scaling options of the axis.

For a list of all members of this type, see AxisScaling Members.

System.Object
Aspose.Words.Drawing.Charts.AxisScaling

[Visual Basic]
Public Class AxisScaling
[C#]
public class AxisScaling

Example

Shows how to set up logarithmic axis scaling.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart and clear its default data series
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();

// Insert a series with X/Y coordinates for 5 points
chart.Series.Add("Series 1", new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }, new[] { 1.0, 20.0, 400.0, 8000.0, 160000.0 });

// The scaling of the X axis is linear by default, which means it will display "0, 1, 2, 3..."
Assert.AreEqual(AxisScaleType.Linear, chart.AxisX.Scaling.Type);

// Linear axis scaling is suitable for our X-values, but not our erratic Y-values
// We can set the scaling of the Y-axis to Logarithmic with a base of 20
// The Y-axis will now display "1, 20, 400, 8000...", which is ideal for accurate representation of this set of Y-values
chart.AxisY.Scaling.Type = AxisScaleType.Logarithmic;
chart.AxisY.Scaling.LogBase = 20.0;

doc.Save(ArtifactsDir + "Charts.AxisScaling.docx");

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

AxisScaling Members | Aspose.Words.Drawing.Charts Namespace


AxisScaling Members

AxisScaling overview

Public Instance Constructors

AxisScaling Constructor Initializes a new instance of the AxisScaling class.

Public Instance Properties

LogBase | Gets or sets the logarithmic base for a logarithmic axis.
Maximum | Gets or sets the maximum value of the axis.
Minimum | Gets or sets minimum value of the axis.
Type | Gets or sets scaling type of the axis.

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


AxisScaling Constructor

Initializes a new instance of the AxisScaling class.

[Visual Basic]
Public Sub New()
[C#]
public AxisScaling();

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


AxisScaling Properties

The properties of the AxisScaling class are listed below. For a complete list of AxisScaling class members, see the AxisScaling Members topic.

Public Instance Properties

LogBase | Gets or sets the logarithmic base for a logarithmic axis.
Maximum | Gets or sets the maximum value of the axis.
Minimum | Gets or sets minimum value of the axis.
Type | Gets or sets scaling type of the axis.

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


LogBase Property

Aspose.Words

AxisScaling.LogBase Property

Gets or sets the logarithmic base for a logarithmic axis.

[Visual Basic]
Public Property LogBase As Double
[C#]
public double LogBase {get; set;}

Remarks

The property is not supported by MS Office 2016 new charts.

Valid range of a floating point value is greater than or equal to 2 and less than or equal to 1000. The property has effect only if Type is set to Logarithmic.

Setting this property sets the Type property to Logarithmic.

Example

Shows how to set up logarithmic axis scaling.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart and clear its default data series
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();

// Insert a series with X/Y coordinates for 5 points
chart.Series.Add("Series 1", new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }, new[] { 1.0, 20.0, 400.0, 8000.0, 160000.0 });

// The scaling of the X axis is linear by default, which means it will display "0, 1, 2, 3..."
Assert.AreEqual(AxisScaleType.Linear, chart.AxisX.Scaling.Type);

// Linear axis scaling is suitable for our X-values, but not our erratic Y-values
// We can set the scaling of the Y-axis to Logarithmic with a base of 20
// The Y-axis will now display "1, 20, 400, 8000...", which is ideal for accurate representation of this set of Y-values
chart.AxisY.Scaling.Type = AxisScaleType.Logarithmic;
chart.AxisY.Scaling.LogBase = 20.0;

doc.Save(ArtifactsDir + "Charts.AxisScaling.docx");

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


Maximum Property

Aspose.Words

AxisScaling.Maximum Property

Gets or sets the maximum value of the axis.

[Visual Basic]
Public Property Maximum As AxisBound
[C#]
public AxisBound Maximum {get; set;}

Remarks

The default value is "auto".

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


Minimum Property

Aspose.Words

AxisScaling.Minimum Property

Gets or sets minimum value of the axis.

[Visual Basic]
Public Property Minimum As AxisBound
[C#]
public AxisBound Minimum {get; set;}

Remarks

The default value is "auto".

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


Type Property

Aspose.Words

AxisScaling.Type Property

Gets or sets scaling type of the axis.

[Visual Basic]
Public Property Type As AxisScaleType
[C#]
public AxisScaleType Type {get; set;}

Remarks

The Linear value is the only that is allowed in MS Office 2016 new charts.

Example

Shows how to set up logarithmic axis scaling.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart and clear its default data series
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();

// Insert a series with X/Y coordinates for 5 points
chart.Series.Add("Series 1", new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }, new[] { 1.0, 20.0, 400.0, 8000.0, 160000.0 });

// The scaling of the X axis is linear by default, which means it will display "0, 1, 2, 3..."
Assert.AreEqual(AxisScaleType.Linear, chart.AxisX.Scaling.Type);

// Linear axis scaling is suitable for our X-values, but not our erratic Y-values
// We can set the scaling of the Y-axis to Logarithmic with a base of 20
// The Y-axis will now display "1, 20, 400, 8000...", which is ideal for accurate representation of this set of Y-values
chart.AxisY.Scaling.Type = AxisScaleType.Logarithmic;
chart.AxisY.Scaling.LogBase = 20.0;

doc.Save(ArtifactsDir + "Charts.AxisScaling.docx");

See Also

AxisScaling Class | Aspose.Words.Drawing.Charts Namespace


AxisTickLabelPosition Enumeration

Specifies the possible positions for tick labels.

[Visual Basic]
Public Enum AxisTickLabelPosition
[C#]
public enum AxisTickLabelPosition

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

Members

Member Name | Description | Value
High | Specifies the axis labels shall be at the high end of the perpendicular axis. | 0
Low | Specifies the axis labels shall be at the low end of the perpendicular axis. | 1
NextToAxis | Specifies the axis labels shall be next to the axis. | 2
None | Specifies the axis labels are not drawn. | 3
Default | Specifies default value of tick labels position. | 2

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


AxisTickMark Enumeration

Specifies the possible positions for tick marks.

[Visual Basic]
Public Enum AxisTickMark
[C#]
public enum AxisTickMark

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

Members

Member Name | Description | Value
Cross | Specifies that the tick marks shall cross the axis. | 0
Inside | Specifies that the tick marks shall be inside the plot area. | 1
Outside | Specifies that the tick marks shall be outside the plot area. | 2
None | Specifies that there shall be no tick marks. | 3

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


AxisTimeUnit Enumeration

Specifies the unit of time for axes.

[Visual Basic]
Public Enum AxisTimeUnit
[C#]
public enum AxisTimeUnit

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

Members

Member Name | Description | Value
Automatic | Specifies that unit was not set explicitly and default value should be used. | 0
Days | Specifies that the chart data shall be shown in days. | 1
Months | Specifies that the chart data shall be shown in months. | 2
Years | Specifies that the chart data shall be shown in years. | 3

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


Chart Class

Provides access to the chart shape properties.

For a list of all members of this type, see Chart Members.

System.Object
Aspose.Words.Drawing.Charts.Chart

[Visual Basic]
Public Class Chart
[C#]
public class Chart

Example

Shows how to insert a chart and change its title.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);

Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);

// Get the chart object from the containing shape
Chart chart = chartShape.Chart;

// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;

doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Chart Members | Aspose.Words.Drawing.Charts Namespace


Chart Members

Chart overview

Public Instance Properties

AxisX | Provides access to properties of the X axis of the chart.
AxisY | Provides access to properties of the Y axis of the chart.
AxisZ | Provides access to properties of the Z axis of the chart.
Legend | Provides access to the chart legend properties.
Series | Provides access to series collection.
Title | Provides access to the chart title properties.

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


Chart Properties

The properties of the Chart class are listed below. For a complete list of Chart class members, see the Chart Members topic.

Public Instance Properties

AxisX | Provides access to properties of the X axis of the chart.
AxisY | Provides access to properties of the Y axis of the chart.
AxisZ | Provides access to properties of the Z axis of the chart.
Legend | Provides access to the chart legend properties.
Series | Provides access to series collection.
Title | Provides access to the chart title properties.

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


AxisX Property

Aspose.Words

Chart.AxisX Property

Provides access to properties of the X axis of the chart.

[Visual Basic]
Public ReadOnly Property AxisX As ChartAxis
[C#]
public ChartAxis AxisX {get;}

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


AxisY Property

Aspose.Words

Chart.AxisY Property

Provides access to properties of the Y axis of the chart.

[Visual Basic]
Public ReadOnly Property AxisY As ChartAxis
[C#]
public ChartAxis AxisY {get;}

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


AxisZ Property

Aspose.Words

Chart.AxisZ Property

Provides access to properties of the Z axis of the chart.

[Visual Basic]
Public ReadOnly Property AxisZ As ChartAxis
[C#]
public ChartAxis AxisZ {get;}

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


Legend Property

Aspose.Words

Chart.Legend Property

Provides access to the chart legend properties.

[Visual Basic]
Public ReadOnly Property Legend As ChartLegend
[C#]
public ChartLegend Legend {get;}

Example

Shows how to edit the appearance of a chart's legend.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a line graph
Shape chartShape = builder.InsertChart(ChartType.Line, 450, 300);
Chart chart = chartShape.Chart;

// Get its legend
ChartLegend legend = chart.Legend;

// By default, other elements of a chart will not overlap with its legend
Assert.False(legend.Overlay);

// We can move its position by setting this attribute
legend.Position = LegendPosition.TopRight;

doc.Save(ArtifactsDir + "Charts.ChartLegend.docx");

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


Series Property

Aspose.Words

Chart.Series Property

Provides access to series collection.

[Visual Basic]
Public ReadOnly Property Series As ChartSeriesCollection
[C#]
public ChartSeriesCollection Series {get;}

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


Title Property

Aspose.Words

Chart.Title Property

Provides access to the chart title properties.

[Visual Basic]
Public ReadOnly Property Title As ChartTitle
[C#]
public ChartTitle Title {get;}

Example

Shows how to insert a chart and change its title.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);

Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);

// Get the chart object from the containing shape
Chart chart = chartShape.Chart;

// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;

doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");

See Also

Chart Class | Aspose.Words.Drawing.Charts Namespace


ChartAxis Class

Represents the axis options of the chart.

For a list of all members of this type, see ChartAxis Members.

System.Object
Aspose.Words.Drawing.Charts.ChartAxis

[Visual Basic]
Public Class ChartAxis
[C#]
public class ChartAxis

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartAxis Members | Aspose.Words.Drawing.Charts Namespace


ChartAxis Members

ChartAxis overview

Public Instance Properties

AxisBetweenCategories | Gets or sets a flag indicating whether the value axis crosses the category axis between categories.
BaseTimeUnit | Returns or sets the smallest time unit that is represented on the time category axis.
CategoryType | Gets or sets type of the category axis.
Crosses | Specifies how this axis crosses the perpendicular axis.
CrossesAt | Specifies where on the perpendicular axis the axis crosses.
DisplayUnit | Specifies the scaling value of the display units for the value axis.
Hidden | Gets or sets a flag indicating whether this axis is hidden or not.
MajorTickMark | Returns or sets the major tick marks.
MajorUnit | Returns or sets the distance between major tick marks.
MajorUnitIsAuto | Gets or sets a flag indicating whether default distance between major tick marks shall be used.
MajorUnitScale | Returns or sets the scale value for major tick marks on the time category axis.
MinorTickMark | Returns or sets the minor tick marks for the axis.
MinorUnit | Returns or sets the distance between minor tick marks.
MinorUnitIsAuto | Gets or sets a flag indicating whether default distance between minor tick marks shall be used.
MinorUnitScale | Returns or sets the scale value for minor tick marks on the time category axis.
NumberFormat | Returns a ChartNumberFormat object that allows defining number formats for the axis.
ReverseOrder | Returns or sets a flag indicating whether values of axis should be displayed in reverse order, i.e. from max to min.
Scaling | Provides access to the scaling options of the axis.
TickLabelAlignment | Gets or sets text alignment of axis tick labels.
TickLabelOffset | Gets or sets the distance of labels from the axis.
TickLabelPosition | Returns or sets the position of the tick labels on the axis.
TickLabelSpacing | Gets or sets the interval, at which tick labels are drawn.
TickLabelSpacingIsAuto | Gets or sets a flag indicating whether automatic interval of drawing tick labels shall be used.
TickMarkSpacing | Gets or sets the interval, at which tick marks are drawn.
Type | Returns type of the axis.

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


ChartAxis Properties

The properties of the ChartAxis class are listed below. For a complete list of ChartAxis class members, see the ChartAxis Members topic.

Public Instance Properties

AxisBetweenCategories | Gets or sets a flag indicating whether the value axis crosses the category axis between categories.
BaseTimeUnit | Returns or sets the smallest time unit that is represented on the time category axis.
CategoryType | Gets or sets type of the category axis.
Crosses | Specifies how this axis crosses the perpendicular axis.
CrossesAt | Specifies where on the perpendicular axis the axis crosses.
DisplayUnit | Specifies the scaling value of the display units for the value axis.
Hidden | Gets or sets a flag indicating whether this axis is hidden or not.
MajorTickMark | Returns or sets the major tick marks.
MajorUnit | Returns or sets the distance between major tick marks.
MajorUnitIsAuto | Gets or sets a flag indicating whether default distance between major tick marks shall be used.
MajorUnitScale | Returns or sets the scale value for major tick marks on the time category axis.
MinorTickMark | Returns or sets the minor tick marks for the axis.
MinorUnit | Returns or sets the distance between minor tick marks.
MinorUnitIsAuto | Gets or sets a flag indicating whether default distance between minor tick marks shall be used.
MinorUnitScale | Returns or sets the scale value for minor tick marks on the time category axis.
NumberFormat | Returns a ChartNumberFormat object that allows defining number formats for the axis.
ReverseOrder | Returns or sets a flag indicating whether values of axis should be displayed in reverse order, i.e. from max to min.
Scaling | Provides access to the scaling options of the axis.
TickLabelAlignment | Gets or sets text alignment of axis tick labels.
TickLabelOffset | Gets or sets the distance of labels from the axis.
TickLabelPosition | Returns or sets the position of the tick labels on the axis.
TickLabelSpacing | Gets or sets the interval, at which tick labels are drawn.
TickLabelSpacingIsAuto | Gets or sets a flag indicating whether automatic interval of drawing tick labels shall be used.
TickMarkSpacing | Gets or sets the interval, at which tick marks are drawn.
Type | Returns type of the axis.

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


AxisBetweenCategories Property

Aspose.Words

ChartAxis.AxisBetweenCategories Property

Gets or sets a flag indicating whether the value axis crosses the category axis between categories.

[Visual Basic]
Public Property AxisBetweenCategories As Boolean
[C#]
public bool AxisBetweenCategories {get; set;}

Remarks

The property has effect only for value axes. It is not supported by MS Office 2016 new charts.

Example

Shows how to get a graph axis to cross at a custom location.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a column chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Column, 450, 250);
Chart chart = shape.Chart;

// Get the Y-axis to cross at a value of 3.0, making 3.0 the new Y-zero of our column chart
// This effectively means that all the columns with Y-values about 3.0 will be above the Y-centre and point up,
// while ones below 3.0 will point down
ChartAxis axis = chart.AxisX;
axis.AxisBetweenCategories = true;
axis.Crosses = AxisCrosses.Custom;
axis.CrossesAt = 3.0;

doc.Save(ArtifactsDir + "Charts.AxisCross.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


BaseTimeUnit Property

Aspose.Words

ChartAxis.BaseTimeUnit Property

Returns or sets the smallest time unit that is represented on the time category axis.

[Visual Basic]
Public Property BaseTimeUnit As AxisTimeUnit
[C#]
public AxisTimeUnit BaseTimeUnit {get; set;}

Remarks

The property has effect only for time category axes.

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


CategoryType Property

Aspose.Words

ChartAxis.CategoryType Property

Gets or sets type of the category axis.

[Visual Basic]
Public Property CategoryType As AxisCategoryType
[C#]
public AxisCategoryType CategoryType {get; set;}

Remarks

Only text categories (Category) are allowed in MS Office 2016 new charts.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


Crosses Property

Aspose.Words

ChartAxis.Crosses Property

Specifies how this axis crosses the perpendicular axis.

[Visual Basic]
Public Property Crosses As AxisCrosses
[C#]
public AxisCrosses Crosses {get; set;}

Remarks

Default value is Automatic.

The property is not supported by MS Office 2016 new charts.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


CrossesAt Property

Aspose.Words

ChartAxis.CrossesAt Property

Specifies where on the perpendicular axis the axis crosses.

[Visual Basic]
Public Property CrossesAt As Double
[C#]
public double CrossesAt {get; set;}

Remarks

The property has effect only if Crosses are set to Custom. It is not supported by MS Office 2016 new charts.

The units are determined by the type of axis. When the axis is a value axis, the value of the property is a decimal number on the value axis. When the axis is a time category axis, the value is defined as an integer number of days relative to the base date (30/12/1899). For a text category axis, the value is an integer category number, starting with 1 as the first category.

Example

Shows how to get a graph axis to cross at a custom location.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a column chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Column, 450, 250);
Chart chart = shape.Chart;

// Get the Y-axis to cross at a value of 3.0, making 3.0 the new Y-zero of our column chart
// This effectively means that all the columns with Y-values about 3.0 will be above the Y-centre and point up,
// while ones below 3.0 will point down
ChartAxis axis = chart.AxisX;
axis.AxisBetweenCategories = true;
axis.Crosses = AxisCrosses.Custom;
axis.CrossesAt = 3.0;

doc.Save(ArtifactsDir + "Charts.AxisCross.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


DisplayUnit Property

Aspose.Words

ChartAxis.DisplayUnit Property

Specifies the scaling value of the display units for the value axis.

[Visual Basic]
Public ReadOnly Property DisplayUnit As AxisDisplayUnit
[C#]
public AxisDisplayUnit DisplayUnit {get;}

Remarks

The property has effect only for value axes.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


Hidden Property

Aspose.Words

ChartAxis.Hidden Property

Gets or sets a flag indicating whether this axis is hidden or not.

[Visual Basic]
Public Property Hidden As Boolean
[C#]
public bool Hidden {get; set;}

Remarks

Default value is false.

Example

Shows how to hide chart axises.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
chart.AxisX.Hidden = true;
chart.AxisY.Hidden = true;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("AW Series 1",
    new string[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
    new double[] { 1.2, 0.3, 2.1, 2.9, 4.2 });

MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Docx);

shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
chart = shape.Chart;

Assert.AreEqual(true, chart.AxisX.Hidden);
Assert.AreEqual(true, chart.AxisY.Hidden);

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MajorTickMark Property

Aspose.Words

ChartAxis.MajorTickMark Property

Returns or sets the major tick marks.

[Visual Basic]
Public Property MajorTickMark As AxisTickMark
[C#]
public AxisTickMark MajorTickMark {get; set;}

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MajorUnit Property

Aspose.Words

ChartAxis.MajorUnit Property

Returns or sets the distance between major tick marks.

[Visual Basic]
Public Property MajorUnit As Double
[C#]
public double MajorUnit {get; set;}

Remarks

Valid range of a value is greater than zero. The property has effect for time category and value axes.

Setting this property sets the MajorUnitIsAuto property to false.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MajorUnitIsAuto Property

Aspose.Words

ChartAxis.MajorUnitIsAuto Property

Gets or sets a flag indicating whether default distance between major tick marks shall be used.

[Visual Basic]
Public Property MajorUnitIsAuto As Boolean
[C#]
public bool MajorUnitIsAuto {get; set;}

Remarks

The property has effect for time category and value axes.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MajorUnitScale Property

Aspose.Words

ChartAxis.MajorUnitScale Property

Returns or sets the scale value for major tick marks on the time category axis.

[Visual Basic]
Public Property MajorUnitScale As AxisTimeUnit
[C#]
public AxisTimeUnit MajorUnitScale {get; set;}

Remarks

The property has effect only for time category axes.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MinorTickMark Property

Aspose.Words

ChartAxis.MinorTickMark Property

Returns or sets the minor tick marks for the axis.

[Visual Basic]
Public Property MinorTickMark As AxisTickMark
[C#]
public AxisTickMark MinorTickMark {get; set;}

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MinorUnit Property

Aspose.Words

ChartAxis.MinorUnit Property

Returns or sets the distance between minor tick marks.

[Visual Basic]
Public Property MinorUnit As Double
[C#]
public double MinorUnit {get; set;}

Remarks

Valid range of a value is greater than zero. The property has effect for time category and value axes.

Setting this property sets the MinorUnitIsAuto property to false.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MinorUnitIsAuto Property

Aspose.Words

ChartAxis.MinorUnitIsAuto Property

Gets or sets a flag indicating whether default distance between minor tick marks shall be used.

[Visual Basic]
Public Property MinorUnitIsAuto As Boolean
[C#]
public bool MinorUnitIsAuto {get; set;}

Remarks

The property has effect for time category and value axes.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


MinorUnitScale Property

Aspose.Words

ChartAxis.MinorUnitScale Property

Returns or sets the scale value for minor tick marks on the time category axis.

[Visual Basic]
Public Property MinorUnitScale As AxisTimeUnit
[C#]
public AxisTimeUnit MinorUnitScale {get; set;}

Remarks

The property has effect only for time category axes.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


NumberFormat Property

Aspose.Words

ChartAxis.NumberFormat Property

Returns a ChartNumberFormat object that allows defining number formats for the axis.

[Visual Basic]
Public ReadOnly Property NumberFormat As ChartNumberFormat
[C#]
public ChartNumberFormat NumberFormat {get;}

Example

Shows how to set formatting for chart values.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 1900000, 850000, 2100000, 600000, 1500000 });

// Set number format.
chart.AxisY.NumberFormat.FormatCode = "#,##0";

// Set this to override the above value and draw the number format from the source cell
Assert.False(chart.AxisY.NumberFormat.IsLinkedToSource);

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


ReverseOrder Property

Aspose.Words

ChartAxis.ReverseOrder Property

Returns or sets a flag indicating whether values of axis should be displayed in reverse order, i.e. from max to min.

[Visual Basic]
Public Property ReverseOrder As Boolean
[C#]
public bool ReverseOrder {get; set;}

Remarks

The property is not supported by MS Office 2016 new charts. Default value is false.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


Scaling Property

Aspose.Words

ChartAxis.Scaling Property

Provides access to the scaling options of the axis.

[Visual Basic]
Public ReadOnly Property Scaling As AxisScaling
[C#]
public AxisScaling Scaling {get;}

Example

Shows how to insert chart with date/time values

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

// Fill data.
chart.Series.Add("Aspose Test Series",
    new[]
    {
        new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
        new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
    },
    new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });

ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));

// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;

// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);

doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


TickLabelAlignment Property

Aspose.Words

ChartAxis.TickLabelAlignment Property

Gets or sets text alignment of axis tick labels.

[Visual Basic]
Public Property TickLabelAlignment As ParagraphAlignment
[C#]
public ParagraphAlignment TickLabelAlignment {get; set;}

Remarks

This property has effect only for multi-line labels.

Default value is Center.

.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


TickLabelOffset Property

Aspose.Words

ChartAxis.TickLabelOffset Property

Gets or sets the distance of labels from the axis.

[Visual Basic]
Public Property TickLabelOffset As Integer
[C#]
public int TickLabelOffset {get; set;}

Remarks

The property represents a percentage of the default label offset.

Valid range is from 0 to 1000 percent inclusive. Default value is 100%.

The property has effect only for category axes. It is not supported by MS Office 2016 new charts.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


TickLabelPosition Property

Aspose.Words

ChartAxis.TickLabelPosition Property

Returns or sets the position of the tick labels on the axis.

[Visual Basic]
Public Property TickLabelPosition As AxisTickLabelPosition
[C#]
public AxisTickLabelPosition TickLabelPosition {get; set;}

Remarks

The property is not supported by MS Office 2016 new charts.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


TickLabelSpacing Property

Aspose.Words

ChartAxis.TickLabelSpacing Property

Gets or sets the interval, at which tick labels are drawn.

[Visual Basic]
Public Property TickLabelSpacing As Integer
[C#]
public int TickLabelSpacing {get; set;}

Remarks

The property has effect for text category and series axes. It is not supported by MS Office 2016 new charts. Valid range of a value is greater than or equal to 1.

Setting this property sets the TickLabelSpacingIsAuto property to false.

Example

Shows how to manipulate the tick marks and displayed values of a chart axis.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;

// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;

axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;

// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);

// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);

// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;

// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;

// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;

doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


TickLabelSpacingIsAuto Property

Aspose.Words

ChartAxis.TickLabelSpacingIsAuto Property

Gets or sets a flag indicating whether automatic interval of drawing tick labels shall be used.

[Visual Basic]
Public Property TickLabelSpacingIsAuto As Boolean
[C#]
public bool TickLabelSpacingIsAuto {get; set;}

Remarks

Default value is true.

The property has effect for text category and series axes. It is not supported by MS Office 2016 new charts.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


TickMarkSpacing Property

Aspose.Words

ChartAxis.TickMarkSpacing Property

Gets or sets the interval, at which tick marks are drawn.

[Visual Basic]
Public Property TickMarkSpacing As Integer
[C#]
public int TickMarkSpacing {get; set;}

Remarks

The property has effect for text category and series axes. It is not supported by MS Office 2016 new charts.

Valid range of a value is greater than or equal to 1.

Example

Shows how to insert chart using the axis options for detailed configuration.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 640, 320, 280, 120, 150 });

// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;

// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);

// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;

// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


Type Property

Aspose.Words

ChartAxis.Type Property

Returns type of the axis.

[Visual Basic]
Public ReadOnly Property Type As ChartAxisType
[C#]
public ChartAxisType Type {get;}

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

See Also

ChartAxis Class | Aspose.Words.Drawing.Charts Namespace


ChartAxisType Enumeration

Specifies type of chart axis.

[Visual Basic]
Public Enum ChartAxisType
[C#]
public enum ChartAxisType

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

Members

Member Name | Description | Value
Category | Category axis of a chart. | 0
Series | Series axis of a chart. | 1
Value | Value axis of a chart. | 2

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


ChartDataLabel Class

Represents data label on a chart point or trendline.

For a list of all members of this type, see ChartDataLabel Members.

System.Object
Aspose.Words.Drawing.Charts.ChartDataLabel

[Visual Basic]
Public Class ChartDataLabel
[C#]
public class ChartDataLabel

Remarks

On a series, the ChartDataLabel object is a member of the ChartDataLabelCollection. The ChartDataLabelCollection contains a ChartDataLabel object for each point.

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartDataLabel Members | Aspose.Words.Drawing.Charts Namespace


ChartDataLabel Members

ChartDataLabel overview

Public Instance Properties

Index | Specifies the index of the containing element. This index shall determine which of the parent's children collection this element applies to. Default value is 0.
IsVisible | Returns true if this data label has something to display.
NumberFormat | Returns number format of the parent element.
Separator | Gets or sets string separator used for the data labels on a chart. The default is a comma, except for pie charts showing only category name and percentage, when a line break shall be used instead.
ShowBubbleSize | Allows to specify if bubble size is to be displayed for the data labels on a chart. Applies only to Bubble charts. Default value is false.
ShowCategoryName | Allows to specify if category name is to be displayed for the data labels on a chart. Default value is false.
ShowDataLabelsRange | Allows to specify if values from data labels range to be displayed in the data labels. Default value is false.
ShowLeaderLines | Allows to specify if data label leader lines need be shown. Default value is false.
ShowLegendKey | Allows to specify if legend key is to be displayed for the data labels on a chart. Default value is false.
ShowPercentage | Allows to specify if percentage value is to be displayed for the data labels on a chart. Default value is false.
ShowSeriesName | Returns or sets a Boolean to indicate the series name display behavior for the data labels on a chart. True to show the series name. False to hide. By default false.
ShowValue | Allows to specify if values are to be displayed in the data labels. Default value is false.

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabel Properties

The properties of the ChartDataLabel class are listed below. For a complete list of ChartDataLabel class members, see the ChartDataLabel Members topic.

Public Instance Properties

Index | Specifies the index of the containing element. This index shall determine which of the parent's children collection this element applies to. Default value is 0.
IsVisible | Returns true if this data label has something to display.
NumberFormat | Returns number format of the parent element.
Separator | Gets or sets string separator used for the data labels on a chart. The default is a comma, except for pie charts showing only category name and percentage, when a line break shall be used instead.
ShowBubbleSize | Allows to specify if bubble size is to be displayed for the data labels on a chart. Applies only to Bubble charts. Default value is false.
ShowCategoryName | Allows to specify if category name is to be displayed for the data labels on a chart. Default value is false.
ShowDataLabelsRange | Allows to specify if values from data labels range to be displayed in the data labels. Default value is false.
ShowLeaderLines | Allows to specify if data label leader lines need be shown. Default value is false.
ShowLegendKey | Allows to specify if legend key is to be displayed for the data labels on a chart. Default value is false.
ShowPercentage | Allows to specify if percentage value is to be displayed for the data labels on a chart. Default value is false.
ShowSeriesName | Returns or sets a Boolean to indicate the series name display behavior for the data labels on a chart. True to show the series name. False to hide. By default false.
ShowValue | Allows to specify if values are to be displayed in the data labels. Default value is false.

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


Index Property

Aspose.Words

ChartDataLabel.Index Property

Specifies the index of the containing element. This index shall determine which of the parent's children collection this element applies to. Default value is 0.

[Visual Basic]
Public ReadOnly Property Index As Integer
[C#]
public int Index {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


IsVisible Property

Aspose.Words

ChartDataLabel.IsVisible Property

Returns true if this data label has something to display.

[Visual Basic]
Public ReadOnly Property IsVisible As Boolean
[C#]
public bool IsVisible {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


NumberFormat Property

Aspose.Words

ChartDataLabel.NumberFormat Property

Returns number format of the parent element.

[Visual Basic]
Public ReadOnly Property NumberFormat As ChartNumberFormat
[C#]
public ChartNumberFormat NumberFormat {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


Separator Property

Aspose.Words

ChartDataLabel.Separator Property

Gets or sets string separator used for the data labels on a chart. The default is a comma, except for pie charts showing only category name and percentage, when a line break shall be used instead.

[Visual Basic]
Public Property Separator As String
[C#]
public string Separator {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowBubbleSize Property

Aspose.Words

ChartDataLabel.ShowBubbleSize Property

Allows to specify if bubble size is to be displayed for the data labels on a chart. Applies only to Bubble charts. Default value is false.

[Visual Basic]
Public Property ShowBubbleSize As Boolean
[C#]
public bool ShowBubbleSize {get; set;}

Example

Demonstrates bubble chart-exclusive features.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a bubble chart with 3D effects on each bubble
Shape shape = builder.InsertChart(ChartType.Bubble3D, 500, 350);
Chart chart = shape.Chart;

Assert.True(chart.Series[0].Bubble3D);

// Apply a data label to each bubble that displays the size of its bubble
for (int i = 0; i < 3; i++)
{
    ChartDataLabel cdl = chart.Series[0].DataLabels.Add(i);
    cdl.ShowBubbleSize = true;
}

doc.Save(ArtifactsDir + "Charts.Bubble3D.docx");

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowCategoryName Property

Aspose.Words

ChartDataLabel.ShowCategoryName Property

Allows to specify if category name is to be displayed for the data labels on a chart. Default value is false.

[Visual Basic]
Public Property ShowCategoryName As Boolean
[C#]
public bool ShowCategoryName {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowDataLabelsRange Property

Aspose.Words

ChartDataLabel.ShowDataLabelsRange Property

Allows to specify if values from data labels range to be displayed in the data labels. Default value is false.

[Visual Basic]
Public Property ShowDataLabelsRange As Boolean
[C#]
public bool ShowDataLabelsRange {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowLeaderLines Property

Aspose.Words

ChartDataLabel.ShowLeaderLines Property

Allows to specify if data label leader lines need be shown. Default value is false.

[Visual Basic]
Public Property ShowLeaderLines As Boolean
[C#]
public bool ShowLeaderLines {get; set;}

Remarks

Applies to Pie charts only. Leader lines create a visual connection between a data label and its corresponding data point.

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowLegendKey Property

Aspose.Words

ChartDataLabel.ShowLegendKey Property

Allows to specify if legend key is to be displayed for the data labels on a chart. Default value is false.

[Visual Basic]
Public Property ShowLegendKey As Boolean
[C#]
public bool ShowLegendKey {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowPercentage Property

Aspose.Words

ChartDataLabel.ShowPercentage Property

Allows to specify if percentage value is to be displayed for the data labels on a chart. Default value is false.

[Visual Basic]
Public Property ShowPercentage As Boolean
[C#]
public bool ShowPercentage {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowSeriesName Property

Aspose.Words

ChartDataLabel.ShowSeriesName Property

Returns or sets a Boolean to indicate the series name display behavior for the data labels on a chart. True to show the series name. False to hide. By default false.

[Visual Basic]
Public Property ShowSeriesName As Boolean
[C#]
public bool ShowSeriesName {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ShowValue Property

Aspose.Words

ChartDataLabel.ShowValue Property

Allows to specify if values are to be displayed in the data labels. Default value is false.

[Visual Basic]
Public Property ShowValue As Boolean
[C#]
public bool ShowValue {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabel Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection Class

Represents a collection of ChartDataLabel.

For a list of all members of this type, see ChartDataLabelCollection Members.

System.Object
Aspose.Words.Drawing.Charts.ChartDataLabelCollection

[Visual Basic]
Public Class ChartDataLabelCollection
Implements IEnumerable`1([Aspose.Words.Drawing.Charts.ChartDataLabel, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class ChartDataLabelCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartDataLabelCollection Members | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection Members

ChartDataLabelCollection overview

Public Instance Properties

Count | Returns the number of ChartDataLabel in this collection.
Item | Returns ChartDataLabel for the specified index.

Public Instance Methods

Add | Adds new ChartDataLabel at the specified index.
Clear | Removes all ChartDataLabel from this collection.
GetEnumerator | Returns an enumerator object.
RemoveAt | Removes a ChartDataLabel at the specified index.

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection Properties

The properties of the ChartDataLabelCollection class are listed below. For a complete list of ChartDataLabelCollection class members, see the ChartDataLabelCollection Members topic.

Public Instance Properties

Count | Returns the number of ChartDataLabel in this collection.
Item | Returns ChartDataLabel for the specified index.

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


Count Property

Aspose.Words

ChartDataLabelCollection.Count Property

Returns the number of ChartDataLabel in this collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


Item Property

Aspose.Words

ChartDataLabelCollection.Item Property

Returns ChartDataLabel for the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As ChartDataLabel
[C#]
public ChartDataLabel this[
int index
] {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection Methods

The methods of the ChartDataLabelCollection class are listed below. For a complete list of ChartDataLabelCollection class members, see the ChartDataLabelCollection Members topic.

Public Instance Methods

Add | Adds new ChartDataLabel at the specified index.
Clear | Removes all ChartDataLabel from this collection.
GetEnumerator | Returns an enumerator object.
RemoveAt | Removes a ChartDataLabel at the specified index.

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection.Add Method

Adds new ChartDataLabel at the specified index.

[Visual Basic]
Public Function Add( _
ByVal index As Integer _
) As ChartDataLabel
[C#]
public ChartDataLabel Add(
int index
);

Parameters

index
Target data label index.

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection.Clear Method

Removes all ChartDataLabel from this collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of ChartDataLabel) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<ChartDataLabel> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataLabelCollection.RemoveAt Method

Removes a ChartDataLabel at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the chart data label to remove.

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartDataLabelCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPoint Class

Allows to specify formatting of a single data point on the chart.

For a list of all members of this type, see ChartDataPoint Members.

System.Object
Aspose.Words.Drawing.Charts.ChartDataPoint

[Visual Basic]
Public Class ChartDataPoint
Implements IChartDataPoint
[C#]
public class ChartDataPoint : IChartDataPoint

Remarks

On a series, the ChartDataPoint object is a member of the ChartDataPointCollection. The ChartDataPointCollection contains a ChartDataPoint object for each point.

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartDataPoint Members | Aspose.Words.Drawing.Charts Namespace


ChartDataPoint Members

ChartDataPoint overview

Public Instance Properties

Bubble3D |
Explosion |
Index | Index of the data point this object applies formatting to.
InvertIfNegative |
Marker |

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPoint Properties

The properties of the ChartDataPoint class are listed below. For a complete list of ChartDataPoint class members, see the ChartDataPoint Members topic.

Public Instance Properties

Bubble3D |
Explosion |
Index | Index of the data point this object applies formatting to.
InvertIfNegative |
Marker |

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


Bubble3D Property

Aspose.Words

ChartDataPoint.Bubble3D Property

[Visual Basic]
NotOverridable Public Property Bubble3D As Boolean _
Implements IChartDataPoint.Bubble3D
[C#]
public bool Bubble3D {get; set;}

Implements

IChartDataPoint.Bubble3D

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


Explosion Property

Aspose.Words

ChartDataPoint.Explosion Property

[Visual Basic]
NotOverridable Public Property Explosion As Integer _
Implements IChartDataPoint.Explosion
[C#]
public int Explosion {get; set;}

Implements

IChartDataPoint.Explosion

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


Index Property

Aspose.Words

ChartDataPoint.Index Property

Index of the data point this object applies formatting to.

[Visual Basic]
Public ReadOnly Property Index As Integer
[C#]
public int Index {get;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


InvertIfNegative Property

Aspose.Words

ChartDataPoint.InvertIfNegative Property

[Visual Basic]
NotOverridable Public Property InvertIfNegative As Boolean _
Implements IChartDataPoint.InvertIfNegative
[C#]
public bool InvertIfNegative {get; set;}

Implements

IChartDataPoint.InvertIfNegative

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


Marker Property

Aspose.Words

ChartDataPoint.Marker Property

[Visual Basic]
NotOverridable Public ReadOnly Property Marker As ChartMarker _
Implements IChartDataPoint.Marker
[C#]
public ChartMarker Marker {get;}

Implements

IChartDataPoint.Marker

See Also

ChartDataPoint Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection Class

Represents collection of a ChartDataPoint.

For a list of all members of this type, see ChartDataPointCollection Members.

System.Object
Aspose.Words.Drawing.Charts.ChartDataPointCollection

[Visual Basic]
Public Class ChartDataPointCollection
Implements IEnumerable`1([Aspose.Words.Drawing.Charts.ChartDataPoint, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class ChartDataPointCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartDataPointCollection Members | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection Members

ChartDataPointCollection overview

Public Instance Properties

Count | Returns the number of ChartDataPoint in this collection.
Item | Returns ChartDataPoint for the specified index. If there is no ChartDataPoint for the specified index, returns default series ChartDataPoint.

Public Instance Methods

Add | Adds new ChartDataPoint at the specified index.
Clear | Removes all ChartDataPoint from this collection.
GetEnumerator | Returns an enumerator object.
RemoveAt | Removes a ChartDataPoint at the specified index.

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection Properties

The properties of the ChartDataPointCollection class are listed below. For a complete list of ChartDataPointCollection class members, see the ChartDataPointCollection Members topic.

Public Instance Properties

Count | Returns the number of ChartDataPoint in this collection.
Item | Returns ChartDataPoint for the specified index. If there is no ChartDataPoint for the specified index, returns default series ChartDataPoint.

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


Count Property

Aspose.Words

ChartDataPointCollection.Count Property

Returns the number of ChartDataPoint in this collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


Item Property

Aspose.Words

ChartDataPointCollection.Item Property

Returns ChartDataPoint for the specified index. If there is no ChartDataPoint for the specified index, returns default series ChartDataPoint.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As ChartDataPoint
[C#]
public ChartDataPoint this[
int index
] {get;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection Methods

The methods of the ChartDataPointCollection class are listed below. For a complete list of ChartDataPointCollection class members, see the ChartDataPointCollection Members topic.

Public Instance Methods

Add | Adds new ChartDataPoint at the specified index.
Clear | Removes all ChartDataPoint from this collection.
GetEnumerator | Returns an enumerator object.
RemoveAt | Removes a ChartDataPoint at the specified index.

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection.Add Method

Adds new ChartDataPoint at the specified index.

[Visual Basic]
Public Function Add( _
ByVal index As Integer _
) As ChartDataPoint
[C#]
public ChartDataPoint Add(
int index
);

Parameters

index
Target data point index.

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection.Clear Method

Removes all ChartDataPoint from this collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of ChartDataPoint) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<ChartDataPoint> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartDataPointCollection.RemoveAt Method

Removes a ChartDataPoint at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the bookmark to remove.

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartDataPointCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartLegend Class

Represents chart legend properties.

For a list of all members of this type, see ChartLegend Members.

System.Object
Aspose.Words.Drawing.Charts.ChartLegend

[Visual Basic]
Public Class ChartLegend
[C#]
public class ChartLegend

Example

Shows how to edit the appearance of a chart's legend.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a line graph
Shape chartShape = builder.InsertChart(ChartType.Line, 450, 300);
Chart chart = chartShape.Chart;

// Get its legend
ChartLegend legend = chart.Legend;

// By default, other elements of a chart will not overlap with its legend
Assert.False(legend.Overlay);

// We can move its position by setting this attribute
legend.Position = LegendPosition.TopRight;

doc.Save(ArtifactsDir + "Charts.ChartLegend.docx");

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartLegend Members | Aspose.Words.Drawing.Charts Namespace


ChartLegend Members

ChartLegend overview

Public Instance Constructors

ChartLegend Constructor Initializes a new instance of the ChartLegend class.

Public Instance Properties

Overlay | Determines whether other chart elements shall be allowed to overlap legend. Default value is false.
Position | Specifies the position of the legend on a chart. Default value is Right.

See Also

ChartLegend Class | Aspose.Words.Drawing.Charts Namespace


ChartLegend Constructor

Initializes a new instance of the ChartLegend class.

[Visual Basic]
Public Sub New()
[C#]
public ChartLegend();

See Also

ChartLegend Class | Aspose.Words.Drawing.Charts Namespace


ChartLegend Properties

The properties of the ChartLegend class are listed below. For a complete list of ChartLegend class members, see the ChartLegend Members topic.

Public Instance Properties

Overlay | Determines whether other chart elements shall be allowed to overlap legend. Default value is false.
Position | Specifies the position of the legend on a chart. Default value is Right.

See Also

ChartLegend Class | Aspose.Words.Drawing.Charts Namespace


Overlay Property

Aspose.Words

ChartLegend.Overlay Property

Determines whether other chart elements shall be allowed to overlap legend. Default value is false.

[Visual Basic]
Public Property Overlay As Boolean
[C#]
public bool Overlay {get; set;}

Example

Shows how to edit the appearance of a chart's legend.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a line graph
Shape chartShape = builder.InsertChart(ChartType.Line, 450, 300);
Chart chart = chartShape.Chart;

// Get its legend
ChartLegend legend = chart.Legend;

// By default, other elements of a chart will not overlap with its legend
Assert.False(legend.Overlay);

// We can move its position by setting this attribute
legend.Position = LegendPosition.TopRight;

doc.Save(ArtifactsDir + "Charts.ChartLegend.docx");

See Also

ChartLegend Class | Aspose.Words.Drawing.Charts Namespace


Position Property

Aspose.Words

ChartLegend.Position Property

Specifies the position of the legend on a chart. Default value is Right.

[Visual Basic]
Public Property Position As LegendPosition
[C#]
public LegendPosition Position {get; set;}

Example

Shows how to edit the appearance of a chart's legend.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a line graph
Shape chartShape = builder.InsertChart(ChartType.Line, 450, 300);
Chart chart = chartShape.Chart;

// Get its legend
ChartLegend legend = chart.Legend;

// By default, other elements of a chart will not overlap with its legend
Assert.False(legend.Overlay);

// We can move its position by setting this attribute
legend.Position = LegendPosition.TopRight;

doc.Save(ArtifactsDir + "Charts.ChartLegend.docx");

See Also

ChartLegend Class | Aspose.Words.Drawing.Charts Namespace


ChartMarker Class

Represents a chart data marker.

For a list of all members of this type, see ChartMarker Members.

System.Object
Aspose.Words.Drawing.Charts.ChartMarker

[Visual Basic]
Public Class ChartMarker
[C#]
public class ChartMarker

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartMarker Members | Aspose.Words.Drawing.Charts Namespace


ChartMarker Members

ChartMarker overview

Public Instance Constructors

ChartMarker Constructor Initializes a new instance of the ChartMarker class.

Public Instance Properties

Size | Gets or sets chart marker size. Default value is 7.
Symbol | Gets or sets chart marker symbol.

See Also

ChartMarker Class | Aspose.Words.Drawing.Charts Namespace


ChartMarker Constructor

Initializes a new instance of the ChartMarker class.

[Visual Basic]
Public Sub New()
[C#]
public ChartMarker();

See Also

ChartMarker Class | Aspose.Words.Drawing.Charts Namespace


ChartMarker Properties

The properties of the ChartMarker class are listed below. For a complete list of ChartMarker class members, see the ChartMarker Members topic.

Public Instance Properties

Size | Gets or sets chart marker size. Default value is 7.
Symbol | Gets or sets chart marker symbol.

See Also

ChartMarker Class | Aspose.Words.Drawing.Charts Namespace


Size Property

Aspose.Words

ChartMarker.Size Property

Gets or sets chart marker size. Default value is 7.

[Visual Basic]
Public Property Size As Integer
[C#]
public int Size {get; set;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartMarker Class | Aspose.Words.Drawing.Charts Namespace


Symbol Property

Aspose.Words

ChartMarker.Symbol Property

Gets or sets chart marker symbol.

[Visual Basic]
Public Property Symbol As MarkerSymbol
[C#]
public MarkerSymbol Symbol {get; set;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartMarker Class | Aspose.Words.Drawing.Charts Namespace


ChartNumberFormat Class

Represents number formatting of the parent element.

For a list of all members of this type, see ChartNumberFormat Members.

System.Object
Aspose.Words.Drawing.Charts.ChartNumberFormat

[Visual Basic]
Public Class ChartNumberFormat
[C#]
public class ChartNumberFormat

Example

Shows how to set formatting for chart values.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 1900000, 850000, 2100000, 600000, 1500000 });

// Set number format.
chart.AxisY.NumberFormat.FormatCode = "#,##0";

// Set this to override the above value and draw the number format from the source cell
Assert.False(chart.AxisY.NumberFormat.IsLinkedToSource);

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartNumberFormat Members | Aspose.Words.Drawing.Charts Namespace


ChartNumberFormat Members

ChartNumberFormat overview

Public Instance Properties

FormatCode | Gets or sets the format code applied to a data label.
IsLinkedToSource | Specifies whether the format code is linked to a source cell. Default is true.

See Also

ChartNumberFormat Class | Aspose.Words.Drawing.Charts Namespace


ChartNumberFormat Properties

The properties of the ChartNumberFormat class are listed below. For a complete list of ChartNumberFormat class members, see the ChartNumberFormat Members topic.

Public Instance Properties

FormatCode | Gets or sets the format code applied to a data label.
IsLinkedToSource | Specifies whether the format code is linked to a source cell. Default is true.

See Also

ChartNumberFormat Class | Aspose.Words.Drawing.Charts Namespace


FormatCode Property

Aspose.Words

ChartNumberFormat.FormatCode Property

Gets or sets the format code applied to a data label.

[Visual Basic]
Public Property FormatCode As String
[C#]
public string FormatCode {get; set;}

Remarks

Number formatting is used to change the way a value appears in data label and can be used in some very creative ways. The examples of number formats:

Number - "#,##0.00"

Currency - "\"$\"#,##0.00"

Time - "[$-x-systime]h:mm:ss AM/PM"

Date - "d/mm/yyyy"

Percentage - "0.00%"

Fraction - "# ?/?"

Scientific - "0.00E+00"

Text - "@"

Accounting - "_-\"$\"* #,##0.00_-;-\"$\"* #,##0.00_-;_-\"$\"* \"-\"??_-;_-@_-"

Custom with color - "[Red]-#,##0.0"

Example

Shows how to set formatting for chart values.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 1900000, 850000, 2100000, 600000, 1500000 });

// Set number format.
chart.AxisY.NumberFormat.FormatCode = "#,##0";

// Set this to override the above value and draw the number format from the source cell
Assert.False(chart.AxisY.NumberFormat.IsLinkedToSource);

See Also

ChartNumberFormat Class | Aspose.Words.Drawing.Charts Namespace


IsLinkedToSource Property

Aspose.Words

ChartNumberFormat.IsLinkedToSource Property

Specifies whether the format code is linked to a source cell. Default is true.

[Visual Basic]
Public Property IsLinkedToSource As Boolean
[C#]
public bool IsLinkedToSource {get; set;}

Remarks

The NumberFormat will be reset to general if format code is linked to source.

Example

Shows how to set formatting for chart values.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;

// Clear demo data.
chart.Series.Clear();

chart.Series.Add("Aspose Test Series",
    new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
    new double[] { 1900000, 850000, 2100000, 600000, 1500000 });

// Set number format.
chart.AxisY.NumberFormat.FormatCode = "#,##0";

// Set this to override the above value and draw the number format from the source cell
Assert.False(chart.AxisY.NumberFormat.IsLinkedToSource);

See Also

ChartNumberFormat Class | Aspose.Words.Drawing.Charts Namespace


ChartSeries Class

Represents chart series properties.

For a list of all members of this type, see ChartSeries Members.

System.Object
Aspose.Words.Drawing.Charts.ChartSeries

[Visual Basic]
Public Class ChartSeries
Implements IChartDataPoint
[C#]
public class ChartSeries : IChartDataPoint

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartSeries Members | Aspose.Words.Drawing.Charts Namespace


ChartSeries Members

ChartSeries overview

Public Instance Properties

Bubble3D |
DataLabels | Specifies the settings for the data labels for the entire series.
DataPoints | Returns a collection of formatting objects for all data points in this series.
Explosion |
InvertIfNegative |
Marker |
Name | Gets or sets the name of the series, if name is not set explicitly it is generated using index. By default returns Series plus one based index.
Smooth | Allows to specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


ChartSeries Properties

The properties of the ChartSeries class are listed below. For a complete list of ChartSeries class members, see the ChartSeries Members topic.

Public Instance Properties

Bubble3D |
DataLabels | Specifies the settings for the data labels for the entire series.
DataPoints | Returns a collection of formatting objects for all data points in this series.
Explosion |
InvertIfNegative |
Marker |
Name | Gets or sets the name of the series, if name is not set explicitly it is generated using index. By default returns Series plus one based index.
Smooth | Allows to specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


Bubble3D Property

Aspose.Words

ChartSeries.Bubble3D Property

[Visual Basic]
NotOverridable Public Property Bubble3D As Boolean _
Implements IChartDataPoint.Bubble3D
[C#]
public bool Bubble3D {get; set;}

Implements

IChartDataPoint.Bubble3D

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


DataLabels Property

Aspose.Words

ChartSeries.DataLabels Property

Specifies the settings for the data labels for the entire series.

[Visual Basic]
Public ReadOnly Property DataLabels As ChartDataLabelCollection
[C#]
public ChartDataLabelCollection DataLabels {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


DataPoints Property

Aspose.Words

ChartSeries.DataPoints Property

Returns a collection of formatting objects for all data points in this series.

[Visual Basic]
Public ReadOnly Property DataPoints As ChartDataPointCollection
[C#]
public ChartDataPointCollection DataPoints {get;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


Explosion Property

Aspose.Words

ChartSeries.Explosion Property

[Visual Basic]
NotOverridable Public Property Explosion As Integer _
Implements IChartDataPoint.Explosion
[C#]
public int Explosion {get; set;}

Implements

IChartDataPoint.Explosion

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


InvertIfNegative Property

Aspose.Words

ChartSeries.InvertIfNegative Property

[Visual Basic]
NotOverridable Public Property InvertIfNegative As Boolean _
Implements IChartDataPoint.InvertIfNegative
[C#]
public bool InvertIfNegative {get; set;}

Implements

IChartDataPoint.InvertIfNegative

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


Marker Property

Aspose.Words

ChartSeries.Marker Property

[Visual Basic]
NotOverridable Public ReadOnly Property Marker As ChartMarker _
Implements IChartDataPoint.Marker
[C#]
public ChartMarker Marker {get;}

Implements

IChartDataPoint.Marker

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


Name Property

Aspose.Words

ChartSeries.Name Property

Gets or sets the name of the series, if name is not set explicitly it is generated using index. By default returns Series plus one based index.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Example

Shows how to apply labels to data points in a chart.

[C#]

public void ChartDataLabels()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a bar chart
    Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);

    // Get the chart object from the containing shape
    Chart chart = chartShape.Chart;

    // The chart already contains demo data comprised of 3 series each with 4 categories
    Assert.AreEqual(3, chart.Series.Count);
    Assert.AreEqual("Series 1", chart.Series[0].Name);

    // Apply data labels to every series in the graph
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataLabels(series, 4, "000.0", ", ");
        Assert.AreEqual(4, series.DataLabels.Count);
    }

    // Get the enumerator for a data label collection
    using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.AreEqual(", ", enumerator.Current.Separator);
            enumerator.Current.Separator = " & ";
        }
    }

    // If the chart looks too busy, we can remove data labels one by one
    chart.Series[1].DataLabels.RemoveAt(2);

    // We can also clear an entire data label collection for one whole series
    chart.Series[2].DataLabels.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}

/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
    for (int i = 0; i < labelsCount; i++)
    {
        ChartDataLabel label = series.DataLabels.Add(i);
        Assert.False(label.IsVisible);

        // Edit the appearance of the new data label
        label.ShowCategoryName = true;
        label.ShowSeriesName = true;
        label.ShowValue = true;
        label.ShowLeaderLines = true;
        label.ShowLegendKey = true;
        label.ShowPercentage = false;
        Assert.False(label.ShowDataLabelsRange);

        // Apply number format and separator
        label.NumberFormat.FormatCode = numberFormat;
        label.Separator = separator;

        // The label automatically becomes visible
        Assert.True(label.IsVisible);
    }
}

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


Smooth Property

Aspose.Words

ChartSeries.Smooth Property

Allows to specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.

[Visual Basic]
Public Property Smooth As Boolean
[C#]
public bool Smooth {get; set;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

ChartSeries Class | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection Class

Represents collection of a ChartSeries.

For a list of all members of this type, see ChartSeriesCollection Members.

System.Object
Aspose.Words.Drawing.Charts.ChartSeriesCollection

[Visual Basic]
Public Class ChartSeriesCollection
Implements IEnumerable`1([Aspose.Words.Drawing.Charts.ChartSeries, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class ChartSeriesCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to work with a chart's data collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;

// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);

// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
    // And use it to go over all the data labels in one series and change their separator
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current.Name);
    }
}

// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });

Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);

// We can remove series by index
chartData.RemoveAt(2);

Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);

// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();

Assert.AreEqual(0, chartData.Count);

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartSeriesCollection Members | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection Members

ChartSeriesCollection overview

Public Instance Properties

Count | Returns the number of ChartSeries in this collection.
Item | Returns a ChartSeries at the specified index.

Public Instance Methods

Add | Overloaded. Adds new ChartSeries to this collection. Use this method to add series to any type of Bar, Column, Line and Surface charts.
Clear | Removes all ChartSeries from this collection.
GetEnumerator | Returns an enumerator object.
RemoveAt | Removes a ChartSeries at the specified index.

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection Properties

The properties of the ChartSeriesCollection class are listed below. For a complete list of ChartSeriesCollection class members, see the ChartSeriesCollection Members topic.

Public Instance Properties

Count | Returns the number of ChartSeries in this collection.
Item | Returns a ChartSeries at the specified index.

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


Count Property

Aspose.Words

ChartSeriesCollection.Count Property

Returns the number of ChartSeries in this collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to work with a chart's data collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;

// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);

// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
    // And use it to go over all the data labels in one series and change their separator
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current.Name);
    }
}

// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });

Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);

// We can remove series by index
chartData.RemoveAt(2);

Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);

// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();

Assert.AreEqual(0, chartData.Count);

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


Item Property

Aspose.Words

ChartSeriesCollection.Item Property

Returns a ChartSeries at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As ChartSeries
[C#]
public ChartSeries this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to work with a chart's data collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;

// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);

// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
    // And use it to go over all the data labels in one series and change their separator
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current.Name);
    }
}

// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });

Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);

// We can remove series by index
chartData.RemoveAt(2);

Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);

// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();

Assert.AreEqual(0, chartData.Count);

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection Methods

The methods of the ChartSeriesCollection class are listed below. For a complete list of ChartSeriesCollection class members, see the ChartSeriesCollection Members topic.

Public Instance Methods

Add | Overloaded. Adds new ChartSeries to this collection. Use this method to add series to any type of Bar, Column, Line and Surface charts.
Clear | Removes all ChartSeries from this collection.
GetEnumerator | Returns an enumerator object.
RemoveAt | Removes a ChartSeries at the specified index.

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


Add Method

Aspose.Words

ChartSeriesCollection.Add Method

Adds new ChartSeries to this collection. Use this method to add series to any type of Area, Radar and Stock charts.

Overload List

Adds new ChartSeries to this collection. Use this method to add series to any type of Area, Radar and Stock charts.

public ChartSeries Add(string,DateTime[],double[]);

Adds new ChartSeries to this collection. Use this method to add series to any type of Scatter charts.

public ChartSeries Add(string,double[],double[]);

Adds new ChartSeries to this collection. Use this method to add series to any type of Bubble charts.

public ChartSeries Add(string,double[],double[],double[]);

Adds new ChartSeries to this collection. Use this method to add series to any type of Bar, Column, Line and Surface charts.

public ChartSeries Add(string,string[],double[]);

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection.Add Method (String, DateTime[], Double[])

Adds new ChartSeries to this collection. Use this method to add series to any type of Area, Radar and Stock charts.

[Visual Basic]
Overloads Public Function Add( _
ByVal seriesName As String, _
ByVal dates As Date(), _
ByVal values As Double() _
) As ChartSeries
[C#]
public ChartSeries Add(
string seriesName,
DateTime[] dates,
double[] values
);

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace | ChartSeriesCollection.Add Overload List


ChartSeriesCollection.Add Method (String, Double[], Double[])

Adds new ChartSeries to this collection. Use this method to add series to any type of Scatter charts.

[Visual Basic]
Overloads Public Function Add( _
ByVal seriesName As String, _
ByVal xValues As Double(), _
ByVal yValues As Double() _
) As ChartSeries
[C#]
public ChartSeries Add(
string seriesName,
double[] xValues,
double[] yValues
);

Return Value

Recently added ChartSeries object.

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace | ChartSeriesCollection.Add Overload List


ChartSeriesCollection.Add Method (String, Double[], Double[], Double[])

Adds new ChartSeries to this collection. Use this method to add series to any type of Bubble charts.

[Visual Basic]
Overloads Public Function Add( _
ByVal seriesName As String, _
ByVal xValues As Double(), _
ByVal yValues As Double(), _
ByVal bubbleSizes As Double() _
) As ChartSeries
[C#]
public ChartSeries Add(
string seriesName,
double[] xValues,
double[] yValues,
double[] bubbleSizes
);

Return Value

Recently added ChartSeries object.

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace | ChartSeriesCollection.Add Overload List


ChartSeriesCollection.Add Method (String, String[], Double[])

Adds new ChartSeries to this collection. Use this method to add series to any type of Bar, Column, Line and Surface charts.

[Visual Basic]
Overloads Public Function Add( _
ByVal seriesName As String, _
ByVal categories As String(), _
ByVal values As Double() _
) As ChartSeries
[C#]
public ChartSeries Add(
string seriesName,
string[] categories,
double[] values
);

Return Value

Recently added ChartSeries object.

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace | ChartSeriesCollection.Add Overload List


ChartSeriesCollection.Clear Method

Removes all ChartSeries from this collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to work with a chart's data collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;

// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);

// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
    // And use it to go over all the data labels in one series and change their separator
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current.Name);
    }
}

// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });

Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);

// We can remove series by index
chartData.RemoveAt(2);

Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);

// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();

Assert.AreEqual(0, chartData.Count);

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of ChartSeries) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<ChartSeries> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to work with a chart's data collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;

// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);

// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
    // And use it to go over all the data labels in one series and change their separator
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current.Name);
    }
}

// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });

Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);

// We can remove series by index
chartData.RemoveAt(2);

Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);

// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();

Assert.AreEqual(0, chartData.Count);

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartSeriesCollection.RemoveAt Method

Removes a ChartSeries at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the ChartSeries to remove.

Example

Shows how to work with a chart's data collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;

// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);

// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
    // And use it to go over all the data labels in one series and change their separator
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current.Name);
    }
}

// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });

Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);

// We can remove series by index
chartData.RemoveAt(2);

Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);

// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();

Assert.AreEqual(0, chartData.Count);

See Also

ChartSeriesCollection Class | Aspose.Words.Drawing.Charts Namespace


ChartTitle Class

Provides access to the chart title properties.

For a list of all members of this type, see ChartTitle Members.

System.Object
Aspose.Words.Drawing.Charts.ChartTitle

[Visual Basic]
Public Class ChartTitle
[C#]
public class ChartTitle

Example

Shows how to insert a chart and change its title.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);

Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);

// Get the chart object from the containing shape
Chart chart = chartShape.Chart;

// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;

doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ChartTitle Members | Aspose.Words.Drawing.Charts Namespace


ChartTitle Members

ChartTitle overview

Public Instance Properties

Overlay | Determines whether other chart elements shall be allowed to overlap title. By default overlay is false.
Show | Determines whether the title shall be shown for this chart. Default value is true.
Text | Gets or sets the text of the chart title. If null or empty value is specified, auto generated title will be shown.

See Also

ChartTitle Class | Aspose.Words.Drawing.Charts Namespace


ChartTitle Properties

The properties of the ChartTitle class are listed below. For a complete list of ChartTitle class members, see the ChartTitle Members topic.

Public Instance Properties

Overlay | Determines whether other chart elements shall be allowed to overlap title. By default overlay is false.
Show | Determines whether the title shall be shown for this chart. Default value is true.
Text | Gets or sets the text of the chart title. If null or empty value is specified, auto generated title will be shown.

See Also

ChartTitle Class | Aspose.Words.Drawing.Charts Namespace


Overlay Property

Aspose.Words

ChartTitle.Overlay Property

Determines whether other chart elements shall be allowed to overlap title. By default overlay is false.

[Visual Basic]
Public Property Overlay As Boolean
[C#]
public bool Overlay {get; set;}

Example

Shows how to insert a chart and change its title.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);

Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);

// Get the chart object from the containing shape
Chart chart = chartShape.Chart;

// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;

doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");

See Also

ChartTitle Class | Aspose.Words.Drawing.Charts Namespace


Show Property

Aspose.Words

ChartTitle.Show Property

Determines whether the title shall be shown for this chart. Default value is true.

[Visual Basic]
Public Property Show As Boolean
[C#]
public bool Show {get; set;}

Example

Shows how to insert a chart and change its title.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);

Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);

// Get the chart object from the containing shape
Chart chart = chartShape.Chart;

// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;

doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");

See Also

ChartTitle Class | Aspose.Words.Drawing.Charts Namespace


Text Property

Aspose.Words

ChartTitle.Text Property

Gets or sets the text of the chart title. If null or empty value is specified, auto generated title will be shown.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Remarks

Use Show option if you need to hide the Title.

Example

Shows how to insert a chart and change its title.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);

Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);

// Get the chart object from the containing shape
Chart chart = chartShape.Chart;

// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;

doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");

See Also

ChartTitle Class | Aspose.Words.Drawing.Charts Namespace


ChartType Enumeration

Specifies type of a chart.

[Visual Basic]
Public Enum ChartType
[C#]
public enum ChartType

Example

Shows an appropriate graph type for each chart series.

[C#]

public void ChartSeriesCollection()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // There are 4 ways of populating a chart's series collection
    // 1: Each series has a string array of categories, each with a corresponding data value
    // Some of the other possible applications are bar, column, line and surface charts
    Chart chart = AppendChart(builder, ChartType.Column, 300, 300);

    // Create and name 3 categories with a string array
    string[] categories = { "Category 1", "Category 2", "Category 3" };

    // Create 2 series of data, each with one point for every category
    // This will generate a column graph with 3 clusters of 2 bars
    chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
    chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });

    // Categories are distributed along the X-axis while values are distributed along the Y-axis
    Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 2: Each series will have a collection of dates with a corresponding value for each date
    // Area, radar and stock charts are some of the appropriate chart types for this
    chart = AppendChart(builder, ChartType.Area, 300, 300);

    // Create a collection of dates to serve as categories
    DateTime[] dates = { new DateTime(2014, 3, 31),
        new DateTime(2017, 1, 23),
        new DateTime(2017, 6, 18),
        new DateTime(2019, 11, 22),
        new DateTime(2020, 9, 7)
    };

    // Add one series with one point for each date
    // Our sporadic dates will be distributed along the X-axis in a linear fashion
    chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });

    // 3: Each series will take two data arrays
    // Appropriate for scatter plots
    chart = AppendChart(builder, ChartType.Scatter, 300, 300);

    // In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
    chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
    chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });

    // Both axes are value axes in this case
    Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
    Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);

    // 4: Each series will be built from three data arrays, used for bubble charts
    chart = AppendChart(builder, ChartType.Bubble, 300, 300);

    // The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
    chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });

    doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}

/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
    Shape chartShape = builder.InsertChart(chartType, width, height);
    Chart chart = chartShape.Chart;
    chart.Series.Clear();

    Assert.AreEqual(0, chart.Series.Count);

    return chart;
}

Members

Member Name | Description | Value
Area | Area chart. | 0
AreaStacked | Stacked Area chart. | 1
AreaPercentStacked | 100% Stacked Area chart. | 2
Area3D | 3D Area chart. | 3
Area3DStacked | 3D Stacked Area chart. | 4
Area3DPercentStacked | 3D 100% Stacked Area chart. | 5
Bar | Bar chart. | 6
BarStacked | Stacked Bar chart. | 7
BarPercentStacked | 100% Stacked Bar chart. | 8
Bar3D | 3D Bar chart. | 9
Bar3DStacked | 3D Stacked Bar chart. | 10
Bar3DPercentStacked | 3D 100% Stacked Bar chart. | 11
Bubble | Bubble chart. | 12
Bubble3D | 3D Bubble chart. | 13
Column | Column chart. | 14
ColumnStacked | Stacked Column chart. | 15
ColumnPercentStacked | 100% Stacked Column chart. | 16
Column3D | 3D Column chart. | 17
Column3DStacked | 3D Stacked Column chart. | 18
Column3DPercentStacked | 3D 100% Stacked Column chart. | 19
Column3DClustered | 3D Clustered Column chart. | 20
Doughnut | Doughnut chart. | 21
Line | Line chart. | 22
LineStacked | Stacked Line chart. | 23
LinePercentStacked | 100% Stacked Line chart. | 24
Line3D | 3D Line chart. | 25
Pie | Pie chart. | 26
Pie3D | 3D Pie chart. | 27
PieOfBar | Pie of Bar chart. | 28
PieOfPie | Pie of Pie chart. | 29
Radar | Radar chart. | 30
Scatter | Scatter chart. | 31
Stock | Stock chart. | 32
Surface | Surface chart. | 33
Surface3D | 3D Surface chart. | 34

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


IChartDataPoint Interface

Contains properties of a single data point on the chart.

For a list of all members of this type, see IChartDataPoint Members.

[Visual Basic]
Public Interface IChartDataPoint
[C#]
public interface IChartDataPoint

Types that implement IChartDataPoint

Type | Description
ChartDataPoint | Allows to specify formatting of a single data point on the chart.
ChartSeries | Represents chart series properties.

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IChartDataPoint Members | Aspose.Words.Drawing.Charts Namespace


IChartDataPoint Members

IChartDataPoint overview

Public Instance Properties

Bubble3D | Specifies whether the bubbles in Bubble chart should have a 3-D effect applied to them.
Explosion | Specifies the amount the data point shall be moved from the center of the pie. Can be negative, negative means that property is not set and no explosion should be applied. Applies only to Pie charts.
InvertIfNegative | Specifies whether the parent element shall inverts its colors if the value is negative.
Marker | Specifies a data marker. Marker is automatically created when requested.

See Also

IChartDataPoint Interface | Aspose.Words.Drawing.Charts Namespace


IChartDataPoint Properties

The properties of the IChartDataPoint interface are listed below. For a complete list of IChartDataPoint interface members, see the IChartDataPoint Members topic.

Public Instance Properties

Bubble3D | Specifies whether the bubbles in Bubble chart should have a 3-D effect applied to them.
Explosion | Specifies the amount the data point shall be moved from the center of the pie. Can be negative, negative means that property is not set and no explosion should be applied. Applies only to Pie charts.
InvertIfNegative | Specifies whether the parent element shall inverts its colors if the value is negative.
Marker | Specifies a data marker. Marker is automatically created when requested.

See Also

IChartDataPoint Interface | Aspose.Words.Drawing.Charts Namespace


Bubble3D Property

Aspose.Words

IChartDataPoint.Bubble3D Property

Specifies whether the bubbles in Bubble chart should have a 3-D effect applied to them.

[Visual Basic]
Property Bubble3D As Boolean
[C#]
bool Bubble3D {get; set;}

Example

Demonstrates bubble chart-exclusive features.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a bubble chart with 3D effects on each bubble
Shape shape = builder.InsertChart(ChartType.Bubble3D, 500, 350);
Chart chart = shape.Chart;

Assert.True(chart.Series[0].Bubble3D);

// Apply a data label to each bubble that displays the size of its bubble
for (int i = 0; i < 3; i++)
{
    ChartDataLabel cdl = chart.Series[0].DataLabels.Add(i);
    cdl.ShowBubbleSize = true;
}

doc.Save(ArtifactsDir + "Charts.Bubble3D.docx");

See Also

IChartDataPoint Interface | Aspose.Words.Drawing.Charts Namespace


Explosion Property

Aspose.Words

IChartDataPoint.Explosion Property

Specifies the amount the data point shall be moved from the center of the pie. Can be negative, negative means that property is not set and no explosion should be applied. Applies only to Pie charts.

[Visual Basic]
Property Explosion As Integer
[C#]
int Explosion {get; set;}

Example

Shows how to manipulate the position of the portions of a pie chart.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Shape shape = builder.InsertChart(ChartType.Pie, 500, 350);
Chart chart = shape.Chart;

// In a pie chart, the portions are the data points, which cannot have markers or sizes applied to them
// However, we can set this variable to move any individual "slice" away from the center of the chart
ChartDataPoint cdp = chart.Series[0].DataPoints.Add(0);
cdp.Explosion = 10;

cdp = chart.Series[0].DataPoints.Add(1);
cdp.Explosion = 40;

doc.Save(ArtifactsDir + "Charts.PieChartExplosion.docx");

See Also

IChartDataPoint Interface | Aspose.Words.Drawing.Charts Namespace


InvertIfNegative Property

Aspose.Words

IChartDataPoint.InvertIfNegative Property

Specifies whether the parent element shall inverts its colors if the value is negative.

[Visual Basic]
Property InvertIfNegative As Boolean
[C#]
bool InvertIfNegative {get; set;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

IChartDataPoint Interface | Aspose.Words.Drawing.Charts Namespace


Marker Property

Aspose.Words

IChartDataPoint.Marker Property

Specifies a data marker. Marker is automatically created when requested.

[Visual Basic]
Property Marker As ChartMarker
[C#]
ChartMarker Marker {get;}

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

See Also

IChartDataPoint Interface | Aspose.Words.Drawing.Charts Namespace


LegendPosition Enumeration

Specifies the possible positions for a chart legend.

[Visual Basic]
Public Enum LegendPosition
[C#]
public enum LegendPosition

Example

Shows how to edit the appearance of a chart's legend.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a line graph
Shape chartShape = builder.InsertChart(ChartType.Line, 450, 300);
Chart chart = chartShape.Chart;

// Get its legend
ChartLegend legend = chart.Legend;

// By default, other elements of a chart will not overlap with its legend
Assert.False(legend.Overlay);

// We can move its position by setting this attribute
legend.Position = LegendPosition.TopRight;

doc.Save(ArtifactsDir + "Charts.ChartLegend.docx");

Members

Member Name | Description | Value
None | No legend will be shown for the chart. | 0
Bottom | Specifies that the legend shall be drawn at the bottom of the chart. | 1
Left | Specifies that the legend shall be drawn at the left of the chart. | 2
Right | Specifies that the legend shall be drawn at the right of the chart. | 3
Top | Specifies that the legend shall be drawn at the top of the chart. | 4
TopRight | Specifies that the legend shall be drawn at the top right of the chart. | 5

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


MarkerSymbol Enumeration

Specifies marker symbol style.

[Visual Basic]
Public Enum MarkerSymbol
[C#]
public enum MarkerSymbol

Example

Shows how to customize chart data points.

[C#]

[Test]
public void ChartDataPoint()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Add a line chart, which will have default data that we will use
    Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
    Chart chart = shape.Chart;

    // Apply diamond-shaped data points to the line of the first series
    foreach (ChartSeries series in chart.Series)
    {
        ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
    }

    // We can further decorate a series line by smoothing it
    chart.Series[0].Smooth = true;

    // Get the enumerator for the data point collection from one series
    using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
    {
        // And use it to go over all the data labels in one series and change their separator
        while (enumerator.MoveNext())
        {
            Assert.False(enumerator.Current.InvertIfNegative);
        }
    }

    // If the chart looks too busy, we can remove data points one by one
    chart.Series[1].DataPoints.RemoveAt(2);

    // We can also clear an entire data point collection for one whole series
    chart.Series[2].DataPoints.Clear();

    doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}

/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
    for (int i = 0; i < dataPointsCount; i++)
    {
        ChartDataPoint point = series.DataPoints.Add(i);
        point.Marker.Symbol = markerSymbol;
        point.Marker.Size = dataPointSize;

        Assert.AreEqual(i, point.Index);
    }
}

Members

Member Name | Description | Value
Default | Specifies a default marker symbol shall be drawn at each data point. | 0
Circle | Specifies a circle shall be drawn at each data point. | 1
Dash | Specifies a dash shall be drawn at each data point. | 2
Diamond | Specifies a diamond shall be drawn at each data point. | 3
Dot | Specifies a dot shall be drawn at each data point. | 4
None | Specifies nothing shall be drawn at each data point. | 5
Picture | Specifies a picture shall be drawn at each data point. | 6
Plus | Specifies a plus shall be drawn at each data point. | 7
Square | Specifies a square shall be drawn at each data point. | 8
Star | Specifies a star shall be drawn at each data point. | 9
Triangle | Specifies a triangle shall be drawn at each data point. | 10
X | Specifies an X shall be drawn at each data point. | 11

Requirements

Namespace: Aspose.Words.Drawing.Charts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Charts Namespace


Aspose.Words.Drawing.Ole

Aspose.Words

Aspose.Words.Drawing.Ole Namespace

Contains classes to work with OLE / ActiveX controls and forms in Microsoft Word documents.

Namespace hierarchy

Classes

Class | Description
Forms2OleControl | Represents Microsoft Forms 2.0 OLE control.
Forms2OleControlCollection | Represents collection of Forms2OleControl objects.
OleControl | Represents OLE ActiveX control.

Enumerations

Enumeration | Description
Forms2OleControlType |


Forms2OleControl Class

Represents Microsoft Forms 2.0 OLE control.

For a list of all members of this type, see Forms2OleControl Members.

System.Object
Aspose.Words.Drawing.Ole.OleControl
Aspose.Words.Drawing.Ole.Forms2OleControl

[Visual Basic]
MustInherit Public Class Forms2OleControl
Inherits OleControl
[C#]
public abstract class Forms2OleControl : OleControl

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

Requirements

Namespace: Aspose.Words.Drawing.Ole

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Forms2OleControl Members | Aspose.Words.Drawing.Ole Namespace


Forms2OleControl Members

Forms2OleControl overview

Public Instance Properties

Caption | Gets Caption property of control. Default value is an empty string.
ChildNodes | Gets collection of immediate child controls.
Enabled | Returns true if control is in enabled state.
IsForms2OleControl |
Name (inherited from OleControl) | Gets name of the ActiveX control.
Type | Gets type of Forms 2.0 control.
Value | Gets underlying Value property which often represents control state. For example checked option button has '1' value while unchecked has '0'. Default value is an empty string.

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


Forms2OleControl Properties

The properties of the Forms2OleControl class are listed below. For a complete list of Forms2OleControl class members, see the Forms2OleControl Members topic.

Public Instance Properties

Caption | Gets Caption property of control. Default value is an empty string.
ChildNodes | Gets collection of immediate child controls.
Enabled | Returns true if control is in enabled state.
IsForms2OleControl |
Name (inherited from OleControl) | Gets name of the ActiveX control.
Type | Gets type of Forms 2.0 control.
Value | Gets underlying Value property which often represents control state. For example checked option button has '1' value while unchecked has '0'. Default value is an empty string.

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


Caption Property

Aspose.Words

Forms2OleControl.Caption Property

Gets Caption property of control. Default value is an empty string.

[Visual Basic]
Public ReadOnly Property Caption As String
[C#]
public string Caption {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


ChildNodes Property

Aspose.Words

Forms2OleControl.ChildNodes Property

Gets collection of immediate child controls.

[Visual Basic]
Public ReadOnly Property ChildNodes As Forms2OleControlCollection
[C#]
public Forms2OleControlCollection ChildNodes {get;}

Remarks

Returns null if this control can not have children.

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


Enabled Property

Aspose.Words

Forms2OleControl.Enabled Property

Returns true if control is in enabled state.

[Visual Basic]
Public ReadOnly Property Enabled As Boolean
[C#]
public bool Enabled {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


IsForms2OleControl Property

Aspose.Words

Forms2OleControl.IsForms2OleControl Property

[Visual Basic]
Overrides Public ReadOnly Property IsForms2OleControl As Boolean
[C#]
public override bool IsForms2OleControl {get;}

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


Type Property

Aspose.Words

Forms2OleControl.Type Property

Gets type of Forms 2.0 control.

[Visual Basic]
Public ReadOnly Property Type As Forms2OleControlType
[C#]
public Forms2OleControlType Type {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


Value Property

Aspose.Words

Forms2OleControl.Value Property

Gets underlying Value property which often represents control state. For example checked option button has '1' value while unchecked has '0'. Default value is an empty string.

[Visual Basic]
Public ReadOnly Property Value As String
[C#]
public string Value {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

Forms2OleControl Class | Aspose.Words.Drawing.Ole Namespace


Forms2OleControlCollection Class

Represents collection of Forms2OleControl objects.

For a list of all members of this type, see Forms2OleControlCollection Members.

System.Object
Aspose.Words.Drawing.Ole.Forms2OleControlCollection

[Visual Basic]
Public Class Forms2OleControlCollection
[C#]
public class Forms2OleControlCollection

Example

Shows how to access an OLE control embedded in a document and its child controls.

[C#]

// Open a document that contains a Microsoft Forms OLE control with child controls
Document doc = new Document(MyDir + "Shape.Ole.ControlCollection.docm");

// Get the shape that contains the control
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

Assert.AreEqual("6e182020-f460-11ce-9bcd-00aa00608e01", shape.OleFormat.Clsid.ToString());

Forms2OleControl oleControl = (Forms2OleControl)shape.OleFormat.OleControl;

// Some controls contain child controls
Forms2OleControlCollection oleControlCollection = oleControl.ChildNodes;

// In this case, the child controls are 3 option buttons
Assert.AreEqual(3, oleControlCollection.Count);

Assert.AreEqual("C#", oleControlCollection[0].Caption);
Assert.AreEqual("1", oleControlCollection[0].Value);

Assert.AreEqual("Visual Basic", oleControlCollection[1].Caption);
Assert.AreEqual("0", oleControlCollection[1].Value);

Assert.AreEqual("Delphi", oleControlCollection[2].Caption);
Assert.AreEqual("0", oleControlCollection[2].Value);

Requirements

Namespace: Aspose.Words.Drawing.Ole

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Forms2OleControlCollection Members | Aspose.Words.Drawing.Ole Namespace


Forms2OleControlCollection Members

Forms2OleControlCollection overview

Public Instance Constructors

Forms2OleControlCollection Constructor Initializes a new instance of the Forms2OleControlCollection class.

Public Instance Properties

Count | Gets count of objects in the collection.
Item | Gets Forms2OleControl object at specified index.

See Also

Forms2OleControlCollection Class | Aspose.Words.Drawing.Ole Namespace


Forms2OleControlCollection Constructor

Initializes a new instance of the Forms2OleControlCollection class.

[Visual Basic]
Public Sub New()
[C#]
public Forms2OleControlCollection();

See Also

Forms2OleControlCollection Class | Aspose.Words.Drawing.Ole Namespace


Forms2OleControlCollection Properties

The properties of the Forms2OleControlCollection class are listed below. For a complete list of Forms2OleControlCollection class members, see the Forms2OleControlCollection Members topic.

Public Instance Properties

Count | Gets count of objects in the collection.
Item | Gets Forms2OleControl object at specified index.

See Also

Forms2OleControlCollection Class | Aspose.Words.Drawing.Ole Namespace


Count Property

Aspose.Words

Forms2OleControlCollection.Count Property

Gets count of objects in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to access an OLE control embedded in a document and its child controls.

[C#]

// Open a document that contains a Microsoft Forms OLE control with child controls
Document doc = new Document(MyDir + "Shape.Ole.ControlCollection.docm");

// Get the shape that contains the control
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

Assert.AreEqual("6e182020-f460-11ce-9bcd-00aa00608e01", shape.OleFormat.Clsid.ToString());

Forms2OleControl oleControl = (Forms2OleControl)shape.OleFormat.OleControl;

// Some controls contain child controls
Forms2OleControlCollection oleControlCollection = oleControl.ChildNodes;

// In this case, the child controls are 3 option buttons
Assert.AreEqual(3, oleControlCollection.Count);

Assert.AreEqual("C#", oleControlCollection[0].Caption);
Assert.AreEqual("1", oleControlCollection[0].Value);

Assert.AreEqual("Visual Basic", oleControlCollection[1].Caption);
Assert.AreEqual("0", oleControlCollection[1].Value);

Assert.AreEqual("Delphi", oleControlCollection[2].Caption);
Assert.AreEqual("0", oleControlCollection[2].Value);

See Also

Forms2OleControlCollection Class | Aspose.Words.Drawing.Ole Namespace


Item Property

Aspose.Words

Forms2OleControlCollection.Item Property

Gets Forms2OleControl object at specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Forms2OleControl
[C#]
public Forms2OleControl this[
int index
] {get;}

Example

Shows how to access an OLE control embedded in a document and its child controls.

[C#]

// Open a document that contains a Microsoft Forms OLE control with child controls
Document doc = new Document(MyDir + "Shape.Ole.ControlCollection.docm");

// Get the shape that contains the control
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

Assert.AreEqual("6e182020-f460-11ce-9bcd-00aa00608e01", shape.OleFormat.Clsid.ToString());

Forms2OleControl oleControl = (Forms2OleControl)shape.OleFormat.OleControl;

// Some controls contain child controls
Forms2OleControlCollection oleControlCollection = oleControl.ChildNodes;

// In this case, the child controls are 3 option buttons
Assert.AreEqual(3, oleControlCollection.Count);

Assert.AreEqual("C#", oleControlCollection[0].Caption);
Assert.AreEqual("1", oleControlCollection[0].Value);

Assert.AreEqual("Visual Basic", oleControlCollection[1].Caption);
Assert.AreEqual("0", oleControlCollection[1].Value);

Assert.AreEqual("Delphi", oleControlCollection[2].Caption);
Assert.AreEqual("0", oleControlCollection[2].Value);

See Also

Forms2OleControlCollection Class | Aspose.Words.Drawing.Ole Namespace


Forms2OleControlType Enumeration

[Visual Basic]
Public Enum Forms2OleControlType
[C#]
public enum Forms2OleControlType

Members

Member Name | Description | Value
OptionButton |  | 0
Label |  | 1
Textbox |  | 2
CheckBox |  | 3
ToggleButton |  | 4
SpinButton |  | 5
ComboBox |  | 6
Frame |  | 7
MultiPage |  | 8
TabStrip |  | 9
CommandButton |  | 10
Image |  | 11
ScrollBar |  | 12
Form |  | 13
ListBox |  | 14

Requirements

Namespace: Aspose.Words.Drawing.Ole

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Drawing.Ole Namespace


OleControl Class

Represents OLE ActiveX control.

For a list of all members of this type, see OleControl Members.

System.Object
Aspose.Words.Drawing.Ole.OleControl
Aspose.Words.Drawing.Ole.Forms2OleControl

[Visual Basic]
Public Class OleControl
[C#]
public class OleControl

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

Requirements

Namespace: Aspose.Words.Drawing.Ole

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OleControl Members | Aspose.Words.Drawing.Ole Namespace


OleControl Members

OleControl overview

Public Instance Properties

IsForms2OleControl | Returns true if the control is a Forms2OleControl.
Name | Gets name of the ActiveX control.

See Also

OleControl Class | Aspose.Words.Drawing.Ole Namespace


OleControl Properties

The properties of the OleControl class are listed below. For a complete list of OleControl class members, see the OleControl Members topic.

Public Instance Properties

IsForms2OleControl | Returns true if the control is a Forms2OleControl.
Name | Gets name of the ActiveX control.

See Also

OleControl Class | Aspose.Words.Drawing.Ole Namespace


IsForms2OleControl Property

Aspose.Words

OleControl.IsForms2OleControl Property

Returns true if the control is a Forms2OleControl.

[Visual Basic]
Overridable Public ReadOnly Property IsForms2OleControl As Boolean
[C#]
public virtual bool IsForms2OleControl {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

OleControl Class | Aspose.Words.Drawing.Ole Namespace


Name Property

Aspose.Words

OleControl.Name Property

Gets name of the ActiveX control.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Example

Shows how to get ActiveX control and properties from the document.

[C#]

Document doc = new Document(MyDir + "Shape.ActiveXObject.docx");

//Get ActiveX control from the document
Shape shape = (Shape) doc.GetChild(NodeType.Shape, 0, true);
OleControl oleControl = shape.OleFormat.OleControl;

Assert.AreEqual(null, oleControl.Name);

//Get ActiveX control properties
if (oleControl.IsForms2OleControl)
{
    Forms2OleControl checkBox = (Forms2OleControl) oleControl;
    Assert.AreEqual("Первый", checkBox.Caption);
    Assert.AreEqual("0", checkBox.Value);
    Assert.AreEqual(true, checkBox.Enabled);
    Assert.AreEqual(Forms2OleControlType.CheckBox, checkBox.Type);
    Assert.AreEqual(null, checkBox.ChildNodes);
}

See Also

OleControl Class | Aspose.Words.Drawing.Ole Namespace


Aspose.Words.Fields

Aspose.Words

Aspose.Words.Fields Namespace

The Aspose.Words.Fields namespace contains classes that represent Microsoft Word fields in a document.

Namespace hierarchy

Classes

Class | Description
BarcodeParameters | Container class for barcode parameters to pass-through to BarcodeGenerator.
DropDownItemCollection | A collection of strings that represent all the items in a drop-down form field.
Field | Represents a Microsoft Word document field.
FieldAddIn | Implements the ADDIN field.
FieldAddressBlock | Implements the ADDRESSBLOCK field.
FieldAdvance | Implements the ADVANCE field.
FieldArgumentBuilder | Builds a complex field argument consisting of fields, nodes, and plain text.
FieldAsk | Implements the ASK field.
FieldAuthor | Implements the AUTHOR field.
FieldAutoNum | Implements the AUTONUM field.
FieldAutoNumLgl | Implements the AUTONUMLGL field.
FieldAutoNumOut | Implements the AUTONUMOUT field.
FieldAutoText | Implements the AUTOTEXT field.
FieldAutoTextList | Implements the AUTOTEXTLIST field.
FieldBarcode | Implements the BARCODE field.
FieldBibliography | Implements the BIBLIOGRAPHY field.
FieldBidiOutline | Implements the BIDIOUTLINE field.
FieldBuilder | Builds a field from field code tokens (arguments and switches).
FieldChar | Base class for nodes that represent field characters in a document.
FieldCitation | Implements the CITATION field.
FieldCollection | A collection of Field objects that represents the fields in the specified range.
FieldComments | Implements the COMMENTS field.
FieldCompare | Implements the COMPARE field.
FieldCreateDate | Implements the CREATEDATE field.
FieldData | Implements the DATA field.
FieldDatabase | Implements the DATABASE field.
FieldDate | Implements the DATE field.
FieldDde | Implements the DDE field.
FieldDdeAuto | Implements the DDEAUTO field.
FieldDisplayBarcode | Implements the DISPLAYBARCODE field.
FieldDocProperty | Implements the DOCPROPERTY field.
FieldDocVariable | Implements DOCVARIABLE field.
FieldEditTime | Implements the EDITTIME field.
FieldEmbed | Implements the EMBED field.
FieldEnd | Represents an end of a Word field in a document.
FieldEQ | Implements the EQ field.
FieldFileName | Implements the FILENAME field.
FieldFileSize | Implements the FILESIZE field.
FieldFillIn | Implements the FILLIN field.
FieldFootnoteRef | Implements the FOOTNOTEREF field.
FieldFormat | Provides typed access to field's numeric, date and time, and general formatting.
FieldFormCheckBox | Implements the FORMCHECKBOX field.
FieldFormDropDown | Implements the FORMDROPDOWN field.
FieldFormText | Implements the FORMTEXT field.
FieldFormula | Implements the = (formula) field.
FieldGlossary | Implements the GLOSSARY field.
FieldGoToButton | Implements the GOTOBUTTON field. Inserts a jump command, such that when it is activated, the insertion point of the document is moved to the specified location.
FieldGreetingLine | Implements the GREETINGLINE field.
FieldHyperlink | Implements the HYPERLINK field
FieldIf | Implements the IF field.
FieldImport | Implements the IMPORT field.
FieldInclude | Implements the INCLUDE field.
FieldIncludePicture | Implements the INCLUDEPICTURE field.
FieldIncludeText | Implements the INCLUDETEXT field.
FieldIndex | Implements the INDEX field.
FieldInfo | Implements the INFO field.
FieldKeywords | Implements the KEYWORDS field.
FieldLastSavedBy | Implements the LASTSAVEDBY field.
FieldLink | Implements the LINK field.
FieldListNum | Implements the LISTNUM field.
FieldMacroButton | Implements the MACROBUTTON field. Allows a macro or command to be run. In Aspose.Words this field can also act as a merge field.
FieldMergeBarcode | Implements the MERGEBARCODE field.
FieldMergeField | Implements the MERGEFIELD field.
FieldMergeRec | Implements the MERGEREC field.
FieldMergeSeq | Implements the MERGESEQ field.
FieldNext | Implements the NEXT field.
FieldNextIf | Implements the NEXTIF field.
FieldNoteRef | Implements the NOTEREF field.
FieldNumChars | Implements the NUMCHARS field.
FieldNumPages | Implements the NUMPAGES field.
FieldNumWords | Implements the NUMWORDS field.
FieldOcx | Implements the OCX field.
FieldOptions | Represents options to control field handling in a document.
FieldPage | Implements the PAGE field.
FieldPageRef | Implements the PAGEREF field.
FieldPrint | Implements the PRINT field.
FieldPrintDate | Implements the PRINTDATE field.
FieldPrivate | Implements the PRIVATE field.
FieldQuote | Implements the QUOTE field.
FieldRD | Implements the RD field.
FieldRef | Implements the REF field.
FieldRevNum | Implements the REVNUM field.
FieldSaveDate | Implements the SAVEDATE field.
FieldSection | Implements the SECTION field.
FieldSectionPages | Implements the SECTIONPAGES field.
FieldSeparator | Represents a Word field separator that separates the field code from the field result.
FieldSeq | Implements the SEQ field.
FieldSet | Implements the SET field.
FieldShape | Implements the SHAPE field.
FieldSkipIf | Implements the SKIPIF field.
FieldStart | Represents a start of a Word field in a document.
FieldStyleRef | Implements the STYLEREF field.
FieldSubject | Implements the SUBJECT field.
FieldSymbol | Implements a SYMBOL field.
FieldTA | Implements the TA field.
FieldTC | Implements the TC field.
FieldTemplate | Implements the TEMPLATE field.
FieldTime | Implements the TIME field.
FieldTitle | Implements the TITLE field.
FieldToa | Implements the TOA field.
FieldToc | Implements the TOC field.
FieldUnknown | Implements an unknown or unrecognized field.
FieldUserAddress | Implements the USERADDRESS field.
FieldUserInitials | Implements the USERINITIALS field.
FieldUserName | Implements the USERNAME field.
FieldXE | Implements the XE field.
FormField | Represents a single form field.
FormFieldCollection | A collection of FormField objects that represent all the form fields in a range.
GeneralFormatCollection | Represents a typed collection of general formats.
MergeFieldImageDimension | Represents an image dimension (i.e. the width or the height) used across a mail merge process.
ToaCategories | Represents a table of authorities categories.
UserInformation | Specifies information about the user.

Interfaces

Interface | Description
IBarcodeGenerator | Public interface for barcode custom generator. Implementation should be provided by user.
IFieldResultFormatter | Implement this interface if you want to control how the field result is formatted.
IFieldUpdateCultureProvider | When implemented, provides a CultureInfo object that should be used during the update of a particular field.
IFieldUserPromptRespondent | Represents the respondent to user prompts during field update.

Enumerations

Enumeration | Description
FieldIfComparisonResult | Specifies the result of the IF field condition evaluation.
FieldType | Specifies Microsoft Word field types.
FieldUpdateCultureSource | Indicates what culture to use during field update.
GeneralFormat | Specifies a general format that is applied to a numeric, text, or any field result. A field may have a combination of general formats.
MergeFieldImageDimensionUnit | Specifies an unit of an image dimension (i.e. the width or the height) used across a mail merge process.
TextFormFieldType | Specifies the type of a text form field.


BarcodeParameters Class

Container class for barcode parameters to pass-through to BarcodeGenerator.

For a list of all members of this type, see BarcodeParameters Members.

System.Object
Aspose.Words.Fields.BarcodeParameters

[Visual Basic]
Public Class BarcodeParameters
[C#]
public class BarcodeParameters

Remarks

The set of parameters are according to DISPLAYBARCODE field options. See the exact list at

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BarcodeParameters Members | Aspose.Words.Fields Namespace


BarcodeParameters Members

BarcodeParameters overview

Public Instance Constructors

BarcodeParameters Constructor Initializes a new instance of the BarcodeParameters class.

Public Instance Properties

AddStartStopChar | Whether to add Start/Stop characters for barcode types NW7 and CODE39.
BackgroundColor | Bar code background color (0x000000 - 0xFFFFFF)
BarcodeType | Bar code type.
BarcodeValue | Data to be encoded.
CaseCodeStyle | Style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]
DisplayText | Whether to display barcode data (text) along with image.
ErrorCorrectionLevel | Error correction level of QR Code. Valid values are [0, 3].
FacingIdentificationMark | Type of a Facing Identification Mark (FIM).
FixCheckDigit | Whether to fix the check digit if it’s invalid.
ForegroundColor | Bar code foreground color (0x000000 - 0xFFFFFF)
IsBookmark | Whether PostalAddress is the name of a bookmark.
IsUSPostalAddress | Whether PostalAddress is a U.S. postal address.
PosCodeStyle | Style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].
PostalAddress | Barcode postal address.
ScalingFactor | Scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000].
SymbolHeight | Bar code image height (in twips - 1/1440 inches)
SymbolRotation | Rotation of the barcode symbol. Valid values are [0, 3].

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


BarcodeParameters Constructor

Initializes a new instance of the BarcodeParameters class.

[Visual Basic]
Public Sub New()
[C#]
public BarcodeParameters();

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


BarcodeParameters Properties

The properties of the BarcodeParameters class are listed below. For a complete list of BarcodeParameters class members, see the BarcodeParameters Members topic.

Public Instance Properties

AddStartStopChar | Whether to add Start/Stop characters for barcode types NW7 and CODE39.
BackgroundColor | Bar code background color (0x000000 - 0xFFFFFF)
BarcodeType | Bar code type.
BarcodeValue | Data to be encoded.
CaseCodeStyle | Style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]
DisplayText | Whether to display barcode data (text) along with image.
ErrorCorrectionLevel | Error correction level of QR Code. Valid values are [0, 3].
FacingIdentificationMark | Type of a Facing Identification Mark (FIM).
FixCheckDigit | Whether to fix the check digit if it’s invalid.
ForegroundColor | Bar code foreground color (0x000000 - 0xFFFFFF)
IsBookmark | Whether PostalAddress is the name of a bookmark.
IsUSPostalAddress | Whether PostalAddress is a U.S. postal address.
PosCodeStyle | Style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].
PostalAddress | Barcode postal address.
ScalingFactor | Scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000].
SymbolHeight | Bar code image height (in twips - 1/1440 inches)
SymbolRotation | Rotation of the barcode symbol. Valid values are [0, 3].

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


AddStartStopChar Property

Aspose.Words

BarcodeParameters.AddStartStopChar Property

Whether to add Start/Stop characters for barcode types NW7 and CODE39.

[Visual Basic]
Public Property AddStartStopChar As Boolean
[C#]
public bool AddStartStopChar {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


BackgroundColor Property

Aspose.Words

BarcodeParameters.BackgroundColor Property

Bar code background color (0x000000 - 0xFFFFFF)

[Visual Basic]
Public Property BackgroundColor As String
[C#]
public string BackgroundColor {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


BarcodeType Property

Aspose.Words

BarcodeParameters.BarcodeType Property

Bar code type.

[Visual Basic]
Public Property BarcodeType As String
[C#]
public string BarcodeType {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


BarcodeValue Property

Aspose.Words

BarcodeParameters.BarcodeValue Property

Data to be encoded.

[Visual Basic]
Public Property BarcodeValue As String
[C#]
public string BarcodeValue {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


CaseCodeStyle Property

Aspose.Words

BarcodeParameters.CaseCodeStyle Property

Style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]

[Visual Basic]
Public Property CaseCodeStyle As String
[C#]
public string CaseCodeStyle {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


DisplayText Property

Aspose.Words

BarcodeParameters.DisplayText Property

Whether to display barcode data (text) along with image.

[Visual Basic]
Public Property DisplayText As Boolean
[C#]
public bool DisplayText {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


ErrorCorrectionLevel Property

Aspose.Words

BarcodeParameters.ErrorCorrectionLevel Property

Error correction level of QR Code. Valid values are [0, 3].

[Visual Basic]
Public Property ErrorCorrectionLevel As String
[C#]
public string ErrorCorrectionLevel {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


FacingIdentificationMark Property

Aspose.Words

BarcodeParameters.FacingIdentificationMark Property

Type of a Facing Identification Mark (FIM).

[Visual Basic]
Public Property FacingIdentificationMark As String
[C#]
public string FacingIdentificationMark {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


FixCheckDigit Property

Aspose.Words

BarcodeParameters.FixCheckDigit Property

Whether to fix the check digit if it’s invalid.

[Visual Basic]
Public Property FixCheckDigit As Boolean
[C#]
public bool FixCheckDigit {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


ForegroundColor Property

Aspose.Words

BarcodeParameters.ForegroundColor Property

Bar code foreground color (0x000000 - 0xFFFFFF)

[Visual Basic]
Public Property ForegroundColor As String
[C#]
public string ForegroundColor {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


IsBookmark Property

Aspose.Words

BarcodeParameters.IsBookmark Property

Whether PostalAddress is the name of a bookmark.

[Visual Basic]
Public Property IsBookmark As Boolean
[C#]
public bool IsBookmark {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


IsUSPostalAddress Property

Aspose.Words

BarcodeParameters.IsUSPostalAddress Property

Whether PostalAddress is a U.S. postal address.

[Visual Basic]
Public Property IsUSPostalAddress As Boolean
[C#]
public bool IsUSPostalAddress {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


PosCodeStyle Property

Aspose.Words

BarcodeParameters.PosCodeStyle Property

Style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].

[Visual Basic]
Public Property PosCodeStyle As String
[C#]
public string PosCodeStyle {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


PostalAddress Property

Aspose.Words

BarcodeParameters.PostalAddress Property

Barcode postal address.

[Visual Basic]
Public Property PostalAddress As String
[C#]
public string PostalAddress {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


ScalingFactor Property

Aspose.Words

BarcodeParameters.ScalingFactor Property

Scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000].

[Visual Basic]
Public Property ScalingFactor As String
[C#]
public string ScalingFactor {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


SymbolHeight Property

Aspose.Words

BarcodeParameters.SymbolHeight Property

Bar code image height (in twips - 1/1440 inches)

[Visual Basic]
Public Property SymbolHeight As String
[C#]
public string SymbolHeight {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


SymbolRotation Property

Aspose.Words

BarcodeParameters.SymbolRotation Property

Rotation of the barcode symbol. Valid values are [0, 3].

[Visual Basic]
Public Property SymbolRotation As String
[C#]
public string SymbolRotation {get; set;}

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

BarcodeParameters Class | Aspose.Words.Fields Namespace


DropDownItemCollection Class

A collection of strings that represent all the items in a drop-down form field.

For a list of all members of this type, see DropDownItemCollection Members.

System.Object
Aspose.Words.Fields.DropDownItemCollection

[Visual Basic]
Public Class DropDownItemCollection
Implements IEnumerable`1([System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), IEnumerable
[C#]
public class DropDownItemCollection : 0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], IEnumerable

Remarks

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DropDownItemCollection Members | Aspose.Words.Fields Namespace | FormField | DropDownItems


DropDownItemCollection Members

DropDownItemCollection overview

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets the element at the specified index.

Public Instance Methods

Add | Adds a string to the end of the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains the specified value.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf | Returns the zero-based index of the specified value in the collection.
Insert | Inserts a string into the collection at the specified index.
Remove | Removes the specified value from the collection.
RemoveAt | Removes a value at the specified index.

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace | FormField | DropDownItems


DropDownItemCollection Properties

The properties of the DropDownItemCollection class are listed below. For a complete list of DropDownItemCollection class members, see the DropDownItemCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets the element at the specified index.

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace | FormField | DropDownItems


Count Property

Aspose.Words

DropDownItemCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


Item Property

Aspose.Words

DropDownItemCollection.Item Property

Gets or sets the element at the specified index.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As String
[C#]
public string this[
int index
] {get; set;}

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection Methods

The methods of the DropDownItemCollection class are listed below. For a complete list of DropDownItemCollection class members, see the DropDownItemCollection Members topic.

Public Instance Methods

Add | Adds a string to the end of the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains the specified value.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf | Returns the zero-based index of the specified value in the collection.
Insert | Inserts a string into the collection at the specified index.
Remove | Removes the specified value from the collection.
RemoveAt | Removes a value at the specified index.

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace | FormField | DropDownItems


DropDownItemCollection.Add Method

Adds a string to the end of the collection.

[Visual Basic]
Public Function Add( _
ByVal value As String _
) As Integer
[C#]
public int Add(
string value
);

Parameters

value
The string to add to the end of the collection.

Return Value

The zero-based index at which the new element is inserted.

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.Contains Method

Determines whether the collection contains the specified value.

[Visual Basic]
Public Function Contains( _
ByVal value As String _
) As Boolean
[C#]
public bool Contains(
string value
);

Parameters

value
Case-sensitive value to locate.

Return Value

True if the item is found in the collection; otherwise, false.

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of String) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<string> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.IndexOf Method

Returns the zero-based index of the specified value in the collection.

[Visual Basic]
Public Function IndexOf( _
ByVal value As String _
) As Integer
[C#]
public int IndexOf(
string value
);

Parameters

value
The case-sensitive value to locate.

Return Value

The zero based index. Negative value if not found.

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.Insert Method

Inserts a string into the collection at the specified index.

[Visual Basic]
Public Sub Insert( _
ByVal index As Integer, _
ByVal value As String _
)
[C#]
public void Insert(
int index,
string value
);

Parameters

index
The zero-based index at which value is inserted.
value
The string to insert.

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.Remove Method

Removes the specified value from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal name As String _
)
[C#]
public void Remove(
string name
);

Parameters

name
The case-sensitive value to remove.

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


DropDownItemCollection.RemoveAt Method

Removes a value at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to insert a combo box field and manipulate the elements in its item collection.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to create and populate a combo box
string[] items = { "One", "Two", "Three" };
FormField comboBoxField = builder.InsertComboBox("DropDown", items, 0);

// Get the list of drop down items
DropDownItemCollection dropDownItems = comboBoxField.DropDownItems;

Assert.AreEqual(3, dropDownItems.Count);
Assert.AreEqual("One", dropDownItems[0]);
Assert.AreEqual(1, dropDownItems.IndexOf("Two"));
Assert.IsTrue(dropDownItems.Contains("Three"));

// We can add an item to the end of the collection or insert it at a desired index
dropDownItems.Add("Four");
dropDownItems.Insert(3, "Three and a half");
Assert.AreEqual(5, dropDownItems.Count);

// Iterate over the collection and print every element
using (IEnumerator<string> dropDownCollectionEnumerator = dropDownItems.GetEnumerator())
{
    while (dropDownCollectionEnumerator.MoveNext())
    {
        string currentItem = dropDownCollectionEnumerator.Current;
        Console.WriteLine(currentItem);
    }
}

// We can remove elements in the same way we added them
dropDownItems.Remove("Four");
dropDownItems.RemoveAt(3);
Assert.IsFalse(dropDownItems.Contains("Three and a half"));
Assert.IsFalse(dropDownItems.Contains("Four"));

doc.Save(ArtifactsDir + "Fields.DropDownItems.docx");

See Also

DropDownItemCollection Class | Aspose.Words.Fields Namespace


Field Class

Represents a Microsoft Word document field.

For a list of all members of this type, see Field Members.

System.Object
Aspose.Words.Fields.Field
Derived types

[Visual Basic]
Public Class Field
[C#]
public class Field

Remarks

A field in a Word document is a complex structure consisting of multiple nodes that include field start, field code, field separator, field result and field end. Fields can be nested, contain rich content and span multiple paragraphs or sections in a document. The Field class is a "facade" object that provides properties and methods that allow to work with a field as a single object.

The Start, Separator and End properties point to the field start, separator and end nodes of the field respectively.

The content between the field start and separator is the field code. The content between the field separator and field end is the field result. The field code typically consists of one or more Run objects that specify instructions. The processing application is expected to execute the field code to calculate the field result.

The process of calculating field results is called the field update. Aspose.Words can update field results of most of the field types in exactly the same way as Microsoft Word does it. Most notably, Aspose.Words can calculate results of even the most complex formula fields. To calculate the field result of a single field use the Update method. To update fields in the whole document use UpdateFields.

You can get the plain text version of the field code using the GetFieldCode method. You can get and set the plain text version of the field result using the Result property. Both the field code and field result can contain complex content, such as nested fields, paragraphs, shapes, tables and in this case you might want to work with the field nodes directly if you need more control.

You do not create instances of the Field class directly. To create a new field use the InsertField method.

Example

Inserts a field into a document using DocumentBuilder and FieldCode.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Field Members | Aspose.Words.Fields Namespace


Field Members

Field overview

Public Instance Properties

DisplayResult | Gets the text that represents the displayed field result.
End | Gets the node that represents the field end.
Format | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId | Gets or sets the LCID of the field.
Result | Gets or sets text that is between the field separator and field end.
Separator | Gets the node that represents the field separator. Can be null.
Start | Gets the node that represents the start of the field.
Type | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink | Performs the field unlink.
Update | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

Field Class | Aspose.Words.Fields Namespace


Field Properties

The properties of the Field class are listed below. For a complete list of Field class members, see the Field Members topic.

Public Instance Properties

DisplayResult | Gets the text that represents the displayed field result.
End | Gets the node that represents the field end.
Format | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId | Gets or sets the LCID of the field.
Result | Gets or sets text that is between the field separator and field end.
Separator | Gets the node that represents the field separator. Can be null.
Start | Gets the node that represents the start of the field.
Type | Gets the Microsoft Word field type.

See Also

Field Class | Aspose.Words.Fields Namespace


DisplayResult Property

Aspose.Words

Field.DisplayResult Property

Gets the text that represents the displayed field result.

[Visual Basic]
Public ReadOnly Property DisplayResult As String
[C#]
public string DisplayResult {get;}

Remarks

The UpdateListLabels method must be called to obtain correct value for the FieldListNum, FieldAutoNum, FieldAutoNumOut and FieldAutoNumLgl fields.

Example

Shows how to get the text that represents the displayed field result.

[C#]

Document document = new Document(MyDir + "Field.FieldDisplayResult.docx");

FieldCollection fields = document.Range.Fields;

Assert.AreEqual("111", fields[0].DisplayResult);
Assert.AreEqual("222", fields[1].DisplayResult);
Assert.AreEqual("Multi\rLine\rText", fields[2].DisplayResult);
Assert.AreEqual("%", fields[3].DisplayResult);
Assert.AreEqual("Macro Button Text", fields[4].DisplayResult);
Assert.AreEqual(string.Empty, fields[5].DisplayResult);

// Method must be called to obtain correct value for the "FieldListNum", "FieldAutoNum",
// "FieldAutoNumOut" and "FieldAutoNumLgl" fields
document.UpdateListLabels();

Assert.AreEqual("1)", fields[5].DisplayResult);

See Also

Field Class | Aspose.Words.Fields Namespace


End Property

Aspose.Words

Field.End Property

Gets the node that represents the field end.

[Visual Basic]
NotOverridable Public ReadOnly Property End As FieldEnd
[C#]
public FieldEnd End {get;}

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

Field Class | Aspose.Words.Fields Namespace


Format Property

Aspose.Words

Field.Format Property

Gets a FieldFormat object that provides typed access to field's formatting.

[Visual Basic]
Public ReadOnly Property Format As FieldFormat
[C#]
public FieldFormat Format {get;}

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

Field Class | Aspose.Words.Fields Namespace


IsDirty Property

Aspose.Words

Field.IsDirty Property

Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.

[Visual Basic]
Public Property IsDirty As Boolean
[C#]
public bool IsDirty {get; set;}

Example

Shows how to use special property for updating field result

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Field fieldToc = builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
fieldToc.IsDirty = true;

MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Docx);

Assert.IsTrue(doc.Range.Fields[0].IsDirty);

LoadOptions loadOptions = new LoadOptions { UpdateDirtyFields = false };
doc = new Document(stream, loadOptions);

See Also

Field Class | Aspose.Words.Fields Namespace


IsLocked Property

Aspose.Words

Field.IsLocked Property

Gets or sets whether the field is locked (should not recalculate its result).

[Visual Basic]
Public Property IsLocked As Boolean
[C#]
public bool IsLocked {get; set;}

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();

See Also

Field Class | Aspose.Words.Fields Namespace


LocaleId Property

Aspose.Words

Field.LocaleId Property

Gets or sets the LCID of the field.

[Visual Basic]
Public Property LocaleId As Integer
[C#]
public int LocaleId {get; set;}

Example

Get or sets locale for fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Field field = builder.InsertField(@"DATE \* MERGEFORMAT");
field.LocaleId = 2064;

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

Field newField = doc.Range.Fields[0];
Assert.AreEqual(2064, newField.LocaleId);

See Also

Field Class | Aspose.Words.Fields Namespace | FieldCode


Result Property

Aspose.Words

Field.Result Property

Gets or sets text that is between the field separator and field end.

[Visual Basic]
Public Property Result As String
[C#]
public string Result {get; set;}

Example

Inserts a field into a document using DocumentBuilder and FieldCode.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();

See Also

Field Class | Aspose.Words.Fields Namespace


Separator Property

Aspose.Words

Field.Separator Property

Gets the node that represents the field separator. Can be null.

[Visual Basic]
NotOverridable Public ReadOnly Property Separator As FieldSeparator
[C#]
public FieldSeparator Separator {get;}

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

Field Class | Aspose.Words.Fields Namespace


Start Property

Aspose.Words

Field.Start Property

Gets the node that represents the start of the field.

[Visual Basic]
NotOverridable Public ReadOnly Property Start As FieldStart
[C#]
public FieldStart Start {get;}

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

Field Class | Aspose.Words.Fields Namespace


Type Property

Aspose.Words

Field.Type Property

Gets the Microsoft Word field type.

[Visual Basic]
Overridable Public ReadOnly Property Type As FieldType
[C#]
public virtual FieldType Type {get;}

Example

Inserts a field into a document using DocumentBuilder and FieldCode.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();

See Also

Field Class | Aspose.Words.Fields Namespace


Field Methods

The methods of the Field class are listed below. For a complete list of Field class members, see the Field Members topic.

Public Instance Methods

GetFieldCode | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink | Performs the field unlink.
Update | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

Field Class | Aspose.Words.Fields Namespace


GetFieldCode Method

Aspose.Words

Field.GetFieldCode Method

Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.

Overload List

Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.

public string GetFieldCode();

Returns text between field start and field separator (or field end if there is no separator).

public string GetFieldCode(bool);

See Also

Field Class | Aspose.Words.Fields Namespace


Field.GetFieldCode Method ()

Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.

[Visual Basic]
Overloads Public Function GetFieldCode() As String
[C#]
public string GetFieldCode();

Example

Inserts a field into a document using DocumentBuilder and FieldCode.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();
Shows how to get text between field start and field separator (or field end if there is no separator)
[C#]

Document doc = new Document(MyDir + "Field.FieldCode.docx");

foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldIf)
    {
        FieldIf fieldIf = (FieldIf)field;

        string fieldCode = fieldIf.GetFieldCode();
        Assert.AreEqual(
            " IF " + ControlChar.FieldStartChar + " MERGEFIELD Q223 " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " > 0 \" (and additionally London Weighting of  " + ControlChar.FieldStartChar + " MERGEFIELD  Q223 \\f £ " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " per hour) \" \"\" ",

        if (containsNestedFields)
        {
            fieldCode = fieldIf.GetFieldCode(true);
            Assert.AreEqual(
                " IF " + ControlChar.FieldStartChar + " MERGEFIELD Q223 " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " > 0 \" (and additionally London Weighting of  " + ControlChar.FieldStartChar + " MERGEFIELD  Q223 \\f £ " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " per hour) \" \"\" ",
        }
        else
        {
            fieldCode = fieldIf.GetFieldCode(false);
            Assert.AreEqual(" IF  > 0 \" (and additionally London Weighting of   per hour) \" \"\" ",
        }
    }
}

See Also

Field Class | Aspose.Words.Fields Namespace | Field.GetFieldCode Overload List


Field.GetFieldCode Method (Boolean)

Returns text between field start and field separator (or field end if there is no separator).

[Visual Basic]
Overloads Public Function GetFieldCode( _
ByVal includeChildFieldCodes As Boolean _
) As String
[C#]
public string GetFieldCode(
bool includeChildFieldCodes
);

Parameters

includeChildFieldCodes
True if child field codes should be included.

Example

Shows how to get text between field start and field separator (or field end if there is no separator)

[C#]

Document doc = new Document(MyDir + "Field.FieldCode.docx");

foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldIf)
    {
        FieldIf fieldIf = (FieldIf)field;

        string fieldCode = fieldIf.GetFieldCode();
        Assert.AreEqual(
            " IF " + ControlChar.FieldStartChar + " MERGEFIELD Q223 " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " > 0 \" (and additionally London Weighting of  " + ControlChar.FieldStartChar + " MERGEFIELD  Q223 \\f £ " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " per hour) \" \"\" ",

        if (containsNestedFields)
        {
            fieldCode = fieldIf.GetFieldCode(true);
            Assert.AreEqual(
                " IF " + ControlChar.FieldStartChar + " MERGEFIELD Q223 " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " > 0 \" (and additionally London Weighting of  " + ControlChar.FieldStartChar + " MERGEFIELD  Q223 \\f £ " + ControlChar.FieldSeparatorChar + ControlChar.FieldEndChar + " per hour) \" \"\" ",
        }
        else
        {
            fieldCode = fieldIf.GetFieldCode(false);
            Assert.AreEqual(" IF  > 0 \" (and additionally London Weighting of   per hour) \" \"\" ",
        }
    }
}

See Also

Field Class | Aspose.Words.Fields Namespace | Field.GetFieldCode Overload List


Field.Remove Method

Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.

[Visual Basic]
Public Function Remove() As Node
[C#]
public Node Remove();

Example

Inserts a field into a document using DocumentBuilder and FieldCode.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();
Shows how to work with a document's field collection.
[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

Field Class | Aspose.Words.Fields Namespace


Field.Unlink Method

Performs the field unlink.

[Visual Basic]
Public Function Unlink() As Boolean
[C#]
public bool Unlink();

Return Value

True if the field has been unlinked, otherwise false.

Remarks

Replaces the field with its most recent result.

Some fields, such as XE (Index Entry) fields and SEQ (Sequence) fields, cannot be unlinked.

Example

Shows how to unlink specific field

[C#]

Document doc = new Document(MyDir + "Field.UnlinkFields.docx");
doc.Range.Fields[1].Unlink();

See Also

Field Class | Aspose.Words.Fields Namespace


Update Method

Aspose.Words

Field.Update Method

Performs the field update. Throws if the field is being updated already.

Overload List

Performs the field update. Throws if the field is being updated already.

public void Update();

Performs a field update. Throws if the field is being updated already.

public void Update(bool);

See Also

Field Class | Aspose.Words.Fields Namespace


Field.Update Method ()

Performs the field update. Throws if the field is being updated already.

[Visual Basic]
Overloads Public Sub Update()
[C#]
public void Update();

Example

Inserts a field into a document using DocumentBuilder and FieldCode.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();

See Also

Field Class | Aspose.Words.Fields Namespace | Field.Update Overload List


Field.Update Method (Boolean)

Performs a field update. Throws if the field is being updated already.

[Visual Basic]
Overloads Public Sub Update( _
ByVal ignoreMergeFormat As Boolean _
)
[C#]
public void Update(
bool ignoreMergeFormat
);

Parameters

ignoreMergeFormat
If true then direct field result formatting is abandoned, regardless of the MERGEFORMAT switch, otherwise normal update is performed.

Example

Shows a way to update a field ignoring the MERGEFORMAT switch

[C#]

LoadOptions loadOptions = new LoadOptions { PreserveIncludePictureField = true };

Document doc = new Document(MyDir + "Field.UpdateFieldIgnoringMergeFormat.docx", loadOptions);

foreach (Field field in doc.Range.Fields)
{
    if (field.Type.Equals(FieldType.FieldIncludePicture))
    {
        FieldIncludePicture includePicture = (FieldIncludePicture)field;

        includePicture.SourceFullName = MyDir + "Images/dotnet-logo.png";
        includePicture.Update(true);
    }
}

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.UpdateFieldIgnoringMergeFormat.docx");

See Also

Field Class | Aspose.Words.Fields Namespace | Field.Update Overload List


FieldAddIn Class

Implements the ADDIN field.

For a list of all members of this type, see FieldAddIn Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAddIn

[Visual Basic]
Public Class FieldAddIn
Inherits Field
[C#]
public class FieldAddIn : Field

Remarks

Contains data created by an add-in.

Example

Shows how to process an ADDIN field.

[C#]

// Open a document that contains an ADDIN field
Document doc = new Document(MyDir + "Field.Addin.docx");

// Aspose.Words does not support inserting ADDIN fields, but they can be read
FieldAddIn field = (FieldAddIn)doc.Range.Fields[0];
Assert.AreEqual(" ADDIN \"My value\" ", field.GetFieldCode());

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAddIn Members | Aspose.Words.Fields Namespace


FieldAddIn Members

FieldAddIn overview

Public Instance Constructors

FieldAddIn Constructor Initializes a new instance of the FieldAddIn class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAddIn Class | Aspose.Words.Fields Namespace


FieldAddIn Constructor

Initializes a new instance of the FieldAddIn class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAddIn();

See Also

FieldAddIn Class | Aspose.Words.Fields Namespace


FieldAddressBlock Class

Implements the ADDRESSBLOCK field.

For a list of all members of this type, see FieldAddressBlock Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAddressBlock

[Visual Basic]
Public Class FieldAddressBlock
Inherits Field
[C#]
public class FieldAddressBlock : Field

Remarks

Represents an address block. An address block is a block of text specifying information appropriate for a postal mailing address, in the order required by the destination country.

Example

Shows how to get mail merge field names used by the field

[C#]

Document doc = new Document(MyDir + "MailMerge.GetFieldNames.docx");

string[] addressFieldsExpect =
{
    "Company", "First Name", "Middle Name", "Last Name", "Suffix", "Address 1", "City", "State",
    "Country or Region", "Postal Code"
};

FieldAddressBlock addressBlockField = (FieldAddressBlock) doc.Range.Fields[0];
string[] addressBlockFieldNames = addressBlockField.GetFieldNames();

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAddressBlock Members | Aspose.Words.Fields Namespace


FieldAddressBlock Members

FieldAddressBlock overview

Public Instance Constructors

FieldAddressBlock Constructor Initializes a new instance of the FieldAddressBlock class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
ExcludedCountryOrRegionName | Gets or sets the excluded country/region name.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatAddressOnCountryOrRegion | Gets or sets whether to format the address according to the country/region of the recipient as defined by POST*CODE (Universal Postal Union 2006).
IncludeCountryOrRegionName | Gets or sets whether to include the name of the country/region.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LanguageId | Gets or sets the language ID used to format the address.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NameAndAddressFormat | Gets or sets the name and address format.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
GetFieldNames | Returns a collection of mail merge field names used by the field.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


FieldAddressBlock Constructor

Initializes a new instance of the FieldAddressBlock class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAddressBlock();

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


FieldAddressBlock Properties

The properties of the FieldAddressBlock class are listed below. For a complete list of FieldAddressBlock class members, see the FieldAddressBlock Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
ExcludedCountryOrRegionName | Gets or sets the excluded country/region name.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatAddressOnCountryOrRegion | Gets or sets whether to format the address according to the country/region of the recipient as defined by POST*CODE (Universal Postal Union 2006).
IncludeCountryOrRegionName | Gets or sets whether to include the name of the country/region.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LanguageId | Gets or sets the language ID used to format the address.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NameAndAddressFormat | Gets or sets the name and address format.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


ExcludedCountryOrRegionName Property

Aspose.Words

FieldAddressBlock.ExcludedCountryOrRegionName Property

Gets or sets the excluded country/region name.

[Visual Basic]
Public Property ExcludedCountryOrRegionName As String
[C#]
public string ExcludedCountryOrRegionName {get; set;}

Example

Shows how to build a field address block.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a field address block
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, true);

// Initially our field is an empty address block field with null attributes
Assert.AreEqual(" ADDRESSBLOCK ", field.GetFieldCode());

// Setting this to "2" will cause all countries/regions to be included, unless it is the one specified in the ExcludedCountryOrRegionName attribute
field.IncludeCountryOrRegionName = "2";
field.FormatAddressOnCountryOrRegion = true;
field.ExcludedCountryOrRegionName = "United States";

// Specify our own name and address format
field.NameAndAddressFormat = "<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>";

// By default, the language ID will be set to that of the first character of the document
// In this case we will specify it to be English
field.LanguageId = "1033";

// Our field code has changed according to the attribute values that we set
Assert.AreEqual(
    " ADDRESSBLOCK  \\c 2 \\d \\e \"United States\" \\f \"<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>\" \\l 1033",
    field.GetFieldCode());

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


FormatAddressOnCountryOrRegion Property

Aspose.Words

FieldAddressBlock.FormatAddressOnCountryOrRegion Property

Gets or sets whether to format the address according to the country/region of the recipient as defined by POST*CODE (Universal Postal Union 2006).

[Visual Basic]
Public Property FormatAddressOnCountryOrRegion As Boolean
[C#]
public bool FormatAddressOnCountryOrRegion {get; set;}

Example

Shows how to build a field address block.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a field address block
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, true);

// Initially our field is an empty address block field with null attributes
Assert.AreEqual(" ADDRESSBLOCK ", field.GetFieldCode());

// Setting this to "2" will cause all countries/regions to be included, unless it is the one specified in the ExcludedCountryOrRegionName attribute
field.IncludeCountryOrRegionName = "2";
field.FormatAddressOnCountryOrRegion = true;
field.ExcludedCountryOrRegionName = "United States";

// Specify our own name and address format
field.NameAndAddressFormat = "<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>";

// By default, the language ID will be set to that of the first character of the document
// In this case we will specify it to be English
field.LanguageId = "1033";

// Our field code has changed according to the attribute values that we set
Assert.AreEqual(
    " ADDRESSBLOCK  \\c 2 \\d \\e \"United States\" \\f \"<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>\" \\l 1033",
    field.GetFieldCode());

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


IncludeCountryOrRegionName Property

Aspose.Words

FieldAddressBlock.IncludeCountryOrRegionName Property

Gets or sets whether to include the name of the country/region.

[Visual Basic]
Public Property IncludeCountryOrRegionName As String
[C#]
public string IncludeCountryOrRegionName {get; set;}

Example

Shows how to build a field address block.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a field address block
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, true);

// Initially our field is an empty address block field with null attributes
Assert.AreEqual(" ADDRESSBLOCK ", field.GetFieldCode());

// Setting this to "2" will cause all countries/regions to be included, unless it is the one specified in the ExcludedCountryOrRegionName attribute
field.IncludeCountryOrRegionName = "2";
field.FormatAddressOnCountryOrRegion = true;
field.ExcludedCountryOrRegionName = "United States";

// Specify our own name and address format
field.NameAndAddressFormat = "<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>";

// By default, the language ID will be set to that of the first character of the document
// In this case we will specify it to be English
field.LanguageId = "1033";

// Our field code has changed according to the attribute values that we set
Assert.AreEqual(
    " ADDRESSBLOCK  \\c 2 \\d \\e \"United States\" \\f \"<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>\" \\l 1033",
    field.GetFieldCode());

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


LanguageId Property

Aspose.Words

FieldAddressBlock.LanguageId Property

Gets or sets the language ID used to format the address.

[Visual Basic]
Public Property LanguageId As String
[C#]
public string LanguageId {get; set;}

Example

Shows how to build a field address block.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a field address block
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, true);

// Initially our field is an empty address block field with null attributes
Assert.AreEqual(" ADDRESSBLOCK ", field.GetFieldCode());

// Setting this to "2" will cause all countries/regions to be included, unless it is the one specified in the ExcludedCountryOrRegionName attribute
field.IncludeCountryOrRegionName = "2";
field.FormatAddressOnCountryOrRegion = true;
field.ExcludedCountryOrRegionName = "United States";

// Specify our own name and address format
field.NameAndAddressFormat = "<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>";

// By default, the language ID will be set to that of the first character of the document
// In this case we will specify it to be English
field.LanguageId = "1033";

// Our field code has changed according to the attribute values that we set
Assert.AreEqual(
    " ADDRESSBLOCK  \\c 2 \\d \\e \"United States\" \\f \"<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>\" \\l 1033",
    field.GetFieldCode());

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


NameAndAddressFormat Property

Aspose.Words

FieldAddressBlock.NameAndAddressFormat Property

Gets or sets the name and address format.

[Visual Basic]
Public Property NameAndAddressFormat As String
[C#]
public string NameAndAddressFormat {get; set;}

Example

Shows how to build a field address block.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a field address block
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, true);

// Initially our field is an empty address block field with null attributes
Assert.AreEqual(" ADDRESSBLOCK ", field.GetFieldCode());

// Setting this to "2" will cause all countries/regions to be included, unless it is the one specified in the ExcludedCountryOrRegionName attribute
field.IncludeCountryOrRegionName = "2";
field.FormatAddressOnCountryOrRegion = true;
field.ExcludedCountryOrRegionName = "United States";

// Specify our own name and address format
field.NameAndAddressFormat = "<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>";

// By default, the language ID will be set to that of the first character of the document
// In this case we will specify it to be English
field.LanguageId = "1033";

// Our field code has changed according to the attribute values that we set
Assert.AreEqual(
    " ADDRESSBLOCK  \\c 2 \\d \\e \"United States\" \\f \"<Title> <Forename> <Surname> <Address Line 1> <Region> <Postcode> <Country>\" \\l 1033",
    field.GetFieldCode());

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


FieldAddressBlock Methods

The methods of the FieldAddressBlock class are listed below. For a complete list of FieldAddressBlock class members, see the FieldAddressBlock Members topic.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
GetFieldNames | Returns a collection of mail merge field names used by the field.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


FieldAddressBlock.GetFieldNames Method

Returns a collection of mail merge field names used by the field.

[Visual Basic]
NotOverridable Public Function GetFieldNames() As String()
[C#]
public string[] GetFieldNames();

Example

Shows how to get mail merge field names used by the field

[C#]

Document doc = new Document(MyDir + "MailMerge.GetFieldNames.docx");

string[] addressFieldsExpect =
{
    "Company", "First Name", "Middle Name", "Last Name", "Suffix", "Address 1", "City", "State",
    "Country or Region", "Postal Code"
};

FieldAddressBlock addressBlockField = (FieldAddressBlock) doc.Range.Fields[0];
string[] addressBlockFieldNames = addressBlockField.GetFieldNames();

See Also

FieldAddressBlock Class | Aspose.Words.Fields Namespace


FieldAdvance Class

Implements the ADVANCE field.

For a list of all members of this type, see FieldAdvance Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAdvance

[Visual Basic]
Public Class FieldAdvance
Inherits Field
[C#]
public class FieldAdvance : Field

Remarks

Moves the starting point at which the text that lexically follows the field is displayed to the right or left, up or down, or to a specific horizontal or vertical position.

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAdvance Members | Aspose.Words.Fields Namespace


FieldAdvance Members

FieldAdvance overview

Public Instance Constructors

FieldAdvance Constructor Initializes a new instance of the FieldAdvance class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DownOffset | Gets or sets the number of points by which the text that follows the field should be moved down.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HorizontalPosition | Gets or sets the number of points by which the text that follows the field should be moved horizontally from the left edge of the column, frame, or text box.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftOffset | Gets or sets the number of points by which the text that follows the field should be moved left.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightOffset | Gets or sets the number of points by which the text that follows the field should be moved right.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UpOffset | Gets or sets the number of points by which the text that follows the field should be moved up.
VerticalPosition | Gets or sets the number of points by which the text that follows the field should be moved vertically from the top edge of the page.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


FieldAdvance Constructor

Initializes a new instance of the FieldAdvance class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAdvance();

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


FieldAdvance Properties

The properties of the FieldAdvance class are listed below. For a complete list of FieldAdvance class members, see the FieldAdvance Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DownOffset | Gets or sets the number of points by which the text that follows the field should be moved down.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HorizontalPosition | Gets or sets the number of points by which the text that follows the field should be moved horizontally from the left edge of the column, frame, or text box.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftOffset | Gets or sets the number of points by which the text that follows the field should be moved left.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightOffset | Gets or sets the number of points by which the text that follows the field should be moved right.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UpOffset | Gets or sets the number of points by which the text that follows the field should be moved up.
VerticalPosition | Gets or sets the number of points by which the text that follows the field should be moved vertically from the top edge of the page.

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


DownOffset Property

Aspose.Words

FieldAdvance.DownOffset Property

Gets or sets the number of points by which the text that follows the field should be moved down.

[Visual Basic]
Public Property DownOffset As String
[C#]
public string DownOffset {get; set;}

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


HorizontalPosition Property

Aspose.Words

FieldAdvance.HorizontalPosition Property

Gets or sets the number of points by which the text that follows the field should be moved horizontally from the left edge of the column, frame, or text box.

[Visual Basic]
Public Property HorizontalPosition As String
[C#]
public string HorizontalPosition {get; set;}

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


LeftOffset Property

Aspose.Words

FieldAdvance.LeftOffset Property

Gets or sets the number of points by which the text that follows the field should be moved left.

[Visual Basic]
Public Property LeftOffset As String
[C#]
public string LeftOffset {get; set;}

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


RightOffset Property

Aspose.Words

FieldAdvance.RightOffset Property

Gets or sets the number of points by which the text that follows the field should be moved right.

[Visual Basic]
Public Property RightOffset As String
[C#]
public string RightOffset {get; set;}

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


UpOffset Property

Aspose.Words

FieldAdvance.UpOffset Property

Gets or sets the number of points by which the text that follows the field should be moved up.

[Visual Basic]
Public Property UpOffset As String
[C#]
public string UpOffset {get; set;}

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


VerticalPosition Property

Aspose.Words

FieldAdvance.VerticalPosition Property

Gets or sets the number of points by which the text that follows the field should be moved vertically from the top edge of the page.

[Visual Basic]
Public Property VerticalPosition As String
[C#]
public string VerticalPosition {get; set;}

Example

Shows how to insert an advance field and edit its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("This text is in its normal place.");
// Create an advance field using document builder
FieldAdvance field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);

builder.Write("This text is moved up and to the right.");

Assert.AreEqual(FieldType.FieldAdvance, field.Type);
Assert.AreEqual(" ADVANCE ", field.GetFieldCode());
// The second text that the builder added will now be moved
field.RightOffset = "5";
field.UpOffset = "5";

Assert.AreEqual(" ADVANCE  \\r 5 \\u 5", field.GetFieldCode());
// If we want to move text in the other direction, and try do that by using negative values for the above field members, we will get an error in our document
// Instead, we need to specify a positive value for the opposite respective field directional variable
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.DownOffset = "5";
field.LeftOffset = "100";

Assert.AreEqual(" ADVANCE  \\d 5 \\l 100", field.GetFieldCode());
// We are still on one paragraph
Assert.AreEqual(1, doc.FirstSection.Body.Paragraphs.Count);
// Since we're setting horizontal and vertical positions next, we need to end the paragraph so the previous line does not get moved with the next one
builder.Writeln("This text is moved down and to the left, overlapping the previous text.");
// This time we can also use negative values
field = (FieldAdvance)builder.InsertField(FieldType.FieldAdvance, true);
field.HorizontalPosition = "-100";
field.VerticalPosition = "200";

Assert.AreEqual(" ADVANCE  \\x -100 \\y 200", field.GetFieldCode());

builder.Write("This text is in a custom position.");

doc.Save(ArtifactsDir + "Field.Advance.docx");

See Also

FieldAdvance Class | Aspose.Words.Fields Namespace


FieldArgumentBuilder Class

Builds a complex field argument consisting of fields, nodes, and plain text.

For a list of all members of this type, see FieldArgumentBuilder Members.

System.Object
Aspose.Words.Fields.FieldArgumentBuilder

[Visual Basic]
Public Class FieldArgumentBuilder
[C#]
public class FieldArgumentBuilder

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldArgumentBuilder Members | Aspose.Words.Fields Namespace


FieldArgumentBuilder Members

FieldArgumentBuilder overview

Public Instance Constructors

FieldArgumentBuilder Constructor Initializes an instance of the FieldArgumentBuilder class.

Public Instance Methods

AddField | Adds a field represented by a FieldBuilder to the argument.
AddNode | Adds a node to the argument.
AddText | Adds a plain text to the argument.

See Also

FieldArgumentBuilder Class | Aspose.Words.Fields Namespace


FieldArgumentBuilder Constructor

Initializes an instance of the FieldArgumentBuilder class.

[Visual Basic]
Public Sub New()
[C#]
public FieldArgumentBuilder();

See Also

FieldArgumentBuilder Class | Aspose.Words.Fields Namespace


FieldArgumentBuilder Methods

The methods of the FieldArgumentBuilder class are listed below. For a complete list of FieldArgumentBuilder class members, see the FieldArgumentBuilder Members topic.

Public Instance Methods

AddField | Adds a field represented by a FieldBuilder to the argument.
AddNode | Adds a node to the argument.
AddText | Adds a plain text to the argument.

See Also

FieldArgumentBuilder Class | Aspose.Words.Fields Namespace


FieldArgumentBuilder.AddField Method

Adds a field represented by a FieldBuilder to the argument.

[Visual Basic]
Public Function AddField( _
ByVal fieldBuilder As FieldBuilder _
) As FieldArgumentBuilder
[C#]
public FieldArgumentBuilder AddField(
FieldBuilder fieldBuilder
);

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldArgumentBuilder Class | Aspose.Words.Fields Namespace


FieldArgumentBuilder.AddNode Method

Adds a node to the argument.

[Visual Basic]
Public Function AddNode( _
ByVal node As Inline _
) As FieldArgumentBuilder
[C#]
public FieldArgumentBuilder AddNode(
Inline node
);

Remarks

Only text level nodes are supported at the moment.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldArgumentBuilder Class | Aspose.Words.Fields Namespace


FieldArgumentBuilder.AddText Method

Adds a plain text to the argument.

[Visual Basic]
Public Function AddText( _
ByVal text As String _
) As FieldArgumentBuilder
[C#]
public FieldArgumentBuilder AddText(
string text
);

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldArgumentBuilder Class | Aspose.Words.Fields Namespace


FieldAsk Class

Implements the ASK field.

For a list of all members of this type, see FieldAsk Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAsk

[Visual Basic]
Public Class FieldAsk
Inherits Field
[C#]
public class FieldAsk : Field

Remarks

Prompts the user to enter information and assigns a bookmark to represent the user's response.

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAsk Members | Aspose.Words.Fields Namespace


FieldAsk Members

FieldAsk overview

Public Instance Constructors

FieldAsk Constructor Initializes a new instance of the FieldAsk class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
DefaultResponse | Gets or sets default user response (initial value contained in the prompt window).
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PromptOnceOnMailMerge | Gets or sets whether the user response should be recieved once per a mail merge operation.
PromptText | Gets or sets the prompt text (the title of the prompt window).
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


FieldAsk Constructor

Initializes a new instance of the FieldAsk class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAsk();

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


FieldAsk Properties

The properties of the FieldAsk class are listed below. For a complete list of FieldAsk class members, see the FieldAsk Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
DefaultResponse | Gets or sets default user response (initial value contained in the prompt window).
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PromptOnceOnMailMerge | Gets or sets whether the user response should be recieved once per a mail merge operation.
PromptText | Gets or sets the prompt text (the title of the prompt window).
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldAsk.BookmarkName Property

Gets or sets the name of the bookmark.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


DefaultResponse Property

Aspose.Words

FieldAsk.DefaultResponse Property

Gets or sets default user response (initial value contained in the prompt window).

[Visual Basic]
Public Property DefaultResponse As String
[C#]
public string DefaultResponse {get; set;}

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


PromptOnceOnMailMerge Property

Aspose.Words

FieldAsk.PromptOnceOnMailMerge Property

Gets or sets whether the user response should be recieved once per a mail merge operation.

[Visual Basic]
Public Property PromptOnceOnMailMerge As Boolean
[C#]
public bool PromptOnceOnMailMerge {get; set;}

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


PromptText Property

Aspose.Words

FieldAsk.PromptText Property

Gets or sets the prompt text (the title of the prompt window).

[Visual Basic]
Public Property PromptText As String
[C#]
public string PromptText {get; set;}

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

See Also

FieldAsk Class | Aspose.Words.Fields Namespace


FieldAuthor Class

Implements the AUTHOR field.

For a list of all members of this type, see FieldAuthor Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAuthor

[Visual Basic]
Public Class FieldAuthor
Inherits Field
[C#]
public class FieldAuthor : Field

Remarks

Retrieves, and optionally sets, the document author's name, as recorded in the Author property of the built-in document properties.

Example

Shows how to display a document creator's name with an AUTHOR field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// If we open an existing document, the document's author's full name will be displayed by the field
// If we create a document programmatically, we need to set this attribute to the author's name so our field has something to display
doc.FieldOptions.DefaultDocumentAuthor = "Joe Bloggs";

builder.Write("This document was created by ");
FieldAuthor field = (FieldAuthor)builder.InsertField(FieldType.FieldAuthor, true);
field.Update();

Assert.AreEqual(" AUTHOR ", field.GetFieldCode());
Assert.AreEqual("Joe Bloggs", field.Result);

// If this property has a value, it will supersede the one we set above
doc.BuiltInDocumentProperties.Author = "John Doe";
field.Update();

Assert.AreEqual(" AUTHOR ", field.GetFieldCode());
Assert.AreEqual("John Doe", field.Result);

// Our field can also override the document's built in author name like this
field.AuthorName = "Jane Doe";
field.Update();

Assert.AreEqual(" AUTHOR  \"Jane Doe\"", field.GetFieldCode());
Assert.AreEqual("Jane Doe", field.Result);

// The author name in the built in properties was changed by the field, but the default document author stays the same
Assert.AreEqual("Jane Doe", doc.BuiltInDocumentProperties.Author);
Assert.AreEqual("Joe Bloggs", doc.FieldOptions.DefaultDocumentAuthor);

doc.Save(ArtifactsDir + "Field.AUTHOR.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAuthor Members | Aspose.Words.Fields Namespace


FieldAuthor Members

FieldAuthor overview

Public Instance Constructors

FieldAuthor Constructor Initializes a new instance of the FieldAuthor class.

Public Instance Properties

AuthorName | Gets or sets the document author's name.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAuthor Class | Aspose.Words.Fields Namespace


FieldAuthor Constructor

Initializes a new instance of the FieldAuthor class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAuthor();

See Also

FieldAuthor Class | Aspose.Words.Fields Namespace


FieldAuthor Properties

The properties of the FieldAuthor class are listed below. For a complete list of FieldAuthor class members, see the FieldAuthor Members topic.

Public Instance Properties

AuthorName | Gets or sets the document author's name.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAuthor Class | Aspose.Words.Fields Namespace


AuthorName Property

Aspose.Words

FieldAuthor.AuthorName Property

Gets or sets the document author's name.

[Visual Basic]
Public Property AuthorName As String
[C#]
public string AuthorName {get; set;}

Example

Shows how to display a document creator's name with an AUTHOR field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// If we open an existing document, the document's author's full name will be displayed by the field
// If we create a document programmatically, we need to set this attribute to the author's name so our field has something to display
doc.FieldOptions.DefaultDocumentAuthor = "Joe Bloggs";

builder.Write("This document was created by ");
FieldAuthor field = (FieldAuthor)builder.InsertField(FieldType.FieldAuthor, true);
field.Update();

Assert.AreEqual(" AUTHOR ", field.GetFieldCode());
Assert.AreEqual("Joe Bloggs", field.Result);

// If this property has a value, it will supersede the one we set above
doc.BuiltInDocumentProperties.Author = "John Doe";
field.Update();

Assert.AreEqual(" AUTHOR ", field.GetFieldCode());
Assert.AreEqual("John Doe", field.Result);

// Our field can also override the document's built in author name like this
field.AuthorName = "Jane Doe";
field.Update();

Assert.AreEqual(" AUTHOR  \"Jane Doe\"", field.GetFieldCode());
Assert.AreEqual("Jane Doe", field.Result);

// The author name in the built in properties was changed by the field, but the default document author stays the same
Assert.AreEqual("Jane Doe", doc.BuiltInDocumentProperties.Author);
Assert.AreEqual("Joe Bloggs", doc.FieldOptions.DefaultDocumentAuthor);

doc.Save(ArtifactsDir + "Field.AUTHOR.docx");

See Also

FieldAuthor Class | Aspose.Words.Fields Namespace


FieldAutoNum Class

Implements the AUTONUM field.

For a list of all members of this type, see FieldAutoNum Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAutoNum

[Visual Basic]
Public Class FieldAutoNum
Inherits Field
[C#]
public class FieldAutoNum : Field

Remarks

Inserts an automatic number.

Example

Shows how to number paragraphs using autonum fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The two fields we insert here will be automatically numbered 1 and 2
builder.InsertField(FieldType.FieldAutoNum, true);
builder.Writeln("\tParagraph 1.");
builder.InsertField(FieldType.FieldAutoNum, true);
builder.Writeln("\tParagraph 2.");

foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldAutoNum)
    {
        // Leaving the FieldAutoNum.SeparatorCharacter field null will set the separator character to '.' by default
        Assert.IsNull(((FieldAutoNum)field).SeparatorCharacter);

        // The first character of the string entered here will be used as the separator character
        ((FieldAutoNum)field).SeparatorCharacter = ":";

        Assert.AreEqual(" AUTONUM  \\s :", field.GetFieldCode());
    }
}

doc.Save(ArtifactsDir + "Field.AutoNum.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAutoNum Members | Aspose.Words.Fields Namespace


FieldAutoNum Members

FieldAutoNum overview

Public Instance Constructors

FieldAutoNum Constructor Initializes a new instance of the FieldAutoNum class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SeparatorCharacter | Gets or sets the separator character to be used.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAutoNum Class | Aspose.Words.Fields Namespace


FieldAutoNum Constructor

Initializes a new instance of the FieldAutoNum class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAutoNum();

See Also

FieldAutoNum Class | Aspose.Words.Fields Namespace


FieldAutoNum Properties

The properties of the FieldAutoNum class are listed below. For a complete list of FieldAutoNum class members, see the FieldAutoNum Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SeparatorCharacter | Gets or sets the separator character to be used.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAutoNum Class | Aspose.Words.Fields Namespace


SeparatorCharacter Property

Aspose.Words

FieldAutoNum.SeparatorCharacter Property

Gets or sets the separator character to be used.

[Visual Basic]
Public Property SeparatorCharacter As String
[C#]
public string SeparatorCharacter {get; set;}

Example

Shows how to number paragraphs using autonum fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The two fields we insert here will be automatically numbered 1 and 2
builder.InsertField(FieldType.FieldAutoNum, true);
builder.Writeln("\tParagraph 1.");
builder.InsertField(FieldType.FieldAutoNum, true);
builder.Writeln("\tParagraph 2.");

foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldAutoNum)
    {
        // Leaving the FieldAutoNum.SeparatorCharacter field null will set the separator character to '.' by default
        Assert.IsNull(((FieldAutoNum)field).SeparatorCharacter);

        // The first character of the string entered here will be used as the separator character
        ((FieldAutoNum)field).SeparatorCharacter = ":";

        Assert.AreEqual(" AUTONUM  \\s :", field.GetFieldCode());
    }
}

doc.Save(ArtifactsDir + "Field.AutoNum.docx");

See Also

FieldAutoNum Class | Aspose.Words.Fields Namespace


FieldAutoNumLgl Class

Implements the AUTONUMLGL field.

For a list of all members of this type, see FieldAutoNumLgl Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAutoNumLgl

[Visual Basic]
Public Class FieldAutoNumLgl
Inherits Field
[C#]
public class FieldAutoNumLgl : Field

Remarks

Inserts an automatic number in legal format.

Example

Shows how to organize a document using autonum legal fields

[C#]

public void FieldAutoNumLgl()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This string will be our paragraph text that
    string loremIpsum =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
        "\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ";

    // In this case our autonum legal field will number our first paragraph as "1."
    InsertNumberedClause(builder, "\tHeading 1", loremIpsum, StyleIdentifier.Heading1);

    // Our heading style number will be 1 again, so this field will keep counting headings at a heading level of 1
    InsertNumberedClause(builder, "\tHeading 2", loremIpsum, StyleIdentifier.Heading1);

    // Our heading style is 2, setting the paragraph numbering depth to 2, setting this field's value to "2.1."
    InsertNumberedClause(builder, "\tHeading 3", loremIpsum, StyleIdentifier.Heading2);

    // Our heading style is 3, so we are going deeper again to "2.1.1."
    InsertNumberedClause(builder, "\tHeading 4", loremIpsum, StyleIdentifier.Heading3);

    // Our heading style is 2, and the next field number at that level is "2.2."
    InsertNumberedClause(builder, "\tHeading 5", loremIpsum, StyleIdentifier.Heading2);

    foreach (Field field in doc.Range.Fields)
    {
        if (field.Type == FieldType.FieldAutoNumLegal)
        {
            // By default the separator will appear as "." in the document but here it is null
            Assert.IsNull(((FieldAutoNumLgl)field).SeparatorCharacter);

            // Change the separator character and remove trailing separators
            ((FieldAutoNumLgl)field).SeparatorCharacter = ":";
            ((FieldAutoNumLgl)field).RemoveTrailingPeriod = true;
            Assert.AreEqual(" AUTONUMLGL  \\s : \\e", field.GetFieldCode());
        }
    }

    doc.Save(ArtifactsDir + "Field.AutoNumLegal.docx");
}

/// <summary>
/// Get a document builder to insert a clause numbered by an autonum legal field
/// </summary>
private void InsertNumberedClause(DocumentBuilder builder, string heading, string contents, StyleIdentifier headingStyle)
{
    // This legal field will automatically number our clauses, taking heading style level into account
    builder.InsertField(FieldType.FieldAutoNumLegal, true);
    builder.CurrentParagraph.ParagraphFormat.StyleIdentifier = headingStyle;
    builder.Writeln(heading);

    // This text will belong to the auto num legal field above it
    // It will collapse when the arrow next to the corresponding autonum legal field is clicked in MS Word
    builder.CurrentParagraph.ParagraphFormat.StyleIdentifier = StyleIdentifier.BodyText;
    builder.Writeln(contents);
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAutoNumLgl Members | Aspose.Words.Fields Namespace


FieldAutoNumLgl Members

FieldAutoNumLgl overview

Public Instance Constructors

FieldAutoNumLgl Constructor Initializes a new instance of the FieldAutoNumLgl class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
RemoveTrailingPeriod | Gets or sets whether to display the number without a trailing period.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SeparatorCharacter | Gets or sets the separator character to be used.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAutoNumLgl Class | Aspose.Words.Fields Namespace


FieldAutoNumLgl Constructor

Initializes a new instance of the FieldAutoNumLgl class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAutoNumLgl();

See Also

FieldAutoNumLgl Class | Aspose.Words.Fields Namespace


FieldAutoNumLgl Properties

The properties of the FieldAutoNumLgl class are listed below. For a complete list of FieldAutoNumLgl class members, see the FieldAutoNumLgl Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
RemoveTrailingPeriod | Gets or sets whether to display the number without a trailing period.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SeparatorCharacter | Gets or sets the separator character to be used.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAutoNumLgl Class | Aspose.Words.Fields Namespace


RemoveTrailingPeriod Property

Aspose.Words

FieldAutoNumLgl.RemoveTrailingPeriod Property

Gets or sets whether to display the number without a trailing period.

[Visual Basic]
Public Property RemoveTrailingPeriod As Boolean
[C#]
public bool RemoveTrailingPeriod {get; set;}

Example

Shows how to organize a document using autonum legal fields

[C#]

public void FieldAutoNumLgl()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This string will be our paragraph text that
    string loremIpsum =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
        "\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ";

    // In this case our autonum legal field will number our first paragraph as "1."
    InsertNumberedClause(builder, "\tHeading 1", loremIpsum, StyleIdentifier.Heading1);

    // Our heading style number will be 1 again, so this field will keep counting headings at a heading level of 1
    InsertNumberedClause(builder, "\tHeading 2", loremIpsum, StyleIdentifier.Heading1);

    // Our heading style is 2, setting the paragraph numbering depth to 2, setting this field's value to "2.1."
    InsertNumberedClause(builder, "\tHeading 3", loremIpsum, StyleIdentifier.Heading2);

    // Our heading style is 3, so we are going deeper again to "2.1.1."
    InsertNumberedClause(builder, "\tHeading 4", loremIpsum, StyleIdentifier.Heading3);

    // Our heading style is 2, and the next field number at that level is "2.2."
    InsertNumberedClause(builder, "\tHeading 5", loremIpsum, StyleIdentifier.Heading2);

    foreach (Field field in doc.Range.Fields)
    {
        if (field.Type == FieldType.FieldAutoNumLegal)
        {
            // By default the separator will appear as "." in the document but here it is null
            Assert.IsNull(((FieldAutoNumLgl)field).SeparatorCharacter);

            // Change the separator character and remove trailing separators
            ((FieldAutoNumLgl)field).SeparatorCharacter = ":";
            ((FieldAutoNumLgl)field).RemoveTrailingPeriod = true;
            Assert.AreEqual(" AUTONUMLGL  \\s : \\e", field.GetFieldCode());
        }
    }

    doc.Save(ArtifactsDir + "Field.AutoNumLegal.docx");
}

/// <summary>
/// Get a document builder to insert a clause numbered by an autonum legal field
/// </summary>
private void InsertNumberedClause(DocumentBuilder builder, string heading, string contents, StyleIdentifier headingStyle)
{
    // This legal field will automatically number our clauses, taking heading style level into account
    builder.InsertField(FieldType.FieldAutoNumLegal, true);
    builder.CurrentParagraph.ParagraphFormat.StyleIdentifier = headingStyle;
    builder.Writeln(heading);

    // This text will belong to the auto num legal field above it
    // It will collapse when the arrow next to the corresponding autonum legal field is clicked in MS Word
    builder.CurrentParagraph.ParagraphFormat.StyleIdentifier = StyleIdentifier.BodyText;
    builder.Writeln(contents);
}

See Also

FieldAutoNumLgl Class | Aspose.Words.Fields Namespace


SeparatorCharacter Property

Aspose.Words

FieldAutoNumLgl.SeparatorCharacter Property

Gets or sets the separator character to be used.

[Visual Basic]
Public Property SeparatorCharacter As String
[C#]
public string SeparatorCharacter {get; set;}

Example

Shows how to organize a document using autonum legal fields

[C#]

public void FieldAutoNumLgl()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This string will be our paragraph text that
    string loremIpsum =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
        "\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ";

    // In this case our autonum legal field will number our first paragraph as "1."
    InsertNumberedClause(builder, "\tHeading 1", loremIpsum, StyleIdentifier.Heading1);

    // Our heading style number will be 1 again, so this field will keep counting headings at a heading level of 1
    InsertNumberedClause(builder, "\tHeading 2", loremIpsum, StyleIdentifier.Heading1);

    // Our heading style is 2, setting the paragraph numbering depth to 2, setting this field's value to "2.1."
    InsertNumberedClause(builder, "\tHeading 3", loremIpsum, StyleIdentifier.Heading2);

    // Our heading style is 3, so we are going deeper again to "2.1.1."
    InsertNumberedClause(builder, "\tHeading 4", loremIpsum, StyleIdentifier.Heading3);

    // Our heading style is 2, and the next field number at that level is "2.2."
    InsertNumberedClause(builder, "\tHeading 5", loremIpsum, StyleIdentifier.Heading2);

    foreach (Field field in doc.Range.Fields)
    {
        if (field.Type == FieldType.FieldAutoNumLegal)
        {
            // By default the separator will appear as "." in the document but here it is null
            Assert.IsNull(((FieldAutoNumLgl)field).SeparatorCharacter);

            // Change the separator character and remove trailing separators
            ((FieldAutoNumLgl)field).SeparatorCharacter = ":";
            ((FieldAutoNumLgl)field).RemoveTrailingPeriod = true;
            Assert.AreEqual(" AUTONUMLGL  \\s : \\e", field.GetFieldCode());
        }
    }

    doc.Save(ArtifactsDir + "Field.AutoNumLegal.docx");
}

/// <summary>
/// Get a document builder to insert a clause numbered by an autonum legal field
/// </summary>
private void InsertNumberedClause(DocumentBuilder builder, string heading, string contents, StyleIdentifier headingStyle)
{
    // This legal field will automatically number our clauses, taking heading style level into account
    builder.InsertField(FieldType.FieldAutoNumLegal, true);
    builder.CurrentParagraph.ParagraphFormat.StyleIdentifier = headingStyle;
    builder.Writeln(heading);

    // This text will belong to the auto num legal field above it
    // It will collapse when the arrow next to the corresponding autonum legal field is clicked in MS Word
    builder.CurrentParagraph.ParagraphFormat.StyleIdentifier = StyleIdentifier.BodyText;
    builder.Writeln(contents);
}

See Also

FieldAutoNumLgl Class | Aspose.Words.Fields Namespace


FieldAutoNumOut Class

Implements the AUTONUMOUT field.

For a list of all members of this type, see FieldAutoNumOut Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAutoNumOut

[Visual Basic]
Public Class FieldAutoNumOut
Inherits Field
[C#]
public class FieldAutoNumOut : Field

Remarks

Inserts an automatic number in outline format.

Example

Shows how to number paragraphs using autonum outline fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// The two fields that we insert here will be numbered 1 and 2
builder.InsertField(FieldType.FieldAutoNumOutline, true);
builder.Writeln("\tParagraph 1.");
builder.InsertField(FieldType.FieldAutoNumOutline, true);
builder.Writeln("\tParagraph 2.");

foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldAutoNumOutline)
    {
        Assert.AreEqual(" AUTONUMOUT ", field.GetFieldCode());
    }
}

doc.Save(ArtifactsDir + "Field.AutoNumOut.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAutoNumOut Members | Aspose.Words.Fields Namespace


FieldAutoNumOut Members

FieldAutoNumOut overview

Public Instance Constructors

FieldAutoNumOut Constructor Initializes a new instance of the FieldAutoNumOut class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAutoNumOut Class | Aspose.Words.Fields Namespace


FieldAutoNumOut Constructor

Initializes a new instance of the FieldAutoNumOut class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAutoNumOut();

See Also

FieldAutoNumOut Class | Aspose.Words.Fields Namespace


FieldAutoText Class

Implements the AUTOTEXT field.

For a list of all members of this type, see FieldAutoText Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAutoText

[Visual Basic]
Public Class FieldAutoText
Inherits Field
[C#]
public class FieldAutoText : Field

Remarks

Inserts an AutoText entry.

Example

Shows how to insert a building block into a document and display it with AUTOTEXT and GLOSSARY fields.

[C#]

Document doc = new Document();

// Create a glossary document and add an AutoText building block
doc.GlossaryDocument = new GlossaryDocument();
BuildingBlock buildingBlock = new BuildingBlock(doc.GlossaryDocument);
buildingBlock.Name = "MyBlock";
buildingBlock.Gallery = BuildingBlockGallery.AutoText;
buildingBlock.Category = "General";
buildingBlock.Description = "MyBlock description";
buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;
doc.GlossaryDocument.AppendChild(buildingBlock);

// Create a source and add it as text content to our building block
Document buildingBlockSource = new Document();
DocumentBuilder buildingBlockSourceBuilder = new DocumentBuilder(buildingBlockSource);
buildingBlockSourceBuilder.Writeln("Hello World!");

Node buildingBlockContent = doc.GlossaryDocument.ImportNode(buildingBlockSource.FirstSection, true);
buildingBlock.AppendChild(buildingBlockContent);

// Create an advance field using document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldAutoText fieldAutoText = (FieldAutoText)builder.InsertField(FieldType.FieldAutoText, true);

// Refer to our building block by name
fieldAutoText.EntryName = "MyBlock";

Assert.AreEqual(" AUTOTEXT  MyBlock", fieldAutoText.GetFieldCode());

// Put additional templates here
doc.FieldOptions.BuiltInTemplatesPaths = new[] { MyDir + "Document.BusinessBrochureTemplate.dotx" };

// We can also display our building block with a GLOSSARY field
FieldGlossary fieldGlossary = (FieldGlossary)builder.InsertField(FieldType.FieldGlossary, true);
fieldGlossary.EntryName = "MyBlock";

Assert.AreEqual(" GLOSSARY  MyBlock", fieldGlossary.GetFieldCode());

// The text content of our building block will be visible in the output
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.AutoText.dotx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAutoText Members | Aspose.Words.Fields Namespace


FieldAutoText Members

FieldAutoText overview

Public Instance Constructors

FieldAutoText Constructor Initializes a new instance of the FieldAutoText class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryName | Gets or sets the name of the AutoText entry.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAutoText Class | Aspose.Words.Fields Namespace


FieldAutoText Constructor

Initializes a new instance of the FieldAutoText class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAutoText();

See Also

FieldAutoText Class | Aspose.Words.Fields Namespace


FieldAutoText Properties

The properties of the FieldAutoText class are listed below. For a complete list of FieldAutoText class members, see the FieldAutoText Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryName | Gets or sets the name of the AutoText entry.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAutoText Class | Aspose.Words.Fields Namespace


EntryName Property

Aspose.Words

FieldAutoText.EntryName Property

Gets or sets the name of the AutoText entry.

[Visual Basic]
Public Property EntryName As String
[C#]
public string EntryName {get; set;}

Example

Shows how to insert a building block into a document and display it with AUTOTEXT and GLOSSARY fields.

[C#]

Document doc = new Document();

// Create a glossary document and add an AutoText building block
doc.GlossaryDocument = new GlossaryDocument();
BuildingBlock buildingBlock = new BuildingBlock(doc.GlossaryDocument);
buildingBlock.Name = "MyBlock";
buildingBlock.Gallery = BuildingBlockGallery.AutoText;
buildingBlock.Category = "General";
buildingBlock.Description = "MyBlock description";
buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;
doc.GlossaryDocument.AppendChild(buildingBlock);

// Create a source and add it as text content to our building block
Document buildingBlockSource = new Document();
DocumentBuilder buildingBlockSourceBuilder = new DocumentBuilder(buildingBlockSource);
buildingBlockSourceBuilder.Writeln("Hello World!");

Node buildingBlockContent = doc.GlossaryDocument.ImportNode(buildingBlockSource.FirstSection, true);
buildingBlock.AppendChild(buildingBlockContent);

// Create an advance field using document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldAutoText fieldAutoText = (FieldAutoText)builder.InsertField(FieldType.FieldAutoText, true);

// Refer to our building block by name
fieldAutoText.EntryName = "MyBlock";

Assert.AreEqual(" AUTOTEXT  MyBlock", fieldAutoText.GetFieldCode());

// Put additional templates here
doc.FieldOptions.BuiltInTemplatesPaths = new[] { MyDir + "Document.BusinessBrochureTemplate.dotx" };

// We can also display our building block with a GLOSSARY field
FieldGlossary fieldGlossary = (FieldGlossary)builder.InsertField(FieldType.FieldGlossary, true);
fieldGlossary.EntryName = "MyBlock";

Assert.AreEqual(" GLOSSARY  MyBlock", fieldGlossary.GetFieldCode());

// The text content of our building block will be visible in the output
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.AutoText.dotx");

See Also

FieldAutoText Class | Aspose.Words.Fields Namespace


FieldAutoTextList Class

Implements the AUTOTEXTLIST field.

For a list of all members of this type, see FieldAutoTextList Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAutoTextList

[Visual Basic]
Public Class FieldAutoTextList
Inherits Field
[C#]
public class FieldAutoTextList : Field

Remarks

Creates a shortcut menu based on AutoText entries in the active template.

Example

Shows how to use an AutoTextList field to select from a list of AutoText entries.

[C#]

public void FieldAutoTextList()
{
    Document doc = new Document();

    // Create a glossary document and populate it with auto text entries that our auto text list will let us select from
    doc.GlossaryDocument = new GlossaryDocument();
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 1", "Contents of AutoText 1");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 2", "Contents of AutoText 2");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 3", "Contents of AutoText 3");

    // Insert an auto text list using a document builder and change its properties
    DocumentBuilder builder = new DocumentBuilder(doc);
    FieldAutoTextList field = (FieldAutoTextList)builder.InsertField(FieldType.FieldAutoTextList, true);
    field.EntryName = "Right click here to pick an AutoText block"; // This is the text that will be visible in the document
    field.ListStyle = "Heading 1";
    field.ScreenTip = "Hover tip text for AutoTextList goes here";

    Assert.AreEqual(" AUTOTEXTLIST  \"Right click here to pick an AutoText block\" " +
                    "\\s \"Heading 1\" " +
                    "\\t \"Hover tip text for AutoTextList goes here\"", field.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.AutoTextList.dotx");
}

/// <summary>
/// Create an AutoText entry and add it to a glossary document
/// </summary>
private static void AppendAutoTextEntry(GlossaryDocument glossaryDoc, string name, string contents)
{
    // Create building block and set it up as an auto text entry
    BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc);
    buildingBlock.Name = name;
    buildingBlock.Gallery = BuildingBlockGallery.AutoText;
    buildingBlock.Category = "General";
    buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;

    // Add content to the building block
    Section section = new Section(glossaryDoc);
    section.AppendChild(new Body(glossaryDoc));
    section.Body.AppendParagraph(contents);
    buildingBlock.AppendChild(section);

    // Add auto text entry to glossary document
    glossaryDoc.AppendChild(buildingBlock);
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldAutoTextList Members | Aspose.Words.Fields Namespace


FieldAutoTextList Members

FieldAutoTextList overview

Public Instance Constructors

FieldAutoTextList Constructor Initializes a new instance of the FieldAutoTextList class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryName | Gets or sets the name of the AutoText entry.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
ListStyle | Gets or sets the name of the style on which the list to contain entries is based.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScreenTip | Gets or sets the text of the ScreenTip to show.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldAutoTextList Class | Aspose.Words.Fields Namespace


FieldAutoTextList Constructor

Initializes a new instance of the FieldAutoTextList class.

[Visual Basic]
Public Sub New()
[C#]
public FieldAutoTextList();

See Also

FieldAutoTextList Class | Aspose.Words.Fields Namespace


FieldAutoTextList Properties

The properties of the FieldAutoTextList class are listed below. For a complete list of FieldAutoTextList class members, see the FieldAutoTextList Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryName | Gets or sets the name of the AutoText entry.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
ListStyle | Gets or sets the name of the style on which the list to contain entries is based.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScreenTip | Gets or sets the text of the ScreenTip to show.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldAutoTextList Class | Aspose.Words.Fields Namespace


EntryName Property

Aspose.Words

FieldAutoTextList.EntryName Property

Gets or sets the name of the AutoText entry.

[Visual Basic]
Public Property EntryName As String
[C#]
public string EntryName {get; set;}

Example

Shows how to use an AutoTextList field to select from a list of AutoText entries.

[C#]

public void FieldAutoTextList()
{
    Document doc = new Document();

    // Create a glossary document and populate it with auto text entries that our auto text list will let us select from
    doc.GlossaryDocument = new GlossaryDocument();
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 1", "Contents of AutoText 1");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 2", "Contents of AutoText 2");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 3", "Contents of AutoText 3");

    // Insert an auto text list using a document builder and change its properties
    DocumentBuilder builder = new DocumentBuilder(doc);
    FieldAutoTextList field = (FieldAutoTextList)builder.InsertField(FieldType.FieldAutoTextList, true);
    field.EntryName = "Right click here to pick an AutoText block"; // This is the text that will be visible in the document
    field.ListStyle = "Heading 1";
    field.ScreenTip = "Hover tip text for AutoTextList goes here";

    Assert.AreEqual(" AUTOTEXTLIST  \"Right click here to pick an AutoText block\" " +
                    "\\s \"Heading 1\" " +
                    "\\t \"Hover tip text for AutoTextList goes here\"", field.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.AutoTextList.dotx");
}

/// <summary>
/// Create an AutoText entry and add it to a glossary document
/// </summary>
private static void AppendAutoTextEntry(GlossaryDocument glossaryDoc, string name, string contents)
{
    // Create building block and set it up as an auto text entry
    BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc);
    buildingBlock.Name = name;
    buildingBlock.Gallery = BuildingBlockGallery.AutoText;
    buildingBlock.Category = "General";
    buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;

    // Add content to the building block
    Section section = new Section(glossaryDoc);
    section.AppendChild(new Body(glossaryDoc));
    section.Body.AppendParagraph(contents);
    buildingBlock.AppendChild(section);

    // Add auto text entry to glossary document
    glossaryDoc.AppendChild(buildingBlock);
}

See Also

FieldAutoTextList Class | Aspose.Words.Fields Namespace


ListStyle Property

Aspose.Words

FieldAutoTextList.ListStyle Property

Gets or sets the name of the style on which the list to contain entries is based.

[Visual Basic]
Public Property ListStyle As String
[C#]
public string ListStyle {get; set;}

Example

Shows how to use an AutoTextList field to select from a list of AutoText entries.

[C#]

public void FieldAutoTextList()
{
    Document doc = new Document();

    // Create a glossary document and populate it with auto text entries that our auto text list will let us select from
    doc.GlossaryDocument = new GlossaryDocument();
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 1", "Contents of AutoText 1");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 2", "Contents of AutoText 2");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 3", "Contents of AutoText 3");

    // Insert an auto text list using a document builder and change its properties
    DocumentBuilder builder = new DocumentBuilder(doc);
    FieldAutoTextList field = (FieldAutoTextList)builder.InsertField(FieldType.FieldAutoTextList, true);
    field.EntryName = "Right click here to pick an AutoText block"; // This is the text that will be visible in the document
    field.ListStyle = "Heading 1";
    field.ScreenTip = "Hover tip text for AutoTextList goes here";

    Assert.AreEqual(" AUTOTEXTLIST  \"Right click here to pick an AutoText block\" " +
                    "\\s \"Heading 1\" " +
                    "\\t \"Hover tip text for AutoTextList goes here\"", field.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.AutoTextList.dotx");
}

/// <summary>
/// Create an AutoText entry and add it to a glossary document
/// </summary>
private static void AppendAutoTextEntry(GlossaryDocument glossaryDoc, string name, string contents)
{
    // Create building block and set it up as an auto text entry
    BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc);
    buildingBlock.Name = name;
    buildingBlock.Gallery = BuildingBlockGallery.AutoText;
    buildingBlock.Category = "General";
    buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;

    // Add content to the building block
    Section section = new Section(glossaryDoc);
    section.AppendChild(new Body(glossaryDoc));
    section.Body.AppendParagraph(contents);
    buildingBlock.AppendChild(section);

    // Add auto text entry to glossary document
    glossaryDoc.AppendChild(buildingBlock);
}

See Also

FieldAutoTextList Class | Aspose.Words.Fields Namespace


ScreenTip Property

Aspose.Words

FieldAutoTextList.ScreenTip Property

Gets or sets the text of the ScreenTip to show.

[Visual Basic]
Public Property ScreenTip As String
[C#]
public string ScreenTip {get; set;}

Example

Shows how to use an AutoTextList field to select from a list of AutoText entries.

[C#]

public void FieldAutoTextList()
{
    Document doc = new Document();

    // Create a glossary document and populate it with auto text entries that our auto text list will let us select from
    doc.GlossaryDocument = new GlossaryDocument();
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 1", "Contents of AutoText 1");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 2", "Contents of AutoText 2");
    AppendAutoTextEntry(doc.GlossaryDocument, "AutoText 3", "Contents of AutoText 3");

    // Insert an auto text list using a document builder and change its properties
    DocumentBuilder builder = new DocumentBuilder(doc);
    FieldAutoTextList field = (FieldAutoTextList)builder.InsertField(FieldType.FieldAutoTextList, true);
    field.EntryName = "Right click here to pick an AutoText block"; // This is the text that will be visible in the document
    field.ListStyle = "Heading 1";
    field.ScreenTip = "Hover tip text for AutoTextList goes here";

    Assert.AreEqual(" AUTOTEXTLIST  \"Right click here to pick an AutoText block\" " +
                    "\\s \"Heading 1\" " +
                    "\\t \"Hover tip text for AutoTextList goes here\"", field.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.AutoTextList.dotx");
}

/// <summary>
/// Create an AutoText entry and add it to a glossary document
/// </summary>
private static void AppendAutoTextEntry(GlossaryDocument glossaryDoc, string name, string contents)
{
    // Create building block and set it up as an auto text entry
    BuildingBlock buildingBlock = new BuildingBlock(glossaryDoc);
    buildingBlock.Name = name;
    buildingBlock.Gallery = BuildingBlockGallery.AutoText;
    buildingBlock.Category = "General";
    buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;

    // Add content to the building block
    Section section = new Section(glossaryDoc);
    section.AppendChild(new Body(glossaryDoc));
    section.Body.AppendParagraph(contents);
    buildingBlock.AppendChild(section);

    // Add auto text entry to glossary document
    glossaryDoc.AppendChild(buildingBlock);
}

See Also

FieldAutoTextList Class | Aspose.Words.Fields Namespace


FieldBarcode Class

Implements the BARCODE field.

For a list of all members of this type, see FieldBarcode Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldBarcode

[Visual Basic]
Public Class FieldBarcode
Inherits Field
[C#]
public class FieldBarcode : Field

Remarks

Inserts a postal barcode in a machine-readable form of address used by the U.S. Postal Service.

Example

Shows how to insert a BARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bookmark with a US postal code in it
builder.StartBookmark("BarcodeBookmark");
builder.Writeln("96801");
builder.EndBookmark("BarcodeBookmark");

builder.Writeln();

// Reference a US postal code directly
FieldBarcode fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.FacingIdentificationMark = "C";
fieldBarcode.PostalAddress = "96801";
fieldBarcode.IsUSPostalAddress = true;

builder.Writeln();

// Reference a US postal code from a bookmark
fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.PostalAddress = "BarcodeBookmark";
fieldBarcode.IsBookmark = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.USAddressBarcode.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldBarcode Members | Aspose.Words.Fields Namespace


FieldBarcode Members

FieldBarcode overview

Public Instance Constructors

FieldBarcode Constructor Initializes a new instance of the FieldBarcode class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FacingIdentificationMark | Gets or sets the type of a Facing Identification Mark (FIM) to insert.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsBookmark | Gets or sets whether PostalAddress is the name of a bookmark.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsUSPostalAddress | Gets or sets whether PostalAddress is a U.S. postal address.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PostalAddress | Gets or sets the postal address used for generating a barcode or the name of the bookmark that refers to it.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


FieldBarcode Constructor

Initializes a new instance of the FieldBarcode class.

[Visual Basic]
Public Sub New()
[C#]
public FieldBarcode();

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


FieldBarcode Properties

The properties of the FieldBarcode class are listed below. For a complete list of FieldBarcode class members, see the FieldBarcode Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FacingIdentificationMark | Gets or sets the type of a Facing Identification Mark (FIM) to insert.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsBookmark | Gets or sets whether PostalAddress is the name of a bookmark.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsUSPostalAddress | Gets or sets whether PostalAddress is a U.S. postal address.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PostalAddress | Gets or sets the postal address used for generating a barcode or the name of the bookmark that refers to it.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


FacingIdentificationMark Property

Aspose.Words

FieldBarcode.FacingIdentificationMark Property

Gets or sets the type of a Facing Identification Mark (FIM) to insert.

[Visual Basic]
Public Property FacingIdentificationMark As String
[C#]
public string FacingIdentificationMark {get; set;}

Example

Shows how to insert a BARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bookmark with a US postal code in it
builder.StartBookmark("BarcodeBookmark");
builder.Writeln("96801");
builder.EndBookmark("BarcodeBookmark");

builder.Writeln();

// Reference a US postal code directly
FieldBarcode fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.FacingIdentificationMark = "C";
fieldBarcode.PostalAddress = "96801";
fieldBarcode.IsUSPostalAddress = true;

builder.Writeln();

// Reference a US postal code from a bookmark
fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.PostalAddress = "BarcodeBookmark";
fieldBarcode.IsBookmark = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.USAddressBarcode.docx");

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


IsBookmark Property

Aspose.Words

FieldBarcode.IsBookmark Property

Gets or sets whether PostalAddress is the name of a bookmark.

[Visual Basic]
Public Property IsBookmark As Boolean
[C#]
public bool IsBookmark {get; set;}

Example

Shows how to insert a BARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bookmark with a US postal code in it
builder.StartBookmark("BarcodeBookmark");
builder.Writeln("96801");
builder.EndBookmark("BarcodeBookmark");

builder.Writeln();

// Reference a US postal code directly
FieldBarcode fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.FacingIdentificationMark = "C";
fieldBarcode.PostalAddress = "96801";
fieldBarcode.IsUSPostalAddress = true;

builder.Writeln();

// Reference a US postal code from a bookmark
fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.PostalAddress = "BarcodeBookmark";
fieldBarcode.IsBookmark = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.USAddressBarcode.docx");

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


IsUSPostalAddress Property

Aspose.Words

FieldBarcode.IsUSPostalAddress Property

Gets or sets whether PostalAddress is a U.S. postal address.

[Visual Basic]
Public Property IsUSPostalAddress As Boolean
[C#]
public bool IsUSPostalAddress {get; set;}

Example

Shows how to insert a BARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bookmark with a US postal code in it
builder.StartBookmark("BarcodeBookmark");
builder.Writeln("96801");
builder.EndBookmark("BarcodeBookmark");

builder.Writeln();

// Reference a US postal code directly
FieldBarcode fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.FacingIdentificationMark = "C";
fieldBarcode.PostalAddress = "96801";
fieldBarcode.IsUSPostalAddress = true;

builder.Writeln();

// Reference a US postal code from a bookmark
fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.PostalAddress = "BarcodeBookmark";
fieldBarcode.IsBookmark = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.USAddressBarcode.docx");

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


PostalAddress Property

Aspose.Words

FieldBarcode.PostalAddress Property

Gets or sets the postal address used for generating a barcode or the name of the bookmark that refers to it.

[Visual Basic]
Public Property PostalAddress As String
[C#]
public string PostalAddress {get; set;}

Example

Shows how to insert a BARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a bookmark with a US postal code in it
builder.StartBookmark("BarcodeBookmark");
builder.Writeln("96801");
builder.EndBookmark("BarcodeBookmark");

builder.Writeln();

// Reference a US postal code directly
FieldBarcode fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.FacingIdentificationMark = "C";
fieldBarcode.PostalAddress = "96801";
fieldBarcode.IsUSPostalAddress = true;

builder.Writeln();

// Reference a US postal code from a bookmark
fieldBarcode = (FieldBarcode)builder.InsertField(FieldType.FieldBarcode, true);
fieldBarcode.PostalAddress = "BarcodeBookmark";
fieldBarcode.IsBookmark = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.USAddressBarcode.docx");

See Also

FieldBarcode Class | Aspose.Words.Fields Namespace


FieldBibliography Class

Implements the BIBLIOGRAPHY field.

For a list of all members of this type, see FieldBibliography Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldBibliography

[Visual Basic]
Public Class FieldBibliography
Inherits Field
[C#]
public class FieldBibliography : Field

Remarks

Inserts the contents of the document's Bibliography part in a bibliographic style.

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldBibliography Members | Aspose.Words.Fields Namespace


FieldBibliography Members

FieldBibliography overview

Public Instance Constructors

FieldBibliography Constructor Initializes a new instance of the FieldBibliography class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatLanguageId | Gets or sets the language ID that is used to format the bibliographic sources in the document.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldBibliography Class | Aspose.Words.Fields Namespace


FieldBibliography Constructor

Initializes a new instance of the FieldBibliography class.

[Visual Basic]
Public Sub New()
[C#]
public FieldBibliography();

See Also

FieldBibliography Class | Aspose.Words.Fields Namespace


FieldBibliography Properties

The properties of the FieldBibliography class are listed below. For a complete list of FieldBibliography class members, see the FieldBibliography Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatLanguageId | Gets or sets the language ID that is used to format the bibliographic sources in the document.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldBibliography Class | Aspose.Words.Fields Namespace


FormatLanguageId Property

Aspose.Words

FieldBibliography.FormatLanguageId Property

Gets or sets the language ID that is used to format the bibliographic sources in the document.

[Visual Basic]
Public Property FormatLanguageId As String
[C#]
public string FormatLanguageId {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldBibliography Class | Aspose.Words.Fields Namespace


FieldBidiOutline Class

Implements the BIDIOUTLINE field.

For a list of all members of this type, see FieldBidiOutline Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldBidiOutline

[Visual Basic]
Public Class FieldBidiOutline
Inherits Field
[C#]
public class FieldBidiOutline : Field

Remarks

This field is identical to the AUTONUMLGL field, except for the separator that delimits each level of the paragraph numbering.

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldBidiOutline Members | Aspose.Words.Fields Namespace


FieldBidiOutline Members

FieldBidiOutline overview

Public Instance Constructors

FieldBidiOutline Constructor Initializes a new instance of the FieldBidiOutline class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldBidiOutline Class | Aspose.Words.Fields Namespace


FieldBidiOutline Constructor

Initializes a new instance of the FieldBidiOutline class.

[Visual Basic]
Public Sub New()
[C#]
public FieldBidiOutline();

See Also

FieldBidiOutline Class | Aspose.Words.Fields Namespace


FieldBuilder Class

Builds a field from field code tokens (arguments and switches).

For a list of all members of this type, see FieldBuilder Members.

System.Object
Aspose.Words.Fields.FieldBuilder

[Visual Basic]
Public Class FieldBuilder
[C#]
public class FieldBuilder

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldBuilder Members | Aspose.Words.Fields Namespace


FieldBuilder Members

FieldBuilder overview

Public Instance Constructors

FieldBuilder Constructor Initializes an instance of the FieldBuilder class.

Public Instance Methods

AddArgument | Overloaded. Adds a field's argument.
AddSwitch | Overloaded. Adds a field's switch.
BuildAndInsert | Overloaded. Builds and inserts a field into the document before the specified inline node.

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace


FieldBuilder Constructor

Initializes an instance of the FieldBuilder class.

[Visual Basic]
Public Sub New( _
ByVal fieldType As FieldType _
)
[C#]
public FieldBuilder(
FieldType fieldType
);

Parameters

fieldType
The type of the field to build.

Example

Builds and inserts a field into the document before the specified inline node

[C#]

Document doc = new Document();
Run run = DocumentHelper.InsertNewRun(doc, " Hello World!", 0);

FieldBuilder fieldBuilder = new FieldBuilder(FieldType.FieldRevisionNum);
fieldBuilder.BuildAndInsert(run);

doc.UpdateFields();

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace


FieldBuilder Methods

The methods of the FieldBuilder class are listed below. For a complete list of FieldBuilder class members, see the FieldBuilder Members topic.

Public Instance Methods

AddArgument | Overloaded. Adds a field's argument.
AddSwitch | Overloaded. Adds a field's switch.
BuildAndInsert | Overloaded. Builds and inserts a field into the document before the specified inline node.

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace


AddArgument Method

Aspose.Words

FieldBuilder.AddArgument Method

Adds a field's argument represented by FieldArgumentBuilder to the field's code.

Overload List

Adds a field's argument represented by FieldArgumentBuilder to the field's code.

public FieldBuilder AddArgument(FieldArgumentBuilder);

Adds a child field represented by another FieldBuilder to the field's code.

public FieldBuilder AddArgument(FieldBuilder);

Adds a field's argument.

public FieldBuilder AddArgument(double);

Adds a field's argument.

public FieldBuilder AddArgument(int);

Adds a field's argument.

public FieldBuilder AddArgument(string);

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace


FieldBuilder.AddArgument Method (FieldArgumentBuilder)

Adds a field's argument represented by FieldArgumentBuilder to the field's code.

[Visual Basic]
Overloads Public Function AddArgument( _
ByVal argument As FieldArgumentBuilder _
) As FieldBuilder
[C#]
public FieldBuilder AddArgument(
FieldArgumentBuilder argument
);

Remarks

This overload is used when the argument consists of a mixture of different parts such as child fields, nodes, and plain text.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddArgument Overload List


FieldBuilder.AddArgument Method (FieldBuilder)

Adds a child field represented by another FieldBuilder to the field's code.

[Visual Basic]
Overloads Public Function AddArgument( _
ByVal argument As FieldBuilder _
) As FieldBuilder
[C#]
public FieldBuilder AddArgument(
FieldBuilder argument
);

Remarks

This overload is used when the argument consists of a single child field.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddArgument Overload List


FieldBuilder.AddArgument Method (Double)

Adds a field's argument.

[Visual Basic]
Overloads Public Function AddArgument( _
ByVal argument As Double _
) As FieldBuilder
[C#]
public FieldBuilder AddArgument(
double argument
);

Parameters

argument
The argument value.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddArgument Overload List


FieldBuilder.AddArgument Method (Int32)

Adds a field's argument.

[Visual Basic]
Overloads Public Function AddArgument( _
ByVal argument As Integer _
) As FieldBuilder
[C#]
public FieldBuilder AddArgument(
int argument
);

Parameters

argument
The argument value.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddArgument Overload List


FieldBuilder.AddArgument Method (String)

Adds a field's argument.

[Visual Basic]
Overloads Public Function AddArgument( _
ByVal argument As String _
) As FieldBuilder
[C#]
public FieldBuilder AddArgument(
string argument
);

Parameters

argument
The argument value.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddArgument Overload List


AddSwitch Method

Aspose.Words

FieldBuilder.AddSwitch Method

Adds a field's switch.

Overload List

Adds a field's switch.

public FieldBuilder AddSwitch(string);

Adds a field's switch.

public FieldBuilder AddSwitch(string,double);

Adds a field's switch.

public FieldBuilder AddSwitch(string,int);

Adds a field's switch.

public FieldBuilder AddSwitch(string,string);

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace


FieldBuilder.AddSwitch Method (String)

Adds a field's switch.

[Visual Basic]
Overloads Public Function AddSwitch( _
ByVal switchName As String _
) As FieldBuilder
[C#]
public FieldBuilder AddSwitch(
string switchName
);

Parameters

switchName
The switch name.

Remarks

This overload adds a flag (switch without argument).

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddSwitch Overload List


FieldBuilder.AddSwitch Method (String, Double)

Adds a field's switch.

[Visual Basic]
Overloads Public Function AddSwitch( _
ByVal switchName As String, _
ByVal switchArgument As Double _
) As FieldBuilder
[C#]
public FieldBuilder AddSwitch(
string switchName,
double switchArgument
);

Parameters

switchName
The switch name.
switchArgument
The switch value.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddSwitch Overload List


FieldBuilder.AddSwitch Method (String, Int32)

Adds a field's switch.

[Visual Basic]
Overloads Public Function AddSwitch( _
ByVal switchName As String, _
ByVal switchArgument As Integer _
) As FieldBuilder
[C#]
public FieldBuilder AddSwitch(
string switchName,
int switchArgument
);

Parameters

switchName
The switch name.
switchArgument
The switch value.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddSwitch Overload List


FieldBuilder.AddSwitch Method (String, String)

Adds a field's switch.

[Visual Basic]
Overloads Public Function AddSwitch( _
ByVal switchName As String, _
ByVal switchArgument As String _
) As FieldBuilder
[C#]
public FieldBuilder AddSwitch(
string switchName,
string switchArgument
);

Parameters

switchName
The switch name.
switchArgument
The switch value.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.AddSwitch Overload List


BuildAndInsert Method

Aspose.Words

FieldBuilder.BuildAndInsert Method

Builds and inserts a field into the document before the specified inline node.

Overload List

Builds and inserts a field into the document before the specified inline node.

public Field BuildAndInsert(Inline);

Builds and inserts a field into the document to the end of the specified paragraph.

public Field BuildAndInsert(Paragraph);

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace


FieldBuilder.BuildAndInsert Method (Inline)

Builds and inserts a field into the document before the specified inline node.

[Visual Basic]
Overloads Public Function BuildAndInsert( _
ByVal refNode As Inline _
) As Field
[C#]
public Field BuildAndInsert(
Inline refNode
);

Return Value

A Field object that represents the inserted field.

Example

Builds and inserts a field into the document before the specified inline node

[C#]

Document doc = new Document();
Run run = DocumentHelper.InsertNewRun(doc, " Hello World!", 0);

FieldBuilder fieldBuilder = new FieldBuilder(FieldType.FieldRevisionNum);
fieldBuilder.BuildAndInsert(run);

doc.UpdateFields();

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.BuildAndInsert Overload List


FieldBuilder.BuildAndInsert Method (Paragraph)

Builds and inserts a field into the document to the end of the specified paragraph.

[Visual Basic]
Overloads Public Function BuildAndInsert( _
ByVal refNode As Paragraph _
) As Field
[C#]
public Field BuildAndInsert(
Paragraph refNode
);

Return Value

A Field object that represents the inserted field.

Example

Shows how to insert fields using a field builder.

[C#]

Document doc = new Document();

// Use a field builder to add a SYMBOL field which displays the "F with hook" symbol
FieldBuilder builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(402);
builder.AddSwitch("\\f", "Arial");
builder.AddSwitch("\\s", 25);
builder.AddSwitch("\\u");
Field field = builder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);

Assert.AreEqual(" SYMBOL 402 \\f Arial \\s 25 \\u ", field.GetFieldCode());

// Use a field builder to create a formula field that will be used by another field builder
FieldBuilder innerFormulaBuilder = new FieldBuilder(FieldType.FieldFormula);
innerFormulaBuilder.AddArgument(100);
innerFormulaBuilder.AddArgument("+");
innerFormulaBuilder.AddArgument(74);

// Add a field builder as an argument to another field builder
// The result of our formula field will be used as an ANSI value representing the "enclosed R" symbol,
// to be displayed by this SYMBOL field
builder = new FieldBuilder(FieldType.FieldSymbol);
builder.AddArgument(innerFormulaBuilder);
field = builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

Assert.AreEqual(" SYMBOL \u0013 = 100 + 74 \u0014\u0015 ", field.GetFieldCode());

// Now we will use our builder to construct a more complex field with nested fields
// For our IF field, we will first create two formula fields to serve as expressions
// Their results will be tested for equality to decide what value an IF field displays
FieldBuilder leftExpression = new FieldBuilder(FieldType.FieldFormula);
leftExpression.AddArgument(2);
leftExpression.AddArgument("+");
leftExpression.AddArgument(3);

FieldBuilder rightExpression = new FieldBuilder(FieldType.FieldFormula);
rightExpression.AddArgument(2.5);
rightExpression.AddArgument("*");
rightExpression.AddArgument(5.2);

// Next, we will create two field arguments using field argument builders
// These will serve as the two possible outputs of our IF field and they will also use our two expressions
FieldArgumentBuilder trueOutput = new FieldArgumentBuilder();
trueOutput.AddText("True, both expressions amount to ");
trueOutput.AddField(leftExpression);

FieldArgumentBuilder falseOutput = new FieldArgumentBuilder();
falseOutput.AddNode(new Run(doc, "False, "));
falseOutput.AddField(leftExpression);
falseOutput.AddNode(new Run(doc, " does not equal "));
falseOutput.AddField(rightExpression);

// Finally, we will use a field builder to create an IF field which takes two field builders as expressions,
// and two field argument builders as the two potential outputs
builder = new FieldBuilder(FieldType.FieldIf);
builder.AddArgument(leftExpression);
builder.AddArgument("=");
builder.AddArgument(rightExpression);
builder.AddArgument(trueOutput);
builder.AddArgument(falseOutput);

builder.BuildAndInsert(doc.FirstSection.Body.AppendParagraph(""));

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldBuilder.docx");

See Also

FieldBuilder Class | Aspose.Words.Fields Namespace | FieldBuilder.BuildAndInsert Overload List


FieldChar Class

Base class for nodes that represent field characters in a document.

For a list of all members of this type, see FieldChar Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.Fields.FieldChar
Aspose.Words.Fields.FieldEnd
Aspose.Words.Fields.FieldSeparator
Aspose.Words.Fields.FieldStart

[Visual Basic]
MustInherit Public Class FieldChar
Inherits SpecialChar
[C#]
public abstract class FieldChar : SpecialChar

Remarks

A complete field in a Microsoft Word document is a complex structure consisting of a field start character, field code, field separator character, field result and field end character. Some fields only have field start, field code and field end.

To easily insert a new field into a document, use the InsertField method.

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldChar Members | Aspose.Words.Fields Namespace | FieldStart | FieldSeparator | FieldEnd


FieldChar Members

FieldChar overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from SpecialChar) | Returns NodeType.SpecialChar.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept (inherited from SpecialChar) | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldChar Class | Aspose.Words.Fields Namespace | FieldStart | FieldSeparator | FieldEnd


FieldChar Properties

The properties of the FieldChar class are listed below. For a complete list of FieldChar class members, see the FieldChar Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType (inherited from SpecialChar) | Returns NodeType.SpecialChar.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

FieldChar Class | Aspose.Words.Fields Namespace | FieldStart | FieldSeparator | FieldEnd


FieldType Property

Aspose.Words

FieldChar.FieldType Property

Returns the type of the field.

[Visual Basic]
Public ReadOnly Property FieldType As FieldType
[C#]
public FieldType FieldType {get;}

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();

See Also

FieldChar Class | Aspose.Words.Fields Namespace


IsDirty Property

Aspose.Words

FieldChar.IsDirty Property

Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.

[Visual Basic]
Public Property IsDirty As Boolean
[C#]
public bool IsDirty {get; set;}

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();

See Also

FieldChar Class | Aspose.Words.Fields Namespace


IsLocked Property

Aspose.Words

FieldChar.IsLocked Property

Gets or sets whether the parent field is locked (should not recalculate its result).

[Visual Basic]
Public Property IsLocked As Boolean
[C#]
public bool IsLocked {get; set;}

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();

See Also

FieldChar Class | Aspose.Words.Fields Namespace


FieldChar Methods

The methods of the FieldChar class are listed below. For a complete list of FieldChar class members, see the FieldChar Members topic.

Public Instance Methods

Accept (inherited from SpecialChar) | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldChar Class | Aspose.Words.Fields Namespace | FieldStart | FieldSeparator | FieldEnd


FieldChar.GetField Method

Returns a field for the field char.

[Visual Basic]
Public Function GetField() As Field
[C#]
public Field GetField();

Return Value

A field for the field char.

Remarks

A new Field object is created each time the method is called.

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();

See Also

FieldChar Class | Aspose.Words.Fields Namespace


FieldCitation Class

Implements the CITATION field.

For a list of all members of this type, see FieldCitation Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldCitation

[Visual Basic]
Public Class FieldCitation
Inherits Field
[C#]
public class FieldCitation : Field

Remarks

Inserts the contents of the Source element with a specified Tag element using a bibliographic style.

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldCitation Members | Aspose.Words.Fields Namespace


FieldCitation Members

FieldCitation overview

Public Instance Constructors

FieldCitation Constructor Initializes a new instance of the FieldCitation class.

Public Instance Properties

AnotherSourceTag | Gets or sets a value that mathes the Tag element's value of another source to be included in the citation.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatLanguageId | Gets or sets the language ID that is used in conjunction with the specified bibliographic style to format the citation in the document.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumber | Gets or sets a page number associated with the citation.
Prefix | Gets or sets a prefix that is prepended to the citation.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceTag | Gets or sets a value that mathes the Tag element's value of the source to insert.
Start (inherited from Field) | Gets the node that represents the start of the field.
Suffix | Gets or sets a suffix that is appended to the citation.
SuppressAuthor | Gets or sets whether the author information is suppressed from the citation.
SuppressTitle | Gets or sets whether the title information is suppressed from the citation.
SuppressYear | Gets or sets whether the year information is suppressed from the citation.
Type (inherited from Field) | Gets the Microsoft Word field type.
VolumeNumber | Gets or sets a volume number associated with the citation.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


FieldCitation Constructor

Initializes a new instance of the FieldCitation class.

[Visual Basic]
Public Sub New()
[C#]
public FieldCitation();

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


FieldCitation Properties

The properties of the FieldCitation class are listed below. For a complete list of FieldCitation class members, see the FieldCitation Members topic.

Public Instance Properties

AnotherSourceTag | Gets or sets a value that mathes the Tag element's value of another source to be included in the citation.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatLanguageId | Gets or sets the language ID that is used in conjunction with the specified bibliographic style to format the citation in the document.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumber | Gets or sets a page number associated with the citation.
Prefix | Gets or sets a prefix that is prepended to the citation.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceTag | Gets or sets a value that mathes the Tag element's value of the source to insert.
Start (inherited from Field) | Gets the node that represents the start of the field.
Suffix | Gets or sets a suffix that is appended to the citation.
SuppressAuthor | Gets or sets whether the author information is suppressed from the citation.
SuppressTitle | Gets or sets whether the title information is suppressed from the citation.
SuppressYear | Gets or sets whether the year information is suppressed from the citation.
Type (inherited from Field) | Gets the Microsoft Word field type.
VolumeNumber | Gets or sets a volume number associated with the citation.

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


AnotherSourceTag Property

Aspose.Words

FieldCitation.AnotherSourceTag Property

Gets or sets a value that mathes the Tag element's value of another source to be included in the citation.

[Visual Basic]
Public Property AnotherSourceTag As String
[C#]
public string AnotherSourceTag {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


FormatLanguageId Property

Aspose.Words

FieldCitation.FormatLanguageId Property

Gets or sets the language ID that is used in conjunction with the specified bibliographic style to format the citation in the document.

[Visual Basic]
Public Property FormatLanguageId As String
[C#]
public string FormatLanguageId {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


PageNumber Property

Aspose.Words

FieldCitation.PageNumber Property

Gets or sets a page number associated with the citation.

[Visual Basic]
Public Property PageNumber As String
[C#]
public string PageNumber {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


Prefix Property

Aspose.Words

FieldCitation.Prefix Property

Gets or sets a prefix that is prepended to the citation.

[Visual Basic]
Public Property Prefix As String
[C#]
public string Prefix {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


SourceTag Property

Aspose.Words

FieldCitation.SourceTag Property

Gets or sets a value that mathes the Tag element's value of the source to insert.

[Visual Basic]
Public Property SourceTag As String
[C#]
public string SourceTag {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


Suffix Property

Aspose.Words

FieldCitation.Suffix Property

Gets or sets a suffix that is appended to the citation.

[Visual Basic]
Public Property Suffix As String
[C#]
public string Suffix {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


SuppressAuthor Property

Aspose.Words

FieldCitation.SuppressAuthor Property

Gets or sets whether the author information is suppressed from the citation.

[Visual Basic]
Public Property SuppressAuthor As Boolean
[C#]
public bool SuppressAuthor {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


SuppressTitle Property

Aspose.Words

FieldCitation.SuppressTitle Property

Gets or sets whether the title information is suppressed from the citation.

[Visual Basic]
Public Property SuppressTitle As Boolean
[C#]
public bool SuppressTitle {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


SuppressYear Property

Aspose.Words

FieldCitation.SuppressYear Property

Gets or sets whether the year information is suppressed from the citation.

[Visual Basic]
Public Property SuppressYear As Boolean
[C#]
public bool SuppressYear {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


VolumeNumber Property

Aspose.Words

FieldCitation.VolumeNumber Property

Gets or sets a volume number associated with the citation.

[Visual Basic]
Public Property VolumeNumber As String
[C#]
public string VolumeNumber {get; set;}

Example

Shows how to work with CITATION and BIBLIOGRAPHY fields.

[C#]

// Open a document that has bibliographical sources
Document doc = new Document(MyDir + "Document.HasBibliography.docx");

// Add text that we can cite
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Text to be cited with one source.");

// Create a citation field using the document builder
FieldCitation field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);

// A simple citation can have just the page number and author's name
field.SourceTag = "Book1"; // We refer to sources using their tag names
field.PageNumber = "85";
field.SuppressAuthor = false;
field.SuppressTitle = true;
field.SuppressYear = true;

Assert.AreEqual(" CITATION  Book1 \\p 85 \\t \\y", field.GetFieldCode());

// We can make a more detailed citation and make it cite 2 sources
builder.Write("Text to be cited with two sources.");
field = (FieldCitation)builder.InsertField(FieldType.FieldCitation, true);
field.SourceTag = "Book1";
field.AnotherSourceTag = "Book2";
field.FormatLanguageId = "en-US";
field.PageNumber = "19";
field.Prefix = "Prefix ";
field.Suffix = " Suffix";
field.SuppressAuthor = false;
field.SuppressTitle = false;
field.SuppressYear = false;
field.VolumeNumber = "VII";

Assert.AreEqual(" CITATION  Book1 \\m Book2 \\l en-US \\p 19 \\f \"Prefix \" \\s \" Suffix\" \\v VII", field.GetFieldCode());

// Insert a new page which will contain our bibliography
builder.InsertBreak(BreakType.PageBreak);

// All our sources can be displayed using a BIBLIOGRAPHY field
FieldBibliography fieldBibliography = (FieldBibliography)builder.InsertField(FieldType.FieldBibliography, true);
fieldBibliography.FormatLanguageId = "1124";

Assert.AreEqual(" BIBLIOGRAPHY  \\l 1124", fieldBibliography.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Citation.docx");

See Also

FieldCitation Class | Aspose.Words.Fields Namespace


FieldCollection Class

A collection of Field objects that represents the fields in the specified range.

For a list of all members of this type, see FieldCollection Members.

System.Object
Aspose.Words.Fields.FieldCollection

[Visual Basic]
Public Class FieldCollection
Implements IEnumerable`1([Aspose.Words.Fields.Field, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class FieldCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

An instance of this collection contains fields which starts fall within the specified range.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldCollection Members | Aspose.Words.Fields Namespace


FieldCollection Members

FieldCollection overview

Public Instance Properties

Count | Returns the number of the fields in the collection.
Item | Returns a field at the specified index.

Public Instance Methods

Clear | Removes all fields of this collection from the document and from this collection itself.
GetEnumerator | Returns an enumerator object.
Remove | Removes the specified field from this collection and from the document.
RemoveAt | Removes a field at the specified index from this collection and from the document.

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection Properties

The properties of the FieldCollection class are listed below. For a complete list of FieldCollection class members, see the FieldCollection Members topic.

Public Instance Properties

Count | Returns the number of the fields in the collection.
Item | Returns a field at the specified index.

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


Count Property

Aspose.Words

FieldCollection.Count Property

Returns the number of the fields in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


Item Property

Aspose.Words

FieldCollection.Item Property

Returns a field at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Field
[C#]
public Field this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection Methods

The methods of the FieldCollection class are listed below. For a complete list of FieldCollection class members, see the FieldCollection Members topic.

Public Instance Methods

Clear | Removes all fields of this collection from the document and from this collection itself.
GetEnumerator | Returns an enumerator object.
Remove | Removes the specified field from this collection and from the document.
RemoveAt | Removes a field at the specified index from this collection and from the document.

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection.Clear Method

Removes all fields of this collection from the document and from this collection itself.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Field) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Field> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection.Remove Method

Removes the specified field from this collection and from the document.

[Visual Basic]
Public Sub Remove( _
ByVal field As Field _
)
[C#]
public void Remove(
Field field
);

Parameters

field
A field to remove.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection.RemoveAt Method

Removes a field at the specified index from this collection and from the document.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
An index into the collection.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldComments Class

Implements the COMMENTS field.

For a list of all members of this type, see FieldComments Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldComments

[Visual Basic]
Public Class FieldComments
Inherits Field
[C#]
public class FieldComments : Field

Remarks

Retrieves, and optionally sets, the comments relating to the current document, as recorded in the Comments property of the built-in document properties.

Example

Shows how to use the COMMENTS field to display a document's comments.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// This property is where the COMMENTS field will source its content from
doc.BuiltInDocumentProperties.Comments = "My comment.";

// Insert a COMMENTS field with a document builder
FieldComments field = (FieldComments)builder.InsertField(FieldType.FieldComments, true);
field.Update();

Assert.AreEqual("My comment.", field.Result);

// We can override the comment from the document's built in properties and display any text we put here instead
field.Text = "My overriding comment.";
field.Update();

Assert.AreEqual("My overriding comment.", field.Result);

doc.Save(ArtifactsDir + "Field.Comments.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldComments Members | Aspose.Words.Fields Namespace


FieldComments Members

FieldComments overview

Public Instance Constructors

FieldComments Constructor Initializes a new instance of the FieldComments class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the comments.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldComments Class | Aspose.Words.Fields Namespace


FieldComments Constructor

Initializes a new instance of the FieldComments class.

[Visual Basic]
Public Sub New()
[C#]
public FieldComments();

See Also

FieldComments Class | Aspose.Words.Fields Namespace


FieldComments Properties

The properties of the FieldComments class are listed below. For a complete list of FieldComments class members, see the FieldComments Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the comments.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldComments Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldComments.Text Property

Gets or sets the text of the comments.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to use the COMMENTS field to display a document's comments.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// This property is where the COMMENTS field will source its content from
doc.BuiltInDocumentProperties.Comments = "My comment.";

// Insert a COMMENTS field with a document builder
FieldComments field = (FieldComments)builder.InsertField(FieldType.FieldComments, true);
field.Update();

Assert.AreEqual("My comment.", field.Result);

// We can override the comment from the document's built in properties and display any text we put here instead
field.Text = "My overriding comment.";
field.Update();

Assert.AreEqual("My overriding comment.", field.Result);

doc.Save(ArtifactsDir + "Field.Comments.docx");

See Also

FieldComments Class | Aspose.Words.Fields Namespace


FieldCompare Class

Implements the COMPARE field.

For a list of all members of this type, see FieldCompare Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldCompare

[Visual Basic]
Public Class FieldCompare
Inherits Field
[C#]
public class FieldCompare : Field

Remarks

Compares the values designated by the expressions LeftExpression and RightExpression in comparison using the operator designated by ComparisonOperator.

Example

Shows how to insert a field that compares expressions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a compare field using a document builder
FieldCompare field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);

// Construct a comparison statement
field.LeftExpression = "3";
field.ComparisonOperator = "<";
field.RightExpression = "2";

// The compare field will print a "0" or "1" depending on the truth of its statement
// The result of this statement is false, so a "0" will be show up in the document
Assert.AreEqual(" COMPARE  3 < 2", field.GetFieldCode());

builder.Writeln();

// Here a "1" will show up, because the statement is true
field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);
field.LeftExpression = "5";
field.ComparisonOperator = "=";
field.RightExpression = "2 + 3";

Assert.AreEqual(" COMPARE  5 = \"2 + 3\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Compare.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldCompare Members | Aspose.Words.Fields Namespace


FieldCompare Members

FieldCompare overview

Public Instance Constructors

FieldCompare Constructor Initializes a new instance of the FieldCompare class.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldCompare Class | Aspose.Words.Fields Namespace


FieldCompare Constructor

Initializes a new instance of the FieldCompare class.

[Visual Basic]
Public Sub New()
[C#]
public FieldCompare();

See Also

FieldCompare Class | Aspose.Words.Fields Namespace


FieldCompare Properties

The properties of the FieldCompare class are listed below. For a complete list of FieldCompare class members, see the FieldCompare Members topic.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldCompare Class | Aspose.Words.Fields Namespace


ComparisonOperator Property

Aspose.Words

FieldCompare.ComparisonOperator Property

Gets or sets the comparison operator.

[Visual Basic]
Public Property ComparisonOperator As String
[C#]
public string ComparisonOperator {get; set;}

Example

Shows how to insert a field that compares expressions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a compare field using a document builder
FieldCompare field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);

// Construct a comparison statement
field.LeftExpression = "3";
field.ComparisonOperator = "<";
field.RightExpression = "2";

// The compare field will print a "0" or "1" depending on the truth of its statement
// The result of this statement is false, so a "0" will be show up in the document
Assert.AreEqual(" COMPARE  3 < 2", field.GetFieldCode());

builder.Writeln();

// Here a "1" will show up, because the statement is true
field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);
field.LeftExpression = "5";
field.ComparisonOperator = "=";
field.RightExpression = "2 + 3";

Assert.AreEqual(" COMPARE  5 = \"2 + 3\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Compare.docx");

See Also

FieldCompare Class | Aspose.Words.Fields Namespace


LeftExpression Property

Aspose.Words

FieldCompare.LeftExpression Property

Gets or sets the left part of the comparison expression.

[Visual Basic]
Public Property LeftExpression As String
[C#]
public string LeftExpression {get; set;}

Example

Shows how to insert a field that compares expressions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a compare field using a document builder
FieldCompare field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);

// Construct a comparison statement
field.LeftExpression = "3";
field.ComparisonOperator = "<";
field.RightExpression = "2";

// The compare field will print a "0" or "1" depending on the truth of its statement
// The result of this statement is false, so a "0" will be show up in the document
Assert.AreEqual(" COMPARE  3 < 2", field.GetFieldCode());

builder.Writeln();

// Here a "1" will show up, because the statement is true
field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);
field.LeftExpression = "5";
field.ComparisonOperator = "=";
field.RightExpression = "2 + 3";

Assert.AreEqual(" COMPARE  5 = \"2 + 3\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Compare.docx");

See Also

FieldCompare Class | Aspose.Words.Fields Namespace


RightExpression Property

Aspose.Words

FieldCompare.RightExpression Property

Gets or sets the right part of the comparison expression.

[Visual Basic]
Public Property RightExpression As String
[C#]
public string RightExpression {get; set;}

Example

Shows how to insert a field that compares expressions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a compare field using a document builder
FieldCompare field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);

// Construct a comparison statement
field.LeftExpression = "3";
field.ComparisonOperator = "<";
field.RightExpression = "2";

// The compare field will print a "0" or "1" depending on the truth of its statement
// The result of this statement is false, so a "0" will be show up in the document
Assert.AreEqual(" COMPARE  3 < 2", field.GetFieldCode());

builder.Writeln();

// Here a "1" will show up, because the statement is true
field = (FieldCompare)builder.InsertField(FieldType.FieldCompare, true);
field.LeftExpression = "5";
field.ComparisonOperator = "=";
field.RightExpression = "2 + 3";

Assert.AreEqual(" COMPARE  5 = \"2 + 3\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Compare.docx");

See Also

FieldCompare Class | Aspose.Words.Fields Namespace


FieldCreateDate Class

Implements the CREATEDATE field.

For a list of all members of this type, see FieldCreateDate Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldCreateDate

[Visual Basic]
Public Class FieldCreateDate
Inherits Field
[C#]
public class FieldCreateDate : Field

Remarks

Retrieves the date and time at which the document was created. By default, the Gregorian calendar is used.

Example

Shows how to insert CREATEDATE fields to display document creation dates.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was created:");

// Insert a CREATEDATE field and display, using the Lunar Calendar, the date the document was created
builder.Write("According to the Lunar Calendar - ");
FieldCreateDate fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseLunarCalendar = true;
Assert.AreEqual(" CREATEDATE  \\h", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\u", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseSakaEraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\s", fieldCreateDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.CreateDate.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldCreateDate Members | Aspose.Words.Fields Namespace


FieldCreateDate Members

FieldCreateDate overview

Public Instance Constructors

FieldCreateDate Constructor Initializes a new instance of the FieldCreateDate class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldCreateDate Class | Aspose.Words.Fields Namespace


FieldCreateDate Constructor

Initializes a new instance of the FieldCreateDate class.

[Visual Basic]
Public Sub New()
[C#]
public FieldCreateDate();

See Also

FieldCreateDate Class | Aspose.Words.Fields Namespace


FieldCreateDate Properties

The properties of the FieldCreateDate class are listed below. For a complete list of FieldCreateDate class members, see the FieldCreateDate Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

See Also

FieldCreateDate Class | Aspose.Words.Fields Namespace


UseLunarCalendar Property

Aspose.Words

FieldCreateDate.UseLunarCalendar Property

Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.

[Visual Basic]
Public Property UseLunarCalendar As Boolean
[C#]
public bool UseLunarCalendar {get; set;}

Example

Shows how to insert CREATEDATE fields to display document creation dates.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was created:");

// Insert a CREATEDATE field and display, using the Lunar Calendar, the date the document was created
builder.Write("According to the Lunar Calendar - ");
FieldCreateDate fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseLunarCalendar = true;
Assert.AreEqual(" CREATEDATE  \\h", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\u", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseSakaEraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\s", fieldCreateDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.CreateDate.docx");

See Also

FieldCreateDate Class | Aspose.Words.Fields Namespace


UseSakaEraCalendar Property

Aspose.Words

FieldCreateDate.UseSakaEraCalendar Property

Gets or sets whether to use the Saka Era calendar.

[Visual Basic]
Public Property UseSakaEraCalendar As Boolean
[C#]
public bool UseSakaEraCalendar {get; set;}

Example

Shows how to insert CREATEDATE fields to display document creation dates.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was created:");

// Insert a CREATEDATE field and display, using the Lunar Calendar, the date the document was created
builder.Write("According to the Lunar Calendar - ");
FieldCreateDate fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseLunarCalendar = true;
Assert.AreEqual(" CREATEDATE  \\h", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\u", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseSakaEraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\s", fieldCreateDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.CreateDate.docx");

See Also

FieldCreateDate Class | Aspose.Words.Fields Namespace


UseUmAlQuraCalendar Property

Aspose.Words

FieldCreateDate.UseUmAlQuraCalendar Property

Gets or sets whether to use the Um-al-Qura calendar.

[Visual Basic]
Public Property UseUmAlQuraCalendar As Boolean
[C#]
public bool UseUmAlQuraCalendar {get; set;}

Example

Shows how to insert CREATEDATE fields to display document creation dates.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was created:");

// Insert a CREATEDATE field and display, using the Lunar Calendar, the date the document was created
builder.Write("According to the Lunar Calendar - ");
FieldCreateDate fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseLunarCalendar = true;
Assert.AreEqual(" CREATEDATE  \\h", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\u", fieldCreateDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National Calendar - ");
fieldCreateDate = (FieldCreateDate)builder.InsertField(FieldType.FieldCreateDate, true);
fieldCreateDate.UseSakaEraCalendar = true;
Assert.AreEqual(" CREATEDATE  \\s", fieldCreateDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.CreateDate.docx");

See Also

FieldCreateDate Class | Aspose.Words.Fields Namespace


FieldData Class

Implements the DATA field.

For a list of all members of this type, see FieldData Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldData

[Visual Basic]
Public Class FieldData
Inherits Field
[C#]
public class FieldData : Field

Example

Shows how to insert a data field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a data field
FieldData field = (FieldData)builder.InsertField(FieldType.FieldData, true);
Assert.AreEqual(" DATA ", field.GetFieldCode());

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldData Members | Aspose.Words.Fields Namespace


FieldData Members

FieldData overview

Public Instance Constructors

FieldData Constructor Initializes a new instance of the FieldData class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldData Class | Aspose.Words.Fields Namespace


FieldData Constructor

Initializes a new instance of the FieldData class.

[Visual Basic]
Public Sub New()
[C#]
public FieldData();

See Also

FieldData Class | Aspose.Words.Fields Namespace


FieldDatabase Class

Implements the DATABASE field.

For a list of all members of this type, see FieldDatabase Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDatabase

[Visual Basic]
Public Class FieldDatabase
Inherits Field
[C#]
public class FieldDatabase : Field

Remarks

Inserts the results of a database query into a WordprocessingML table.

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDatabase Members | Aspose.Words.Fields Namespace


FieldDatabase Members

FieldDatabase overview

Public Instance Constructors

FieldDatabase Constructor Initializes a new instance of the FieldDatabase class.

Public Instance Properties

Connection | Gets or sets a connection to the data.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FileName | Gets or sets the complete path and file name of the database
FirstRecord | Gets or sets the integral record number of the first data record to insert.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatAttributes | Gets or sets which attributes of the format are to be applied to the table.
InsertHeadings | Gets or sets whether to insert the field names from the database as column headings in the resulting table.
InsertOnceOnMailMerge | Gets or sets whether to insert data at the beginning of a merge.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LastRecord | Gets or sets the integral record number of the last data record to insert.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Query | Gets or sets a set of SQL instructions that query the database.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
TableFormat | Gets or sets the format that is to be applied to the result of the database query.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


FieldDatabase Constructor

Initializes a new instance of the FieldDatabase class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDatabase();

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


FieldDatabase Properties

The properties of the FieldDatabase class are listed below. For a complete list of FieldDatabase class members, see the FieldDatabase Members topic.

Public Instance Properties

Connection | Gets or sets a connection to the data.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FileName | Gets or sets the complete path and file name of the database
FirstRecord | Gets or sets the integral record number of the first data record to insert.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatAttributes | Gets or sets which attributes of the format are to be applied to the table.
InsertHeadings | Gets or sets whether to insert the field names from the database as column headings in the resulting table.
InsertOnceOnMailMerge | Gets or sets whether to insert data at the beginning of a merge.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LastRecord | Gets or sets the integral record number of the last data record to insert.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Query | Gets or sets a set of SQL instructions that query the database.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
TableFormat | Gets or sets the format that is to be applied to the result of the database query.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


Connection Property

Aspose.Words

FieldDatabase.Connection Property

Gets or sets a connection to the data.

[Visual Basic]
Public Property Connection As String
[C#]
public string Connection {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


FileName Property

Aspose.Words

FieldDatabase.FileName Property

Gets or sets the complete path and file name of the database

[Visual Basic]
Public Property FileName As String
[C#]
public string FileName {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


FirstRecord Property

Aspose.Words

FieldDatabase.FirstRecord Property

Gets or sets the integral record number of the first data record to insert.

[Visual Basic]
Public Property FirstRecord As String
[C#]
public string FirstRecord {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


FormatAttributes Property

Aspose.Words

FieldDatabase.FormatAttributes Property

Gets or sets which attributes of the format are to be applied to the table.

[Visual Basic]
Public Property FormatAttributes As String
[C#]
public string FormatAttributes {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


InsertHeadings Property

Aspose.Words

FieldDatabase.InsertHeadings Property

Gets or sets whether to insert the field names from the database as column headings in the resulting table.

[Visual Basic]
Public Property InsertHeadings As Boolean
[C#]
public bool InsertHeadings {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


InsertOnceOnMailMerge Property

Aspose.Words

FieldDatabase.InsertOnceOnMailMerge Property

Gets or sets whether to insert data at the beginning of a merge.

[Visual Basic]
Public Property InsertOnceOnMailMerge As Boolean
[C#]
public bool InsertOnceOnMailMerge {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


LastRecord Property

Aspose.Words

FieldDatabase.LastRecord Property

Gets or sets the integral record number of the last data record to insert.

[Visual Basic]
Public Property LastRecord As String
[C#]
public string LastRecord {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


Query Property

Aspose.Words

FieldDatabase.Query Property

Gets or sets a set of SQL instructions that query the database.

[Visual Basic]
Public Property Query As String
[C#]
public string Query {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


TableFormat Property

Aspose.Words

FieldDatabase.TableFormat Property

Gets or sets the format that is to be applied to the result of the database query.

[Visual Basic]
Public Property TableFormat As String
[C#]
public string TableFormat {get; set;}

Example

Shows how to extract data from a database and insert it as a field into a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a database field
FieldDatabase field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);

// Create a simple query that extracts one table from the database
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";
field.Query = "SELECT * FROM [Products]";

// Insert another database field
field = (FieldDatabase)builder.InsertField(FieldType.FieldDatabase, true);
field.FileName = MyDir + @"Database\Northwind.mdb";
field.Connection = "DSN=MS Access Databases";

// This query will sort all the products by their gross sales in descending order
field.Query =
    "SELECT [Products].ProductName, FORMAT(SUM([Order Details].UnitPrice * (1 - [Order Details].Discount) * [Order Details].Quantity), 'Currency') AS GrossSales " +
    "FROM([Products] " +
    "LEFT JOIN[Order Details] ON[Products].[ProductID] = [Order Details].[ProductID]) " +
    "GROUP BY[Products].ProductName " +
    "ORDER BY SUM([Order Details].UnitPrice* (1 - [Order Details].Discount) * [Order Details].Quantity) DESC";

// You can use these variables instead of a LIMIT clause, to simplify your query
// In this case we are taking the first 10 values of the result of our query
field.FirstRecord = "1";
field.LastRecord = "10";

// The number we put here is the index of the format we want to use for our table
// The list of table formats is in the "Table AutoFormat..." menu we find in MS Word when we create a data table field
// Index "10" corresponds to the "Colorful 3" format
field.TableFormat = "10";

// This attribute decides which elements of the table format we picked above we incorporate into our table
// The number we use is a sum of a combination of values corresponding to which elements we choose
// 63 represents borders (1) + shading (2) + font (4) + colour (8) + autofit (16) + heading rows (32)
field.FormatAttributes = "63";

field.InsertHeadings = true;
field.InsertOnceOnMailMerge = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Database.docx");

See Also

FieldDatabase Class | Aspose.Words.Fields Namespace


FieldDate Class

Implements the DATE field.

For a list of all members of this type, see FieldDate Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDate

[Visual Basic]
Public Class FieldDate
Inherits Field
[C#]
public class FieldDate : Field

Remarks

Inserts the current date and time. By default, the Gregorian calendar is used.

Example

Shows how to insert DATE fields with different kinds of calendars.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// One way of putting dates into our documents is inserting DATE fields with document builder
FieldDate fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);

// Set the field's date to the current date of the Islamic Lunar Calendar
fieldDate.UseLunarCalendar = true;
Assert.AreEqual(" DATE  \\h", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Umm al-Qura calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" DATE  \\u", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Indian national calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseSakaEraCalendar = true;
Assert.AreEqual(" DATE  \\s", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the calendar used in the (Insert > Date and Time) dialog box
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseLastFormat = true;
Assert.AreEqual(" DATE  \\l", fieldDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Date.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDate Members | Aspose.Words.Fields Namespace


FieldDate Members

FieldDate overview

Public Instance Constructors

FieldDate Constructor Initializes a new instance of the FieldDate class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLastFormat | Gets or sets whether to use a format last used by the hosting application when inserting a new DATE field.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDate Class | Aspose.Words.Fields Namespace


FieldDate Constructor

Initializes a new instance of the FieldDate class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDate();

See Also

FieldDate Class | Aspose.Words.Fields Namespace


FieldDate Properties

The properties of the FieldDate class are listed below. For a complete list of FieldDate class members, see the FieldDate Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLastFormat | Gets or sets whether to use a format last used by the hosting application when inserting a new DATE field.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

See Also

FieldDate Class | Aspose.Words.Fields Namespace


UseLastFormat Property

Aspose.Words

FieldDate.UseLastFormat Property

Gets or sets whether to use a format last used by the hosting application when inserting a new DATE field.

[Visual Basic]
Public Property UseLastFormat As Boolean
[C#]
public bool UseLastFormat {get; set;}

Example

Shows how to insert DATE fields with different kinds of calendars.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// One way of putting dates into our documents is inserting DATE fields with document builder
FieldDate fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);

// Set the field's date to the current date of the Islamic Lunar Calendar
fieldDate.UseLunarCalendar = true;
Assert.AreEqual(" DATE  \\h", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Umm al-Qura calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" DATE  \\u", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Indian national calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseSakaEraCalendar = true;
Assert.AreEqual(" DATE  \\s", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the calendar used in the (Insert > Date and Time) dialog box
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseLastFormat = true;
Assert.AreEqual(" DATE  \\l", fieldDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Date.docx");

See Also

FieldDate Class | Aspose.Words.Fields Namespace


UseLunarCalendar Property

Aspose.Words

FieldDate.UseLunarCalendar Property

Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.

[Visual Basic]
Public Property UseLunarCalendar As Boolean
[C#]
public bool UseLunarCalendar {get; set;}

Example

Shows how to insert DATE fields with different kinds of calendars.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// One way of putting dates into our documents is inserting DATE fields with document builder
FieldDate fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);

// Set the field's date to the current date of the Islamic Lunar Calendar
fieldDate.UseLunarCalendar = true;
Assert.AreEqual(" DATE  \\h", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Umm al-Qura calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" DATE  \\u", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Indian national calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseSakaEraCalendar = true;
Assert.AreEqual(" DATE  \\s", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the calendar used in the (Insert > Date and Time) dialog box
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseLastFormat = true;
Assert.AreEqual(" DATE  \\l", fieldDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Date.docx");

See Also

FieldDate Class | Aspose.Words.Fields Namespace


UseSakaEraCalendar Property

Aspose.Words

FieldDate.UseSakaEraCalendar Property

Gets or sets whether to use the Saka Era calendar.

[Visual Basic]
Public Property UseSakaEraCalendar As Boolean
[C#]
public bool UseSakaEraCalendar {get; set;}

Example

Shows how to insert DATE fields with different kinds of calendars.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// One way of putting dates into our documents is inserting DATE fields with document builder
FieldDate fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);

// Set the field's date to the current date of the Islamic Lunar Calendar
fieldDate.UseLunarCalendar = true;
Assert.AreEqual(" DATE  \\h", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Umm al-Qura calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" DATE  \\u", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Indian national calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseSakaEraCalendar = true;
Assert.AreEqual(" DATE  \\s", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the calendar used in the (Insert > Date and Time) dialog box
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseLastFormat = true;
Assert.AreEqual(" DATE  \\l", fieldDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Date.docx");

See Also

FieldDate Class | Aspose.Words.Fields Namespace


UseUmAlQuraCalendar Property

Aspose.Words

FieldDate.UseUmAlQuraCalendar Property

Gets or sets whether to use the Um-al-Qura calendar.

[Visual Basic]
Public Property UseUmAlQuraCalendar As Boolean
[C#]
public bool UseUmAlQuraCalendar {get; set;}

Example

Shows how to insert DATE fields with different kinds of calendars.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// One way of putting dates into our documents is inserting DATE fields with document builder
FieldDate fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);

// Set the field's date to the current date of the Islamic Lunar Calendar
fieldDate.UseLunarCalendar = true;
Assert.AreEqual(" DATE  \\h", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Umm al-Qura calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" DATE  \\u", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the Indian national calendar
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseSakaEraCalendar = true;
Assert.AreEqual(" DATE  \\s", fieldDate.GetFieldCode());
builder.Writeln();

// Insert a date field with the current date of the calendar used in the (Insert > Date and Time) dialog box
fieldDate = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
fieldDate.UseLastFormat = true;
Assert.AreEqual(" DATE  \\l", fieldDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Date.docx");

See Also

FieldDate Class | Aspose.Words.Fields Namespace


FieldDde Class

Implements the DDE field.

For a list of all members of this type, see FieldDde Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDde

[Visual Basic]
Public Class FieldDde
Inherits Field
[C#]
public class FieldDde : Field

Remarks

For information copied from another application, this field links that information to its original source file using DDE.

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDde Members | Aspose.Words.Fields Namespace


FieldDde Members

FieldDde overview

Public Instance Constructors

FieldDde Constructor Initializes a new instance of the FieldDde class.

Public Instance Properties

AutoUpdate | Gets or sets whether to update this field automatically.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertAsBitmap | Gets or sets whether to insert the linked object as a bitmap.
InsertAsHtml | Gets or sets whether to insert the linked object as HTML format text.
InsertAsPicture | Gets or sets whether to insert the linked object as a picture.
InsertAsRtf | Gets or sets whether to insert the linked object in rich-text format (RTF).
InsertAsText | Gets or sets whether to insert the linked object in text-only format.
InsertAsUnicode | Gets or sets whether to insert the linked object as Unicode text.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ProgId | Gets or sets the application type of the link information.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the name and location of the source file.
SourceItem | Gets or sets the portion of the source file that's being linked.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDde Class | Aspose.Words.Fields Namespace


FieldDde Constructor

Initializes a new instance of the FieldDde class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDde();

See Also

FieldDde Class | Aspose.Words.Fields Namespace


FieldDde Properties

The properties of the FieldDde class are listed below. For a complete list of FieldDde class members, see the FieldDde Members topic.

Public Instance Properties

AutoUpdate | Gets or sets whether to update this field automatically.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertAsBitmap | Gets or sets whether to insert the linked object as a bitmap.
InsertAsHtml | Gets or sets whether to insert the linked object as HTML format text.
InsertAsPicture | Gets or sets whether to insert the linked object as a picture.
InsertAsRtf | Gets or sets whether to insert the linked object in rich-text format (RTF).
InsertAsText | Gets or sets whether to insert the linked object in text-only format.
InsertAsUnicode | Gets or sets whether to insert the linked object as Unicode text.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ProgId | Gets or sets the application type of the link information.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the name and location of the source file.
SourceItem | Gets or sets the portion of the source file that's being linked.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldDde Class | Aspose.Words.Fields Namespace


AutoUpdate Property

Aspose.Words

FieldDde.AutoUpdate Property

Gets or sets whether to update this field automatically.

[Visual Basic]
Public Property AutoUpdate As Boolean
[C#]
public bool AutoUpdate {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


InsertAsBitmap Property

Aspose.Words

FieldDde.InsertAsBitmap Property

Gets or sets whether to insert the linked object as a bitmap.

[Visual Basic]
Public Property InsertAsBitmap As Boolean
[C#]
public bool InsertAsBitmap {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


InsertAsHtml Property

Aspose.Words

FieldDde.InsertAsHtml Property

Gets or sets whether to insert the linked object as HTML format text.

[Visual Basic]
Public Property InsertAsHtml As Boolean
[C#]
public bool InsertAsHtml {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


InsertAsPicture Property

Aspose.Words

FieldDde.InsertAsPicture Property

Gets or sets whether to insert the linked object as a picture.

[Visual Basic]
Public Property InsertAsPicture As Boolean
[C#]
public bool InsertAsPicture {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


InsertAsRtf Property

Aspose.Words

FieldDde.InsertAsRtf Property

Gets or sets whether to insert the linked object in rich-text format (RTF).

[Visual Basic]
Public Property InsertAsRtf As Boolean
[C#]
public bool InsertAsRtf {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


InsertAsText Property

Aspose.Words

FieldDde.InsertAsText Property

Gets or sets whether to insert the linked object in text-only format.

[Visual Basic]
Public Property InsertAsText As Boolean
[C#]
public bool InsertAsText {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


InsertAsUnicode Property

Aspose.Words

FieldDde.InsertAsUnicode Property

Gets or sets whether to insert the linked object as Unicode text.

[Visual Basic]
Public Property InsertAsUnicode As Boolean
[C#]
public bool InsertAsUnicode {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


IsLinked Property

Aspose.Words

FieldDde.IsLinked Property

Gets or sets whether to reduce the file size by not storing graphics data with the document.

[Visual Basic]
Public Property IsLinked As Boolean
[C#]
public bool IsLinked {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


ProgId Property

Aspose.Words

FieldDde.ProgId Property

Gets or sets the application type of the link information.

[Visual Basic]
Public Property ProgId As String
[C#]
public string ProgId {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldDde.SourceFullName Property

Gets or sets the name and location of the source file.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


SourceItem Property

Aspose.Words

FieldDde.SourceItem Property

Gets or sets the portion of the source file that's being linked.

[Visual Basic]
Public Property SourceItem As String
[C#]
public string SourceItem {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDde Class | Aspose.Words.Fields Namespace


FieldDdeAuto Class

Implements the DDEAUTO field.

For a list of all members of this type, see FieldDdeAuto Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDdeAuto

[Visual Basic]
Public Class FieldDdeAuto
Inherits Field
[C#]
public class FieldDdeAuto : Field

Remarks

For information copied from another application, this field links that information to its original source file using DDE and is updated automatically.

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDdeAuto Members | Aspose.Words.Fields Namespace


FieldDdeAuto Members

FieldDdeAuto overview

Public Instance Constructors

FieldDdeAuto Constructor Initializes a new instance of the FieldDdeAuto class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertAsBitmap | Gets or sets whether to insert the linked object as a bitmap.
InsertAsHtml | Gets or sets whether to insert the linked object as HTML format text.
InsertAsPicture | Gets or sets whether to insert the linked object as a picture.
InsertAsRtf | Gets or sets whether to insert the linked object in rich-text format (RTF).
InsertAsText | Gets or sets whether to insert the linked object in text-only format.
InsertAsUnicode | Gets or sets whether to insert the linked object as Unicode text.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ProgId | Gets or sets the application type of the link information.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the name and location of the source file.
SourceItem | Gets or sets the portion of the source file that's being linked.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


FieldDdeAuto Constructor

Initializes a new instance of the FieldDdeAuto class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDdeAuto();

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


FieldDdeAuto Properties

The properties of the FieldDdeAuto class are listed below. For a complete list of FieldDdeAuto class members, see the FieldDdeAuto Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertAsBitmap | Gets or sets whether to insert the linked object as a bitmap.
InsertAsHtml | Gets or sets whether to insert the linked object as HTML format text.
InsertAsPicture | Gets or sets whether to insert the linked object as a picture.
InsertAsRtf | Gets or sets whether to insert the linked object in rich-text format (RTF).
InsertAsText | Gets or sets whether to insert the linked object in text-only format.
InsertAsUnicode | Gets or sets whether to insert the linked object as Unicode text.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ProgId | Gets or sets the application type of the link information.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the name and location of the source file.
SourceItem | Gets or sets the portion of the source file that's being linked.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


InsertAsBitmap Property

Aspose.Words

FieldDdeAuto.InsertAsBitmap Property

Gets or sets whether to insert the linked object as a bitmap.

[Visual Basic]
Public Property InsertAsBitmap As Boolean
[C#]
public bool InsertAsBitmap {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


InsertAsHtml Property

Aspose.Words

FieldDdeAuto.InsertAsHtml Property

Gets or sets whether to insert the linked object as HTML format text.

[Visual Basic]
Public Property InsertAsHtml As Boolean
[C#]
public bool InsertAsHtml {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


InsertAsPicture Property

Aspose.Words

FieldDdeAuto.InsertAsPicture Property

Gets or sets whether to insert the linked object as a picture.

[Visual Basic]
Public Property InsertAsPicture As Boolean
[C#]
public bool InsertAsPicture {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


InsertAsRtf Property

Aspose.Words

FieldDdeAuto.InsertAsRtf Property

Gets or sets whether to insert the linked object in rich-text format (RTF).

[Visual Basic]
Public Property InsertAsRtf As Boolean
[C#]
public bool InsertAsRtf {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


InsertAsText Property

Aspose.Words

FieldDdeAuto.InsertAsText Property

Gets or sets whether to insert the linked object in text-only format.

[Visual Basic]
Public Property InsertAsText As Boolean
[C#]
public bool InsertAsText {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


InsertAsUnicode Property

Aspose.Words

FieldDdeAuto.InsertAsUnicode Property

Gets or sets whether to insert the linked object as Unicode text.

[Visual Basic]
Public Property InsertAsUnicode As Boolean
[C#]
public bool InsertAsUnicode {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


IsLinked Property

Aspose.Words

FieldDdeAuto.IsLinked Property

Gets or sets whether to reduce the file size by not storing graphics data with the document.

[Visual Basic]
Public Property IsLinked As Boolean
[C#]
public bool IsLinked {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


ProgId Property

Aspose.Words

FieldDdeAuto.ProgId Property

Gets or sets the application type of the link information.

[Visual Basic]
Public Property ProgId As String
[C#]
public string ProgId {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldDdeAuto.SourceFullName Property

Gets or sets the name and location of the source file.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


SourceItem Property

Aspose.Words

FieldDdeAuto.SourceItem Property

Gets or sets the portion of the source file that's being linked.

[Visual Basic]
Public Property SourceItem As String
[C#]
public string SourceItem {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldDdeAuto Class | Aspose.Words.Fields Namespace


FieldDisplayBarcode Class

Implements the DISPLAYBARCODE field.

For a list of all members of this type, see FieldDisplayBarcode Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDisplayBarcode

[Visual Basic]
Public Class FieldDisplayBarcode
Inherits Field
[C#]
public class FieldDisplayBarcode : Field

Remarks

Inserts a barcode.

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDisplayBarcode Members | Aspose.Words.Fields Namespace


FieldDisplayBarcode Members

FieldDisplayBarcode overview

Public Instance Constructors

FieldDisplayBarcode Constructor Initializes a new instance of the FieldDisplayBarcode class.

Public Instance Properties

AddStartStopChar | Gets or sets whether to add Start/Stop characters for barcode types NW7 and CODE39.
BackgroundColor | Gets or sets the background color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
BarcodeType | Gets or sets the barcode type (QR, etc.)
BarcodeValue | Gets or sets the barcode value.
CaseCodeStyle | Gets or sets the style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets whether to display barcode data (text) along with image.
End (inherited from Field) | Gets the node that represents the field end.
ErrorCorrectionLevel | Gets or sets an error correction level of QR Code. Valid values are [0, 3].
FixCheckDigit | Gets or sets whether to fix the check digit if it’s invalid.
ForegroundColor | Gets or sets the foreground color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PosCodeStyle | Gets or sets the style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScalingFactor | Gets or sets a scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000]
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SymbolHeight | Gets or sets the height of the symbol. The units are in TWIPS (1/1440 inch).
SymbolRotation | Gets or sets the rotation of the barcode symbol. Valid values are [0, 3]
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


FieldDisplayBarcode Constructor

Initializes a new instance of the FieldDisplayBarcode class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDisplayBarcode();

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


FieldDisplayBarcode Properties

The properties of the FieldDisplayBarcode class are listed below. For a complete list of FieldDisplayBarcode class members, see the FieldDisplayBarcode Members topic.

Public Instance Properties

AddStartStopChar | Gets or sets whether to add Start/Stop characters for barcode types NW7 and CODE39.
BackgroundColor | Gets or sets the background color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
BarcodeType | Gets or sets the barcode type (QR, etc.)
BarcodeValue | Gets or sets the barcode value.
CaseCodeStyle | Gets or sets the style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets whether to display barcode data (text) along with image.
End (inherited from Field) | Gets the node that represents the field end.
ErrorCorrectionLevel | Gets or sets an error correction level of QR Code. Valid values are [0, 3].
FixCheckDigit | Gets or sets whether to fix the check digit if it’s invalid.
ForegroundColor | Gets or sets the foreground color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PosCodeStyle | Gets or sets the style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScalingFactor | Gets or sets a scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000]
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SymbolHeight | Gets or sets the height of the symbol. The units are in TWIPS (1/1440 inch).
SymbolRotation | Gets or sets the rotation of the barcode symbol. Valid values are [0, 3]
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


AddStartStopChar Property

Aspose.Words

FieldDisplayBarcode.AddStartStopChar Property

Gets or sets whether to add Start/Stop characters for barcode types NW7 and CODE39.

[Visual Basic]
Public Property AddStartStopChar As Boolean
[C#]
public bool AddStartStopChar {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


BackgroundColor Property

Aspose.Words

FieldDisplayBarcode.BackgroundColor Property

Gets or sets the background color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]

[Visual Basic]
Public Property BackgroundColor As String
[C#]
public string BackgroundColor {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


BarcodeType Property

Aspose.Words

FieldDisplayBarcode.BarcodeType Property

Gets or sets the barcode type (QR, etc.)

[Visual Basic]
Public Property BarcodeType As String
[C#]
public string BarcodeType {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


BarcodeValue Property

Aspose.Words

FieldDisplayBarcode.BarcodeValue Property

Gets or sets the barcode value.

[Visual Basic]
Public Property BarcodeValue As String
[C#]
public string BarcodeValue {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


CaseCodeStyle Property

Aspose.Words

FieldDisplayBarcode.CaseCodeStyle Property

Gets or sets the style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]

[Visual Basic]
Public Property CaseCodeStyle As String
[C#]
public string CaseCodeStyle {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


DisplayText Property

Aspose.Words

FieldDisplayBarcode.DisplayText Property

Gets or sets whether to display barcode data (text) along with image.

[Visual Basic]
Public Property DisplayText As Boolean
[C#]
public bool DisplayText {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


ErrorCorrectionLevel Property

Aspose.Words

FieldDisplayBarcode.ErrorCorrectionLevel Property

Gets or sets an error correction level of QR Code. Valid values are [0, 3].

[Visual Basic]
Public Property ErrorCorrectionLevel As String
[C#]
public string ErrorCorrectionLevel {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


FixCheckDigit Property

Aspose.Words

FieldDisplayBarcode.FixCheckDigit Property

Gets or sets whether to fix the check digit if it’s invalid.

[Visual Basic]
Public Property FixCheckDigit As Boolean
[C#]
public bool FixCheckDigit {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


ForegroundColor Property

Aspose.Words

FieldDisplayBarcode.ForegroundColor Property

Gets or sets the foreground color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]

[Visual Basic]
Public Property ForegroundColor As String
[C#]
public string ForegroundColor {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


PosCodeStyle Property

Aspose.Words

FieldDisplayBarcode.PosCodeStyle Property

Gets or sets the style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].

[Visual Basic]
Public Property PosCodeStyle As String
[C#]
public string PosCodeStyle {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


ScalingFactor Property

Aspose.Words

FieldDisplayBarcode.ScalingFactor Property

Gets or sets a scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000]

[Visual Basic]
Public Property ScalingFactor As String
[C#]
public string ScalingFactor {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


SymbolHeight Property

Aspose.Words

FieldDisplayBarcode.SymbolHeight Property

Gets or sets the height of the symbol. The units are in TWIPS (1/1440 inch).

[Visual Basic]
Public Property SymbolHeight As String
[C#]
public string SymbolHeight {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


SymbolRotation Property

Aspose.Words

FieldDisplayBarcode.SymbolRotation Property

Gets or sets the rotation of the barcode symbol. Valid values are [0, 3]

[Visual Basic]
Public Property SymbolRotation As String
[C#]
public string SymbolRotation {get; set;}

Example

Shows how to insert a DISPLAYBARCODE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldDisplayBarcode field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);

// Insert a QR code
field.BarcodeType = "QR";
field.BarcodeValue = "ABC123";
field.BackgroundColor = "0xF8BD69";
field.ForegroundColor = "0xB5413B";
field.ErrorCorrectionLevel = "3";
field.ScalingFactor = "250";
field.SymbolHeight = "1000";
field.SymbolRotation = "0";

Assert.AreEqual(" DISPLAYBARCODE  ABC123 QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0", field.GetFieldCode());
builder.Writeln();

// insert a EAN13 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "EAN13";
field.BarcodeValue = "501234567890";
field.DisplayText = true;
field.PosCodeStyle = "CASE";
field.FixCheckDigit = true;

Assert.AreEqual(" DISPLAYBARCODE  501234567890 EAN13 \\t \\p CASE \\x", field.GetFieldCode());
builder.Writeln();

// insert a CODE39 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "CODE39";
field.BarcodeValue = "12345ABCDE";
field.AddStartStopChar = true;

Assert.AreEqual(" DISPLAYBARCODE  12345ABCDE CODE39 \\d", field.GetFieldCode());
builder.Writeln();

// insert a ITF14 barcode
field = (FieldDisplayBarcode)builder.InsertField(FieldType.FieldDisplayBarcode, true);
field.BarcodeType = "ITF14";
field.BarcodeValue = "09312345678907";
field.CaseCodeStyle = "STD";

Assert.AreEqual(" DISPLAYBARCODE  09312345678907 ITF14 \\c STD", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.DisplayBarcode.docx");

See Also

FieldDisplayBarcode Class | Aspose.Words.Fields Namespace


FieldDocProperty Class

Implements the DOCPROPERTY field.

For a list of all members of this type, see FieldDocProperty Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDocProperty

[Visual Basic]
Public Class FieldDocProperty
Inherits Field
[C#]
public class FieldDocProperty : Field

Remarks

Retrieves the indicated document information.

Example

Shows how to use fields to display document properties and variables.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set the value of a document property
doc.BuiltInDocumentProperties.Category = "My category";

// Display the value of that property with a DOCPROPERTY field
FieldDocProperty fieldDocProperty = (FieldDocProperty)builder.InsertField(" DOCPROPERTY Category ");
fieldDocProperty.Update();

Assert.AreEqual(" DOCPROPERTY Category ", fieldDocProperty.GetFieldCode());
Assert.AreEqual("My category", fieldDocProperty.Result);

builder.Writeln();

// While the set of a document's properties is fixed, we can add, name and define our own values in the variables collection
Assert.That(doc.Variables, Is.Empty);
doc.Variables.Add("My variable", "My variable's value");

// We can access a variable using its name and display it with a DOCVARIABLE field
FieldDocVariable fieldDocVariable = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);
fieldDocVariable.VariableName = "My Variable";
fieldDocVariable.Update();

Assert.AreEqual(" DOCVARIABLE  \"My Variable\"", fieldDocVariable.GetFieldCode());
Assert.AreEqual("My variable's value", fieldDocVariable.Result);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDocProperty Members | Aspose.Words.Fields Namespace


FieldDocProperty Members

FieldDocProperty overview

Public Instance Constructors

FieldDocProperty Constructor Initializes a new instance of the FieldDocProperty class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDocProperty Class | Aspose.Words.Fields Namespace


FieldDocProperty Constructor

Initializes a new instance of the FieldDocProperty class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDocProperty();

See Also

FieldDocProperty Class | Aspose.Words.Fields Namespace


FieldDocVariable Class

Implements DOCVARIABLE field.

For a list of all members of this type, see FieldDocVariable Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldDocVariable

[Visual Basic]
Public Class FieldDocVariable
Inherits Field
[C#]
public class FieldDocVariable : Field

Example

Shows how to use fields to display document properties and variables.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set the value of a document property
doc.BuiltInDocumentProperties.Category = "My category";

// Display the value of that property with a DOCPROPERTY field
FieldDocProperty fieldDocProperty = (FieldDocProperty)builder.InsertField(" DOCPROPERTY Category ");
fieldDocProperty.Update();

Assert.AreEqual(" DOCPROPERTY Category ", fieldDocProperty.GetFieldCode());
Assert.AreEqual("My category", fieldDocProperty.Result);

builder.Writeln();

// While the set of a document's properties is fixed, we can add, name and define our own values in the variables collection
Assert.That(doc.Variables, Is.Empty);
doc.Variables.Add("My variable", "My variable's value");

// We can access a variable using its name and display it with a DOCVARIABLE field
FieldDocVariable fieldDocVariable = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);
fieldDocVariable.VariableName = "My Variable";
fieldDocVariable.Update();

Assert.AreEqual(" DOCVARIABLE  \"My Variable\"", fieldDocVariable.GetFieldCode());
Assert.AreEqual("My variable's value", fieldDocVariable.Result);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldDocVariable Members | Aspose.Words.Fields Namespace


FieldDocVariable Members

FieldDocVariable overview

Public Instance Constructors

FieldDocVariable Constructor Initializes a new instance of the FieldDocVariable class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
VariableName | Gets or sets the name of the document variable to retrieve.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldDocVariable Class | Aspose.Words.Fields Namespace


FieldDocVariable Constructor

Initializes a new instance of the FieldDocVariable class.

[Visual Basic]
Public Sub New()
[C#]
public FieldDocVariable();

See Also

FieldDocVariable Class | Aspose.Words.Fields Namespace


FieldDocVariable Properties

The properties of the FieldDocVariable class are listed below. For a complete list of FieldDocVariable class members, see the FieldDocVariable Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
VariableName | Gets or sets the name of the document variable to retrieve.

See Also

FieldDocVariable Class | Aspose.Words.Fields Namespace


VariableName Property

Aspose.Words

FieldDocVariable.VariableName Property

Gets or sets the name of the document variable to retrieve.

[Visual Basic]
Public Property VariableName As String
[C#]
public string VariableName {get; set;}

Example

Shows how to use fields to display document properties and variables.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set the value of a document property
doc.BuiltInDocumentProperties.Category = "My category";

// Display the value of that property with a DOCPROPERTY field
FieldDocProperty fieldDocProperty = (FieldDocProperty)builder.InsertField(" DOCPROPERTY Category ");
fieldDocProperty.Update();

Assert.AreEqual(" DOCPROPERTY Category ", fieldDocProperty.GetFieldCode());
Assert.AreEqual("My category", fieldDocProperty.Result);

builder.Writeln();

// While the set of a document's properties is fixed, we can add, name and define our own values in the variables collection
Assert.That(doc.Variables, Is.Empty);
doc.Variables.Add("My variable", "My variable's value");

// We can access a variable using its name and display it with a DOCVARIABLE field
FieldDocVariable fieldDocVariable = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);
fieldDocVariable.VariableName = "My Variable";
fieldDocVariable.Update();

Assert.AreEqual(" DOCVARIABLE  \"My Variable\"", fieldDocVariable.GetFieldCode());
Assert.AreEqual("My variable's value", fieldDocVariable.Result);

See Also

FieldDocVariable Class | Aspose.Words.Fields Namespace


FieldEditTime Class

Implements the EDITTIME field.

For a list of all members of this type, see FieldEditTime Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldEditTime

[Visual Basic]
Public Class FieldEditTime
Inherits Field
[C#]
public class FieldEditTime : Field

Remarks

Retrieves the total editing time, in minutes, since the document was created.

Example

Shows how to use the EDITTIME field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert an EDITTIME field in the header
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("You've been editing this document for ");
FieldEditTime field = (FieldEditTime)builder.InsertField(FieldType.FieldEditTime, true);
builder.Writeln(" minutes.");

// The EDITTIME field will show, in minutes only,
// the time spent with the document open in a Microsoft Word window
// The minutes are tracked in a document property, which we can change like this
doc.BuiltInDocumentProperties.TotalEditingTime = 10;
field.Update();

Assert.AreEqual(" EDITTIME ", field.GetFieldCode());
Assert.AreEqual("10", field.Result);

// The field does not update in real time and will have to be manually updated in Microsoft Word also
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.EDITTIME.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldEditTime Members | Aspose.Words.Fields Namespace


FieldEditTime Members

FieldEditTime overview

Public Instance Constructors

FieldEditTime Constructor Initializes a new instance of the FieldEditTime class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldEditTime Class | Aspose.Words.Fields Namespace


FieldEditTime Constructor

Initializes a new instance of the FieldEditTime class.

[Visual Basic]
Public Sub New()
[C#]
public FieldEditTime();

See Also

FieldEditTime Class | Aspose.Words.Fields Namespace


FieldEmbed Class

Implements the EMBED field.

For a list of all members of this type, see FieldEmbed Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldEmbed

[Visual Basic]
Public Class FieldEmbed
Inherits Field
[C#]
public class FieldEmbed : Field

Example

Shows how some older Microsoft Word fields such as SHAPE and EMBED are handled.

[C#]

// Open a document that was created in Microsoft Word 2003
Document doc = new Document(MyDir + "Field.Legacy.doc");

// If we open the document in Word and press Alt+F9, we will see a SHAPE and an EMBED field
// A SHAPE field is the anchor/canvas for an autoshape object with the "In line with text" wrapping style enabled
// An EMBED field has the same function, but for an embedded object, such as a spreadsheet from an external Excel document
// However, these fields will not appear in the document's Fields collection
Assert.AreEqual(0, doc.Range.Fields.Count);

// These fields are supported only by old versions of Microsoft Word
// As such, they are converted into shapes during the document importation process and can instead be found in the collection of Shape nodes
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
Assert.AreEqual(3, shapes.Count);

// The first Shape node corresponds to what was the SHAPE field in the input document: the inline canvas for an autoshape
Shape shape = (Shape)shapes[0];
Assert.AreEqual(ShapeType.Image, shape.ShapeType);

// The next Shape node is the autoshape that is within the canvas
shape = (Shape)shapes[1];
Assert.AreEqual(ShapeType.Can, shape.ShapeType);

// The third Shape is what was the EMBED field that contained the external spreadsheet
shape = (Shape)shapes[2];
Assert.AreEqual(ShapeType.OleObject, shape.ShapeType);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldEmbed Members | Aspose.Words.Fields Namespace


FieldEmbed Members

FieldEmbed overview

Public Instance Constructors

FieldEmbed Constructor Initializes a new instance of the FieldEmbed class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldEmbed Class | Aspose.Words.Fields Namespace


FieldEmbed Constructor

Initializes a new instance of the FieldEmbed class.

[Visual Basic]
Public Sub New()
[C#]
public FieldEmbed();

See Also

FieldEmbed Class | Aspose.Words.Fields Namespace


FieldEnd Class

Represents an end of a Word field in a document.

For a list of all members of this type, see FieldEnd Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.Fields.FieldChar
Aspose.Words.Fields.FieldEnd

[Visual Basic]
Public Class FieldEnd
Inherits FieldChar
[C#]
public class FieldEnd : FieldChar

Remarks

FieldEnd is an inline-level node and represented by the FieldEndChar control character in the document.

FieldEnd can only be a child of Paragraph.

A complete field in a Microsoft Word document is a complex structure consisting of a field start character, field code, field separator character, field result and field end character. Some fields only have field start, field code and field end.

To easily insert a new field into a document, use the InsertField method.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldEnd Members | Aspose.Words.Fields Namespace


FieldEnd Members

FieldEnd overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType (inherited from FieldChar) | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
HasSeparator | Returns true if this field has a separator.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty (inherited from FieldChar) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked (inherited from FieldChar) | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns FieldEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField (inherited from FieldChar) | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldEnd Class | Aspose.Words.Fields Namespace


FieldEnd Properties

The properties of the FieldEnd class are listed below. For a complete list of FieldEnd class members, see the FieldEnd Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType (inherited from FieldChar) | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
HasSeparator | Returns true if this field has a separator.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty (inherited from FieldChar) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked (inherited from FieldChar) | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns FieldEnd.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

FieldEnd Class | Aspose.Words.Fields Namespace


HasSeparator Property

Aspose.Words

FieldEnd.HasSeparator Property

Returns true if this field has a separator.

[Visual Basic]
Public ReadOnly Property HasSeparator As Boolean
[C#]
public bool HasSeparator {get;}

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldEnd Class | Aspose.Words.Fields Namespace


NodeType Property

Aspose.Words

FieldEnd.NodeType Property

Returns FieldEnd.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

FieldEnd Class | Aspose.Words.Fields Namespace


FieldEnd Methods

The methods of the FieldEnd class are listed below. For a complete list of FieldEnd class members, see the FieldEnd Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField (inherited from FieldChar) | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldEnd Class | Aspose.Words.Fields Namespace


FieldEnd.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitFieldEnd.

For more info see the Visitor design pattern.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldEnd Class | Aspose.Words.Fields Namespace


FieldEQ Class

Implements the EQ field.

For a list of all members of this type, see FieldEQ Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldEQ

[Visual Basic]
Public Class FieldEQ
Inherits Field
[C#]
public class FieldEQ : Field

Example

Shows how to use the EQ field to display a variety of mathematical equations.

[C#]

public void FieldEQ()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // An EQ field displays a mathematical equation consisting of one or many elements
    // Each element takes the following form: [switch][options][arguments]
    // One switch, several possible options, followed by a set of argument values inside round braces

    // Here we use a document builder to insert an EQ field, with an "\f" switch, which corresponds to "Fraction"
    // No options are invoked, and the values 1 and 4 are passed as arguments
    // This field will display a fraction with 1 as the numerator and 4 as the denominator
    FieldEQ field = InsertFieldEQ(builder, @"\f(1,4)");

    Assert.AreEqual(@" EQ \f(1,4)", field.GetFieldCode());

    // One EQ field may contain multiple elements placed sequentially,
    // and elements may also be nested by being placed inside the argument brackets of other elements
    // The full list of switches and their corresponding options can be found here:
    // https://blogs.msdn.microsoft.com/murrays/2018/01/23/microsoft-word-eq-field/

    // Array switch "\a", aligned left, 2 columns, 3 points of horizontal and vertical spacing
    InsertFieldEQ(builder, @"\a \al \co2 \vs3 \hs3(4x,- 4y,-4x,+ y)");

    // Bracket switch "\b", bracket character "[", to enclose the contents in a set of square braces
    // Note that we are nesting an array inside the brackets, which will altogether look like a matrix in the output
    InsertFieldEQ(builder, @"\b \bc\[ (\a \al \co3 \vs3 \hs3(1,0,0,0,1,0,0,0,1))");

    // Displacement switch "\d", displacing text "B" 30 spaces to the right of "A", displaying the gap as an underline
    InsertFieldEQ(builder, @"A \d \fo30 \li() B");

    // Formula consisting of multiple fractions
    InsertFieldEQ(builder, @"\f(d,dx)(u + v) = \f(du,dx) + \f(dv,dx)");

    // Integral switch "\i", with a summation symbol
    InsertFieldEQ(builder, @"\i \su(n=1,5,n)");

    // List switch "\l"
    InsertFieldEQ(builder, @"\l(1,1,2,3,n,8,13)");

    // Radical switch "\r", displaying a cubed root of x
    InsertFieldEQ(builder, @"\r (3,x)");

    // Subscript/superscript switch "/s", first as a superscript and then as a subscript
    InsertFieldEQ(builder, @"\s \up8(Superscript) Text \s \do8(Subscript)");

    // Box switch "\x", with lines at the top, bottom, left and right of the input
    InsertFieldEQ(builder, @"\x \to \bo \le \ri(5)");

    // More complex combinations
    InsertFieldEQ(builder, @"\a \ac \vs1 \co1(lim,n→∞) \b (\f(n,n2 + 12) + \f(n,n2 + 22) + ... + \f(n,n2 + n2))");
    InsertFieldEQ(builder, @"\i (,,  \b(\f(x,x2 + 3x + 2))) \s \up10(2)");
    InsertFieldEQ(builder, @"\i \in( tan x, \s \up2(sec x), \b(\r(3) )\s \up4(t) \s \up7(2)  dt)");

    doc.Save(ArtifactsDir + "Field.EQ.docx");
}

/// <summary>
/// Use a document builder to insert an EQ field, set its arguments and start a new paragraph
/// </summary>
private FieldEQ InsertFieldEQ(DocumentBuilder builder, string args)
{
    FieldEQ field = (FieldEQ)builder.InsertField(FieldType.FieldEquation, true);
    builder.MoveTo(field.Separator);
    builder.Write(args);
    builder.MoveTo(field.Start.ParentNode);

    builder.InsertParagraph();
    return field;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldEQ Members | Aspose.Words.Fields Namespace


FieldEQ Members

FieldEQ overview

Public Instance Constructors

FieldEQ Constructor Initializes a new instance of the FieldEQ class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldEQ Class | Aspose.Words.Fields Namespace


FieldEQ Constructor

Initializes a new instance of the FieldEQ class.

[Visual Basic]
Public Sub New()
[C#]
public FieldEQ();

See Also

FieldEQ Class | Aspose.Words.Fields Namespace


FieldFileName Class

Implements the FILENAME field.

For a list of all members of this type, see FieldFileName Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFileName

[Visual Basic]
Public Class FieldFileName
Inherits Field
[C#]
public class FieldFileName : Field

Remarks

Retrieves the name of the current document from its storage location.

In the current implementation, uses the OriginalFileName property to retrieve the file name. If the document was loaded from a stream or created blank, uses the name of the file that is being saved to (if known).

Example

Shows how to use FieldOptions to override the default value for the FILENAME field.

[C#]

Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToDocumentEnd();
builder.Writeln();

// This FILENAME field will display the file name of the document we opened
FieldFileName field = (FieldFileName)builder.InsertField(FieldType.FieldFileName, true);
field.Update();

Assert.AreEqual(" FILENAME ", field.GetFieldCode());
Assert.AreEqual("Document.docx", field.Result);

builder.Writeln();

// By default, the FILENAME field does not show the full path, and we can change this
field = (FieldFileName)builder.InsertField(FieldType.FieldFileName, true);
field.IncludeFullPath = true;

// We can override the values displayed by our FILENAME fields by setting this attribute
Assert.IsNull(doc.FieldOptions.FileName);
doc.FieldOptions.FileName = "Field.FileName.docx";
field.Update();

Assert.AreEqual(" FILENAME  \\p", field.GetFieldCode());
Assert.AreEqual("Field.FileName.docx", field.Result);

doc.UpdateFields();
doc.Save(ArtifactsDir + "" + doc.FieldOptions.FileName);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFileName Members | Aspose.Words.Fields Namespace


FieldFileName Members

FieldFileName overview

Public Instance Constructors

FieldFileName Constructor Initializes a new instance of the FieldFileName class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IncludeFullPath | Gets or sets whether to include the full file path name.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFileName Class | Aspose.Words.Fields Namespace


FieldFileName Constructor

Initializes a new instance of the FieldFileName class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFileName();

See Also

FieldFileName Class | Aspose.Words.Fields Namespace


FieldFileName Properties

The properties of the FieldFileName class are listed below. For a complete list of FieldFileName class members, see the FieldFileName Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IncludeFullPath | Gets or sets whether to include the full file path name.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldFileName Class | Aspose.Words.Fields Namespace


IncludeFullPath Property

Aspose.Words

FieldFileName.IncludeFullPath Property

Gets or sets whether to include the full file path name.

[Visual Basic]
Public Property IncludeFullPath As Boolean
[C#]
public bool IncludeFullPath {get; set;}

Example

Shows how to use FieldOptions to override the default value for the FILENAME field.

[C#]

Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToDocumentEnd();
builder.Writeln();

// This FILENAME field will display the file name of the document we opened
FieldFileName field = (FieldFileName)builder.InsertField(FieldType.FieldFileName, true);
field.Update();

Assert.AreEqual(" FILENAME ", field.GetFieldCode());
Assert.AreEqual("Document.docx", field.Result);

builder.Writeln();

// By default, the FILENAME field does not show the full path, and we can change this
field = (FieldFileName)builder.InsertField(FieldType.FieldFileName, true);
field.IncludeFullPath = true;

// We can override the values displayed by our FILENAME fields by setting this attribute
Assert.IsNull(doc.FieldOptions.FileName);
doc.FieldOptions.FileName = "Field.FileName.docx";
field.Update();

Assert.AreEqual(" FILENAME  \\p", field.GetFieldCode());
Assert.AreEqual("Field.FileName.docx", field.Result);

doc.UpdateFields();
doc.Save(ArtifactsDir + "" + doc.FieldOptions.FileName);

See Also

FieldFileName Class | Aspose.Words.Fields Namespace


FieldFileSize Class

Implements the FILESIZE field.

For a list of all members of this type, see FieldFileSize Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFileSize

[Visual Basic]
Public Class FieldFileSize
Inherits Field
[C#]
public class FieldFileSize : Field

Remarks

Retrieves the size of the current document's file or 0 if the size cannot be determined.

In the current implementation, uses the OriginalFileName property to retrieve the file name used to determine the file size.

Example

Shows how to display the file size of a document with a FILESIZE field.

[C#]

Document doc = new Document(MyDir + "Document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();

// By default, file size is displayed in bytes
FieldFileSize field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.Update();
Assert.AreEqual("23040", field.Result);

// Set the field to display size in kilobytes
field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.IsInKilobytes = true;
field.Update();
Assert.AreEqual("23", field.Result);

// Set the field to display size in megabytes
field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.IsInMegabytes = true;
field.Update();
Assert.AreEqual("0", field.Result);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFileSize Members | Aspose.Words.Fields Namespace


FieldFileSize Members

FieldFileSize overview

Public Instance Constructors

FieldFileSize Constructor Initializes a new instance of the FieldFileSize class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsInKilobytes | Gets or sets whether to display the file size in kilobytes.
IsInMegabytes | Gets or sets whether to display the file size in megabytes.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFileSize Class | Aspose.Words.Fields Namespace


FieldFileSize Constructor

Initializes a new instance of the FieldFileSize class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFileSize();

See Also

FieldFileSize Class | Aspose.Words.Fields Namespace


FieldFileSize Properties

The properties of the FieldFileSize class are listed below. For a complete list of FieldFileSize class members, see the FieldFileSize Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsInKilobytes | Gets or sets whether to display the file size in kilobytes.
IsInMegabytes | Gets or sets whether to display the file size in megabytes.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldFileSize Class | Aspose.Words.Fields Namespace


IsInKilobytes Property

Aspose.Words

FieldFileSize.IsInKilobytes Property

Gets or sets whether to display the file size in kilobytes.

[Visual Basic]
Public Property IsInKilobytes As Boolean
[C#]
public bool IsInKilobytes {get; set;}

Example

Shows how to display the file size of a document with a FILESIZE field.

[C#]

Document doc = new Document(MyDir + "Document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();

// By default, file size is displayed in bytes
FieldFileSize field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.Update();
Assert.AreEqual("23040", field.Result);

// Set the field to display size in kilobytes
field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.IsInKilobytes = true;
field.Update();
Assert.AreEqual("23", field.Result);

// Set the field to display size in megabytes
field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.IsInMegabytes = true;
field.Update();
Assert.AreEqual("0", field.Result);

See Also

FieldFileSize Class | Aspose.Words.Fields Namespace


IsInMegabytes Property

Aspose.Words

FieldFileSize.IsInMegabytes Property

Gets or sets whether to display the file size in megabytes.

[Visual Basic]
Public Property IsInMegabytes As Boolean
[C#]
public bool IsInMegabytes {get; set;}

Example

Shows how to display the file size of a document with a FILESIZE field.

[C#]

Document doc = new Document(MyDir + "Document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();

// By default, file size is displayed in bytes
FieldFileSize field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.Update();
Assert.AreEqual("23040", field.Result);

// Set the field to display size in kilobytes
field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.IsInKilobytes = true;
field.Update();
Assert.AreEqual("23", field.Result);

// Set the field to display size in megabytes
field = (FieldFileSize)builder.InsertField(FieldType.FieldFileSize, true);
field.IsInMegabytes = true;
field.Update();
Assert.AreEqual("0", field.Result);

See Also

FieldFileSize Class | Aspose.Words.Fields Namespace


FieldFillIn Class

Implements the FILLIN field.

For a list of all members of this type, see FieldFillIn Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFillIn

[Visual Basic]
Public Class FieldFillIn
Inherits Field
[C#]
public class FieldFillIn : Field

Remarks

Prompts the user to enter text.

Example

Shows how to use the FILLIN field to prompt the user for a response.

[C#]

public void FieldFillIn()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a FILLIN field with a document builder
    FieldFillIn field = (FieldFillIn)builder.InsertField(FieldType.FieldFillIn, true);
    field.PromptText = "Please enter a response:";
    field.DefaultResponse = "A default response";

    // Set this to prompt the user for a response when a mail merge is performed
    field.PromptOnceOnMailMerge = true;

    Assert.AreEqual(" FILLIN  \"Please enter a response:\" \\d \"A default response\" \\o", field.GetFieldCode());

    // Perform a simple mail merge
    FieldMergeField mergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    mergeField.FieldName = "MergeField";

    doc.FieldOptions.UserPromptRespondent = new PromptRespondent();
    doc.MailMerge.Execute(new [] { "MergeField" }, new object[] { "" });

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FillIn.docx");
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an FILLIN field during a mail merge
/// </summary>
private class PromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from PromptRespondent. " + defaultResponse;
    }
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFillIn Members | Aspose.Words.Fields Namespace


FieldFillIn Members

FieldFillIn overview

Public Instance Constructors

FieldFillIn Constructor Initializes a new instance of the FieldFillIn class.

Public Instance Properties

DefaultResponse | Gets or sets default user response (initial value contained in the prompt window).
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PromptOnceOnMailMerge | Gets or sets whether the user response should be recieved once per a mail merge operation.
PromptText | Gets or sets the prompt text (the title of the prompt window).
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFillIn Class | Aspose.Words.Fields Namespace


FieldFillIn Constructor

Initializes a new instance of the FieldFillIn class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFillIn();

See Also

FieldFillIn Class | Aspose.Words.Fields Namespace


FieldFillIn Properties

The properties of the FieldFillIn class are listed below. For a complete list of FieldFillIn class members, see the FieldFillIn Members topic.

Public Instance Properties

DefaultResponse | Gets or sets default user response (initial value contained in the prompt window).
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PromptOnceOnMailMerge | Gets or sets whether the user response should be recieved once per a mail merge operation.
PromptText | Gets or sets the prompt text (the title of the prompt window).
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldFillIn Class | Aspose.Words.Fields Namespace


DefaultResponse Property

Aspose.Words

FieldFillIn.DefaultResponse Property

Gets or sets default user response (initial value contained in the prompt window).

[Visual Basic]
Public Property DefaultResponse As String
[C#]
public string DefaultResponse {get; set;}

Example

Shows how to use the FILLIN field to prompt the user for a response.

[C#]

public void FieldFillIn()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a FILLIN field with a document builder
    FieldFillIn field = (FieldFillIn)builder.InsertField(FieldType.FieldFillIn, true);
    field.PromptText = "Please enter a response:";
    field.DefaultResponse = "A default response";

    // Set this to prompt the user for a response when a mail merge is performed
    field.PromptOnceOnMailMerge = true;

    Assert.AreEqual(" FILLIN  \"Please enter a response:\" \\d \"A default response\" \\o", field.GetFieldCode());

    // Perform a simple mail merge
    FieldMergeField mergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    mergeField.FieldName = "MergeField";

    doc.FieldOptions.UserPromptRespondent = new PromptRespondent();
    doc.MailMerge.Execute(new [] { "MergeField" }, new object[] { "" });

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FillIn.docx");
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an FILLIN field during a mail merge
/// </summary>
private class PromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from PromptRespondent. " + defaultResponse;
    }
}

See Also

FieldFillIn Class | Aspose.Words.Fields Namespace


PromptOnceOnMailMerge Property

Aspose.Words

FieldFillIn.PromptOnceOnMailMerge Property

Gets or sets whether the user response should be recieved once per a mail merge operation.

[Visual Basic]
Public Property PromptOnceOnMailMerge As Boolean
[C#]
public bool PromptOnceOnMailMerge {get; set;}

Example

Shows how to use the FILLIN field to prompt the user for a response.

[C#]

public void FieldFillIn()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a FILLIN field with a document builder
    FieldFillIn field = (FieldFillIn)builder.InsertField(FieldType.FieldFillIn, true);
    field.PromptText = "Please enter a response:";
    field.DefaultResponse = "A default response";

    // Set this to prompt the user for a response when a mail merge is performed
    field.PromptOnceOnMailMerge = true;

    Assert.AreEqual(" FILLIN  \"Please enter a response:\" \\d \"A default response\" \\o", field.GetFieldCode());

    // Perform a simple mail merge
    FieldMergeField mergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    mergeField.FieldName = "MergeField";

    doc.FieldOptions.UserPromptRespondent = new PromptRespondent();
    doc.MailMerge.Execute(new [] { "MergeField" }, new object[] { "" });

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FillIn.docx");
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an FILLIN field during a mail merge
/// </summary>
private class PromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from PromptRespondent. " + defaultResponse;
    }
}

See Also

FieldFillIn Class | Aspose.Words.Fields Namespace


PromptText Property

Aspose.Words

FieldFillIn.PromptText Property

Gets or sets the prompt text (the title of the prompt window).

[Visual Basic]
Public Property PromptText As String
[C#]
public string PromptText {get; set;}

Example

Shows how to use the FILLIN field to prompt the user for a response.

[C#]

public void FieldFillIn()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a FILLIN field with a document builder
    FieldFillIn field = (FieldFillIn)builder.InsertField(FieldType.FieldFillIn, true);
    field.PromptText = "Please enter a response:";
    field.DefaultResponse = "A default response";

    // Set this to prompt the user for a response when a mail merge is performed
    field.PromptOnceOnMailMerge = true;

    Assert.AreEqual(" FILLIN  \"Please enter a response:\" \\d \"A default response\" \\o", field.GetFieldCode());

    // Perform a simple mail merge
    FieldMergeField mergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    mergeField.FieldName = "MergeField";

    doc.FieldOptions.UserPromptRespondent = new PromptRespondent();
    doc.MailMerge.Execute(new [] { "MergeField" }, new object[] { "" });

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FillIn.docx");
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an FILLIN field during a mail merge
/// </summary>
private class PromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from PromptRespondent. " + defaultResponse;
    }
}

See Also

FieldFillIn Class | Aspose.Words.Fields Namespace


FieldFootnoteRef Class

Implements the FOOTNOTEREF field.

For a list of all members of this type, see FieldFootnoteRef Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFootnoteRef

[Visual Basic]
Public Class FieldFootnoteRef
Inherits Field
[C#]
public class FieldFootnoteRef : Field

Example

Shows how to cross-reference footnotes with the FOOTNOTEREF field

[C#]

// Create a blank document and a document builder for it
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert some text, and a footnote, all inside a bookmark named "CrossRefBookmark"
builder.StartBookmark("CrossRefBookmark");
builder.Write("Hello world!");
builder.InsertFootnote(FootnoteType.Footnote, "Cross referenced footnote.");
builder.EndBookmark("CrossRefBookmark");

builder.InsertParagraph();
builder.Write("CrossReference: ");

// Insert a FOOTNOTEREF field, which lets us reference a footnote more than once while re-using the same footnote marker
//Field field = builder.insertField(" ftnref ");
FieldFootnoteRef field = (FieldFootnoteRef) builder.InsertField(FieldType.FieldFootnoteRef, true);

// Get this field to reference a bookmark
// The bookmark that we chose contains a footnote marker belonging to the footnote we inserted, which will be displayed by the field, just by itself
builder.MoveTo(field.Separator);
builder.Write("CrossRefBookmark");

Assert.AreEqual(field.GetFieldCode(), " FOOTNOTEREF CrossRefBookmark");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FootnoteRef.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFootnoteRef Members | Aspose.Words.Fields Namespace


FieldFootnoteRef Members

FieldFootnoteRef overview

Public Instance Constructors

FieldFootnoteRef Constructor Initializes a new instance of the FieldFootnoteRef class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFootnoteRef Class | Aspose.Words.Fields Namespace


FieldFootnoteRef Constructor

Initializes a new instance of the FieldFootnoteRef class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFootnoteRef();

See Also

FieldFootnoteRef Class | Aspose.Words.Fields Namespace


FieldFormat Class

Provides typed access to field's numeric, date and time, and general formatting.

For a list of all members of this type, see FieldFormat Members.

System.Object
Aspose.Words.Fields.FieldFormat

[Visual Basic]
Public Class FieldFormat
[C#]
public class FieldFormat

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFormat Members | Aspose.Words.Fields Namespace


FieldFormat Members

FieldFormat overview

Public Instance Properties

DateTimeFormat | Gets or sets a formatting that is applied to a date and time field result. Corresponds to the \@ switch.
GeneralFormats | Gets a collection of general formats that are applied to a numeric, text or any field result. Corresponds to the \* switches.
NumericFormat | Gets or sets a formatting that is applied to a numeric field result. Corresponds to the \# switch.

See Also

FieldFormat Class | Aspose.Words.Fields Namespace


FieldFormat Properties

The properties of the FieldFormat class are listed below. For a complete list of FieldFormat class members, see the FieldFormat Members topic.

Public Instance Properties

DateTimeFormat | Gets or sets a formatting that is applied to a date and time field result. Corresponds to the \@ switch.
GeneralFormats | Gets a collection of general formats that are applied to a numeric, text or any field result. Corresponds to the \* switches.
NumericFormat | Gets or sets a formatting that is applied to a numeric field result. Corresponds to the \# switch.

See Also

FieldFormat Class | Aspose.Words.Fields Namespace


DateTimeFormat Property

Aspose.Words

FieldFormat.DateTimeFormat Property

Gets or sets a formatting that is applied to a date and time field result. Corresponds to the \@ switch.

[Visual Basic]
Public Property DateTimeFormat As String
[C#]
public string DateTimeFormat {get; set;}

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

FieldFormat Class | Aspose.Words.Fields Namespace


GeneralFormats Property

Aspose.Words

FieldFormat.GeneralFormats Property

Gets a collection of general formats that are applied to a numeric, text or any field result. Corresponds to the \* switches.

[Visual Basic]
Public ReadOnly Property GeneralFormats As GeneralFormatCollection
[C#]
public GeneralFormatCollection GeneralFormats {get;}

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

FieldFormat Class | Aspose.Words.Fields Namespace


NumericFormat Property

Aspose.Words

FieldFormat.NumericFormat Property

Gets or sets a formatting that is applied to a numeric field result. Corresponds to the \# switch.

[Visual Basic]
Public Property NumericFormat As String
[C#]
public string NumericFormat {get; set;}

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

FieldFormat Class | Aspose.Words.Fields Namespace


FieldFormCheckBox Class

Implements the FORMCHECKBOX field.

For a list of all members of this type, see FieldFormCheckBox Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFormCheckBox

[Visual Basic]
Public Class FieldFormCheckBox
Inherits Field
[C#]
public class FieldFormCheckBox : Field

Remarks

Inserts a check box style form field.

Example

Shows how to process FORMCHECKBOX, FORMDROPDOWN and FORMTEXT fields.

[C#]

// These fields are legacy equivalents of the FormField, and they can be read and not inserted by Aspose.Words,
// and are inserted in Microsoft Word 2019 via the Legacy Tools menu in the Developer tab
Document doc = new Document(MyDir + "Field.FieldForms.doc");

FieldFormCheckBox fieldFormCheckBox = (FieldFormCheckBox)doc.Range.Fields[1];
Assert.AreEqual(" FORMCHECKBOX \u0001", fieldFormCheckBox.GetFieldCode());

FieldFormDropDown fieldFormDropDown = (FieldFormDropDown)doc.Range.Fields[2];
Assert.AreEqual(" FORMDROPDOWN \u0001", fieldFormDropDown.GetFieldCode());

FieldFormText fieldFormText = (FieldFormText)doc.Range.Fields[0];
Assert.AreEqual(" FORMTEXT \u0001", fieldFormText.GetFieldCode());

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFormCheckBox Members | Aspose.Words.Fields Namespace


FieldFormCheckBox Members

FieldFormCheckBox overview

Public Instance Constructors

FieldFormCheckBox Constructor Initializes a new instance of the FieldFormCheckBox class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFormCheckBox Class | Aspose.Words.Fields Namespace


FieldFormCheckBox Constructor

Initializes a new instance of the FieldFormCheckBox class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFormCheckBox();

See Also

FieldFormCheckBox Class | Aspose.Words.Fields Namespace


FieldFormDropDown Class

Implements the FORMDROPDOWN field.

For a list of all members of this type, see FieldFormDropDown Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFormDropDown

[Visual Basic]
Public Class FieldFormDropDown
Inherits Field
[C#]
public class FieldFormDropDown : Field

Remarks

Inserts a drop-down list style form field.

Example

Shows how to process FORMCHECKBOX, FORMDROPDOWN and FORMTEXT fields.

[C#]

// These fields are legacy equivalents of the FormField, and they can be read and not inserted by Aspose.Words,
// and are inserted in Microsoft Word 2019 via the Legacy Tools menu in the Developer tab
Document doc = new Document(MyDir + "Field.FieldForms.doc");

FieldFormCheckBox fieldFormCheckBox = (FieldFormCheckBox)doc.Range.Fields[1];
Assert.AreEqual(" FORMCHECKBOX \u0001", fieldFormCheckBox.GetFieldCode());

FieldFormDropDown fieldFormDropDown = (FieldFormDropDown)doc.Range.Fields[2];
Assert.AreEqual(" FORMDROPDOWN \u0001", fieldFormDropDown.GetFieldCode());

FieldFormText fieldFormText = (FieldFormText)doc.Range.Fields[0];
Assert.AreEqual(" FORMTEXT \u0001", fieldFormText.GetFieldCode());

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFormDropDown Members | Aspose.Words.Fields Namespace


FieldFormDropDown Members

FieldFormDropDown overview

Public Instance Constructors

FieldFormDropDown Constructor Initializes a new instance of the FieldFormDropDown class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFormDropDown Class | Aspose.Words.Fields Namespace


FieldFormDropDown Constructor

Initializes a new instance of the FieldFormDropDown class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFormDropDown();

See Also

FieldFormDropDown Class | Aspose.Words.Fields Namespace


FieldFormText Class

Implements the FORMTEXT field.

For a list of all members of this type, see FieldFormText Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFormText

[Visual Basic]
Public Class FieldFormText
Inherits Field
[C#]
public class FieldFormText : Field

Remarks

Inserts a text box style form field.

Example

Shows how to process FORMCHECKBOX, FORMDROPDOWN and FORMTEXT fields.

[C#]

// These fields are legacy equivalents of the FormField, and they can be read and not inserted by Aspose.Words,
// and are inserted in Microsoft Word 2019 via the Legacy Tools menu in the Developer tab
Document doc = new Document(MyDir + "Field.FieldForms.doc");

FieldFormCheckBox fieldFormCheckBox = (FieldFormCheckBox)doc.Range.Fields[1];
Assert.AreEqual(" FORMCHECKBOX \u0001", fieldFormCheckBox.GetFieldCode());

FieldFormDropDown fieldFormDropDown = (FieldFormDropDown)doc.Range.Fields[2];
Assert.AreEqual(" FORMDROPDOWN \u0001", fieldFormDropDown.GetFieldCode());

FieldFormText fieldFormText = (FieldFormText)doc.Range.Fields[0];
Assert.AreEqual(" FORMTEXT \u0001", fieldFormText.GetFieldCode());

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFormText Members | Aspose.Words.Fields Namespace


FieldFormText Members

FieldFormText overview

Public Instance Constructors

FieldFormText Constructor Initializes a new instance of the FieldFormText class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFormText Class | Aspose.Words.Fields Namespace


FieldFormText Constructor

Initializes a new instance of the FieldFormText class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFormText();

See Also

FieldFormText Class | Aspose.Words.Fields Namespace


FieldFormula Class

Implements the = (formula) field.

For a list of all members of this type, see FieldFormula Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldFormula

[Visual Basic]
Public Class FieldFormula
Inherits Field
[C#]
public class FieldFormula : Field

Remarks

Calcualtes the result of an expression.

Example

Shows how to use the "=" field.

[C#]

Document doc = new Document();

// Create a formula field using a field builder
FieldBuilder fieldBuilder = new FieldBuilder(FieldType.FieldFormula);
fieldBuilder.AddArgument(2);
fieldBuilder.AddArgument("*");
fieldBuilder.AddArgument(5);

FieldFormula field = (FieldFormula)fieldBuilder.BuildAndInsert(doc.FirstSection.Body.FirstParagraph);
field.Update();

Assert.AreEqual(" = 2 * 5 ", field.GetFieldCode());
Assert.AreEqual("10", field.Result);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FORMULA.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldFormula Members | Aspose.Words.Fields Namespace


FieldFormula Members

FieldFormula overview

Public Instance Constructors

FieldFormula Constructor Initializes a new instance of the FieldFormula class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldFormula Class | Aspose.Words.Fields Namespace


FieldFormula Constructor

Initializes a new instance of the FieldFormula class.

[Visual Basic]
Public Sub New()
[C#]
public FieldFormula();

See Also

FieldFormula Class | Aspose.Words.Fields Namespace


FieldGlossary Class

Implements the GLOSSARY field.

For a list of all members of this type, see FieldGlossary Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldGlossary

[Visual Basic]
Public Class FieldGlossary
Inherits Field
[C#]
public class FieldGlossary : Field

Remarks

Inserts a glossary entry.

Example

Shows how to insert a building block into a document and display it with AUTOTEXT and GLOSSARY fields.

[C#]

Document doc = new Document();

// Create a glossary document and add an AutoText building block
doc.GlossaryDocument = new GlossaryDocument();
BuildingBlock buildingBlock = new BuildingBlock(doc.GlossaryDocument);
buildingBlock.Name = "MyBlock";
buildingBlock.Gallery = BuildingBlockGallery.AutoText;
buildingBlock.Category = "General";
buildingBlock.Description = "MyBlock description";
buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;
doc.GlossaryDocument.AppendChild(buildingBlock);

// Create a source and add it as text content to our building block
Document buildingBlockSource = new Document();
DocumentBuilder buildingBlockSourceBuilder = new DocumentBuilder(buildingBlockSource);
buildingBlockSourceBuilder.Writeln("Hello World!");

Node buildingBlockContent = doc.GlossaryDocument.ImportNode(buildingBlockSource.FirstSection, true);
buildingBlock.AppendChild(buildingBlockContent);

// Create an advance field using document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldAutoText fieldAutoText = (FieldAutoText)builder.InsertField(FieldType.FieldAutoText, true);

// Refer to our building block by name
fieldAutoText.EntryName = "MyBlock";

Assert.AreEqual(" AUTOTEXT  MyBlock", fieldAutoText.GetFieldCode());

// Put additional templates here
doc.FieldOptions.BuiltInTemplatesPaths = new[] { MyDir + "Document.BusinessBrochureTemplate.dotx" };

// We can also display our building block with a GLOSSARY field
FieldGlossary fieldGlossary = (FieldGlossary)builder.InsertField(FieldType.FieldGlossary, true);
fieldGlossary.EntryName = "MyBlock";

Assert.AreEqual(" GLOSSARY  MyBlock", fieldGlossary.GetFieldCode());

// The text content of our building block will be visible in the output
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.AutoText.dotx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldGlossary Members | Aspose.Words.Fields Namespace


FieldGlossary Members

FieldGlossary overview

Public Instance Constructors

FieldGlossary Constructor Initializes a new instance of the FieldGlossary class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryName | Gets or sets the name of the glossary entry to insert.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldGlossary Class | Aspose.Words.Fields Namespace


FieldGlossary Constructor

Initializes a new instance of the FieldGlossary class.

[Visual Basic]
Public Sub New()
[C#]
public FieldGlossary();

See Also

FieldGlossary Class | Aspose.Words.Fields Namespace


FieldGlossary Properties

The properties of the FieldGlossary class are listed below. For a complete list of FieldGlossary class members, see the FieldGlossary Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryName | Gets or sets the name of the glossary entry to insert.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldGlossary Class | Aspose.Words.Fields Namespace


EntryName Property

Aspose.Words

FieldGlossary.EntryName Property

Gets or sets the name of the glossary entry to insert.

[Visual Basic]
Public Property EntryName As String
[C#]
public string EntryName {get; set;}

Example

Shows how to insert a building block into a document and display it with AUTOTEXT and GLOSSARY fields.

[C#]

Document doc = new Document();

// Create a glossary document and add an AutoText building block
doc.GlossaryDocument = new GlossaryDocument();
BuildingBlock buildingBlock = new BuildingBlock(doc.GlossaryDocument);
buildingBlock.Name = "MyBlock";
buildingBlock.Gallery = BuildingBlockGallery.AutoText;
buildingBlock.Category = "General";
buildingBlock.Description = "MyBlock description";
buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;
doc.GlossaryDocument.AppendChild(buildingBlock);

// Create a source and add it as text content to our building block
Document buildingBlockSource = new Document();
DocumentBuilder buildingBlockSourceBuilder = new DocumentBuilder(buildingBlockSource);
buildingBlockSourceBuilder.Writeln("Hello World!");

Node buildingBlockContent = doc.GlossaryDocument.ImportNode(buildingBlockSource.FirstSection, true);
buildingBlock.AppendChild(buildingBlockContent);

// Create an advance field using document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldAutoText fieldAutoText = (FieldAutoText)builder.InsertField(FieldType.FieldAutoText, true);

// Refer to our building block by name
fieldAutoText.EntryName = "MyBlock";

Assert.AreEqual(" AUTOTEXT  MyBlock", fieldAutoText.GetFieldCode());

// Put additional templates here
doc.FieldOptions.BuiltInTemplatesPaths = new[] { MyDir + "Document.BusinessBrochureTemplate.dotx" };

// We can also display our building block with a GLOSSARY field
FieldGlossary fieldGlossary = (FieldGlossary)builder.InsertField(FieldType.FieldGlossary, true);
fieldGlossary.EntryName = "MyBlock";

Assert.AreEqual(" GLOSSARY  MyBlock", fieldGlossary.GetFieldCode());

// The text content of our building block will be visible in the output
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.AutoText.dotx");

See Also

FieldGlossary Class | Aspose.Words.Fields Namespace


FieldGoToButton Class

Implements the GOTOBUTTON field. Inserts a jump command, such that when it is activated, the insertion point of the document is moved to the specified location.

For a list of all members of this type, see FieldGoToButton Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldGoToButton

[Visual Basic]
Public Class FieldGoToButton
Inherits Field
[C#]
public class FieldGoToButton : Field

Example

Shows to insert a GOTOBUTTON field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a GOTOBUTTON which will take us to a bookmark referenced by "MyBookmark"
FieldGoToButton field = (FieldGoToButton)builder.InsertField(FieldType.FieldGoToButton, true);
field.DisplayText = "My Button";
field.Location = "MyBookmark";

Assert.AreEqual(" GOTOBUTTON  MyBookmark My Button", field.GetFieldCode());

// Add an arrival destination for our button
builder.InsertBreak(BreakType.PageBreak);
builder.StartBookmark(field.Location);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(field.Location);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GoToButton.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldGoToButton Members | Aspose.Words.Fields Namespace


FieldGoToButton Members

FieldGoToButton overview

Public Instance Constructors

FieldGoToButton Constructor Initializes a new instance of the FieldGoToButton class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets the text of the "button" that appears in the document, such that it can be selected to activate the jump.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Location | Gets or sets the name of a bookmark, a page number, or some other item to jump to.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldGoToButton Class | Aspose.Words.Fields Namespace


FieldGoToButton Constructor

Initializes a new instance of the FieldGoToButton class.

[Visual Basic]
Public Sub New()
[C#]
public FieldGoToButton();

See Also

FieldGoToButton Class | Aspose.Words.Fields Namespace


FieldGoToButton Properties

The properties of the FieldGoToButton class are listed below. For a complete list of FieldGoToButton class members, see the FieldGoToButton Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets the text of the "button" that appears in the document, such that it can be selected to activate the jump.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Location | Gets or sets the name of a bookmark, a page number, or some other item to jump to.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldGoToButton Class | Aspose.Words.Fields Namespace


DisplayText Property

Aspose.Words

FieldGoToButton.DisplayText Property

Gets or sets the text of the "button" that appears in the document, such that it can be selected to activate the jump.

[Visual Basic]
Public Property DisplayText As String
[C#]
public string DisplayText {get; set;}

Example

Shows to insert a GOTOBUTTON field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a GOTOBUTTON which will take us to a bookmark referenced by "MyBookmark"
FieldGoToButton field = (FieldGoToButton)builder.InsertField(FieldType.FieldGoToButton, true);
field.DisplayText = "My Button";
field.Location = "MyBookmark";

Assert.AreEqual(" GOTOBUTTON  MyBookmark My Button", field.GetFieldCode());

// Add an arrival destination for our button
builder.InsertBreak(BreakType.PageBreak);
builder.StartBookmark(field.Location);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(field.Location);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GoToButton.docx");

See Also

FieldGoToButton Class | Aspose.Words.Fields Namespace


Location Property

Aspose.Words

FieldGoToButton.Location Property

Gets or sets the name of a bookmark, a page number, or some other item to jump to.

[Visual Basic]
Public Property Location As String
[C#]
public string Location {get; set;}

Example

Shows to insert a GOTOBUTTON field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add a GOTOBUTTON which will take us to a bookmark referenced by "MyBookmark"
FieldGoToButton field = (FieldGoToButton)builder.InsertField(FieldType.FieldGoToButton, true);
field.DisplayText = "My Button";
field.Location = "MyBookmark";

Assert.AreEqual(" GOTOBUTTON  MyBookmark My Button", field.GetFieldCode());

// Add an arrival destination for our button
builder.InsertBreak(BreakType.PageBreak);
builder.StartBookmark(field.Location);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(field.Location);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GoToButton.docx");

See Also

FieldGoToButton Class | Aspose.Words.Fields Namespace


FieldGreetingLine Class

Implements the GREETINGLINE field.

For a list of all members of this type, see FieldGreetingLine Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldGreetingLine

[Visual Basic]
Public Class FieldGreetingLine
Inherits Field
[C#]
public class FieldGreetingLine : Field

Remarks

Inserts a mail merge greeting line.

Example

Shows how to insert a GREETINGLINE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a custom greeting field with document builder, and also some content
FieldGreetingLine fieldGreetingLine = (FieldGreetingLine)builder.InsertField(FieldType.FieldGreetingLine, true);
builder.Writeln("\n\n\tThis is your custom greeting, created programmatically using Aspose Words!");

// This array contains strings that correspond to column names in the data table that we will mail merge into our document
Assert.AreEqual(0, fieldGreetingLine.GetFieldNames().Length);

// To populate that array, we need to specify a format for our greeting line
fieldGreetingLine.NameFormat = "<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> ";

// In this case, our greeting line's field names array now has "Courtesy Title" and "Last Name"
Assert.AreEqual(2, fieldGreetingLine.GetFieldNames().Length);

// This string will cover any cases where the data in the data table is incorrect by substituting the malformed name with a string
fieldGreetingLine.AlternateText = "Sir or Madam";

// We can set the language ID here too
fieldGreetingLine.LanguageId = "1033";

Assert.AreEqual(" GREETINGLINE  \\f \"<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> \" \\e \"Sir or Madam\" \\l 1033", fieldGreetingLine.GetFieldCode());

// Create a source table for our mail merge that has columns that our greeting line will look for
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");
table.Rows.Add("", "No", "Name"); // This row has an invalid value in the Courtesy Title column, so our greeting will default to the alternate text

doc.MailMerge.Execute(table);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GreetingLine.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldGreetingLine Members | Aspose.Words.Fields Namespace


FieldGreetingLine Members

FieldGreetingLine overview

Public Instance Constructors

FieldGreetingLine Constructor Initializes a new instance of the FieldGreetingLine class.

Public Instance Properties

AlternateText | Gets or sets the text to include in the field if the name is blank.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LanguageId | Gets or sets the language id used to format the name.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NameFormat | Gets or sets the format of the name included in the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
GetFieldNames | Returns a collection of mail merge field names used by the field.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


FieldGreetingLine Constructor

Initializes a new instance of the FieldGreetingLine class.

[Visual Basic]
Public Sub New()
[C#]
public FieldGreetingLine();

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


FieldGreetingLine Properties

The properties of the FieldGreetingLine class are listed below. For a complete list of FieldGreetingLine class members, see the FieldGreetingLine Members topic.

Public Instance Properties

AlternateText | Gets or sets the text to include in the field if the name is blank.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LanguageId | Gets or sets the language id used to format the name.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NameFormat | Gets or sets the format of the name included in the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


AlternateText Property

Aspose.Words

FieldGreetingLine.AlternateText Property

Gets or sets the text to include in the field if the name is blank.

[Visual Basic]
Public Property AlternateText As String
[C#]
public string AlternateText {get; set;}

Example

Shows how to insert a GREETINGLINE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a custom greeting field with document builder, and also some content
FieldGreetingLine fieldGreetingLine = (FieldGreetingLine)builder.InsertField(FieldType.FieldGreetingLine, true);
builder.Writeln("\n\n\tThis is your custom greeting, created programmatically using Aspose Words!");

// This array contains strings that correspond to column names in the data table that we will mail merge into our document
Assert.AreEqual(0, fieldGreetingLine.GetFieldNames().Length);

// To populate that array, we need to specify a format for our greeting line
fieldGreetingLine.NameFormat = "<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> ";

// In this case, our greeting line's field names array now has "Courtesy Title" and "Last Name"
Assert.AreEqual(2, fieldGreetingLine.GetFieldNames().Length);

// This string will cover any cases where the data in the data table is incorrect by substituting the malformed name with a string
fieldGreetingLine.AlternateText = "Sir or Madam";

// We can set the language ID here too
fieldGreetingLine.LanguageId = "1033";

Assert.AreEqual(" GREETINGLINE  \\f \"<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> \" \\e \"Sir or Madam\" \\l 1033", fieldGreetingLine.GetFieldCode());

// Create a source table for our mail merge that has columns that our greeting line will look for
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");
table.Rows.Add("", "No", "Name"); // This row has an invalid value in the Courtesy Title column, so our greeting will default to the alternate text

doc.MailMerge.Execute(table);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GreetingLine.docx");

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


LanguageId Property

Aspose.Words

FieldGreetingLine.LanguageId Property

Gets or sets the language id used to format the name.

[Visual Basic]
Public Property LanguageId As String
[C#]
public string LanguageId {get; set;}

Example

Shows how to insert a GREETINGLINE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a custom greeting field with document builder, and also some content
FieldGreetingLine fieldGreetingLine = (FieldGreetingLine)builder.InsertField(FieldType.FieldGreetingLine, true);
builder.Writeln("\n\n\tThis is your custom greeting, created programmatically using Aspose Words!");

// This array contains strings that correspond to column names in the data table that we will mail merge into our document
Assert.AreEqual(0, fieldGreetingLine.GetFieldNames().Length);

// To populate that array, we need to specify a format for our greeting line
fieldGreetingLine.NameFormat = "<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> ";

// In this case, our greeting line's field names array now has "Courtesy Title" and "Last Name"
Assert.AreEqual(2, fieldGreetingLine.GetFieldNames().Length);

// This string will cover any cases where the data in the data table is incorrect by substituting the malformed name with a string
fieldGreetingLine.AlternateText = "Sir or Madam";

// We can set the language ID here too
fieldGreetingLine.LanguageId = "1033";

Assert.AreEqual(" GREETINGLINE  \\f \"<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> \" \\e \"Sir or Madam\" \\l 1033", fieldGreetingLine.GetFieldCode());

// Create a source table for our mail merge that has columns that our greeting line will look for
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");
table.Rows.Add("", "No", "Name"); // This row has an invalid value in the Courtesy Title column, so our greeting will default to the alternate text

doc.MailMerge.Execute(table);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GreetingLine.docx");

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


NameFormat Property

Aspose.Words

FieldGreetingLine.NameFormat Property

Gets or sets the format of the name included in the field.

[Visual Basic]
Public Property NameFormat As String
[C#]
public string NameFormat {get; set;}

Example

Shows how to insert a GREETINGLINE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a custom greeting field with document builder, and also some content
FieldGreetingLine fieldGreetingLine = (FieldGreetingLine)builder.InsertField(FieldType.FieldGreetingLine, true);
builder.Writeln("\n\n\tThis is your custom greeting, created programmatically using Aspose Words!");

// This array contains strings that correspond to column names in the data table that we will mail merge into our document
Assert.AreEqual(0, fieldGreetingLine.GetFieldNames().Length);

// To populate that array, we need to specify a format for our greeting line
fieldGreetingLine.NameFormat = "<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> ";

// In this case, our greeting line's field names array now has "Courtesy Title" and "Last Name"
Assert.AreEqual(2, fieldGreetingLine.GetFieldNames().Length);

// This string will cover any cases where the data in the data table is incorrect by substituting the malformed name with a string
fieldGreetingLine.AlternateText = "Sir or Madam";

// We can set the language ID here too
fieldGreetingLine.LanguageId = "1033";

Assert.AreEqual(" GREETINGLINE  \\f \"<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> \" \\e \"Sir or Madam\" \\l 1033", fieldGreetingLine.GetFieldCode());

// Create a source table for our mail merge that has columns that our greeting line will look for
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");
table.Rows.Add("", "No", "Name"); // This row has an invalid value in the Courtesy Title column, so our greeting will default to the alternate text

doc.MailMerge.Execute(table);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GreetingLine.docx");

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


FieldGreetingLine Methods

The methods of the FieldGreetingLine class are listed below. For a complete list of FieldGreetingLine class members, see the FieldGreetingLine Members topic.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
GetFieldNames | Returns a collection of mail merge field names used by the field.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


FieldGreetingLine.GetFieldNames Method

Returns a collection of mail merge field names used by the field.

[Visual Basic]
NotOverridable Public Function GetFieldNames() As String()
[C#]
public string[] GetFieldNames();

Example

Shows how to insert a GREETINGLINE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a custom greeting field with document builder, and also some content
FieldGreetingLine fieldGreetingLine = (FieldGreetingLine)builder.InsertField(FieldType.FieldGreetingLine, true);
builder.Writeln("\n\n\tThis is your custom greeting, created programmatically using Aspose Words!");

// This array contains strings that correspond to column names in the data table that we will mail merge into our document
Assert.AreEqual(0, fieldGreetingLine.GetFieldNames().Length);

// To populate that array, we need to specify a format for our greeting line
fieldGreetingLine.NameFormat = "<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> ";

// In this case, our greeting line's field names array now has "Courtesy Title" and "Last Name"
Assert.AreEqual(2, fieldGreetingLine.GetFieldNames().Length);

// This string will cover any cases where the data in the data table is incorrect by substituting the malformed name with a string
fieldGreetingLine.AlternateText = "Sir or Madam";

// We can set the language ID here too
fieldGreetingLine.LanguageId = "1033";

Assert.AreEqual(" GREETINGLINE  \\f \"<< _BEFORE_ Dear >><< _TITLE0_ >><< _LAST0_ >><< _AFTER_ ,>> \" \\e \"Sir or Madam\" \\l 1033", fieldGreetingLine.GetFieldCode());

// Create a source table for our mail merge that has columns that our greeting line will look for
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");
table.Rows.Add("", "No", "Name"); // This row has an invalid value in the Courtesy Title column, so our greeting will default to the alternate text

doc.MailMerge.Execute(table);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.GreetingLine.docx");

See Also

FieldGreetingLine Class | Aspose.Words.Fields Namespace


FieldHyperlink Class

Implements the HYPERLINK field

For a list of all members of this type, see FieldHyperlink Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldHyperlink

[Visual Basic]
Public Class FieldHyperlink
Inherits Field
[C#]
public class FieldHyperlink : Field

Remarks

When selected, causes control to jump to the location such as a bookmark or a URL.

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldHyperlink Members | Aspose.Words.Fields Namespace


FieldHyperlink Members

FieldHyperlink overview

Public Instance Constructors

FieldHyperlink Constructor Initializes a new instance of the FieldHyperlink class.

Public Instance Properties

Address | Gets or sets a location where this hyperlink jumps.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsImageMap | Gets or sets whether to append coordinates to the hyperlink for a server-side image map.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
OpenInNewWindow | Gets or sets whether to open the destination site in a new web browser window.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScreenTip | Gets or sets the ScreenTip text for the hyperlink.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SubAddress | Gets or sets a location in the file, such as a bookmark, where this hyperlink jumps.
Target | Gets or sets the target to which the link should be redirected.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


FieldHyperlink Constructor

Initializes a new instance of the FieldHyperlink class.

[Visual Basic]
Public Sub New()
[C#]
public FieldHyperlink();

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


FieldHyperlink Properties

The properties of the FieldHyperlink class are listed below. For a complete list of FieldHyperlink class members, see the FieldHyperlink Members topic.

Public Instance Properties

Address | Gets or sets a location where this hyperlink jumps.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsImageMap | Gets or sets whether to append coordinates to the hyperlink for a server-side image map.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
OpenInNewWindow | Gets or sets whether to open the destination site in a new web browser window.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScreenTip | Gets or sets the ScreenTip text for the hyperlink.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SubAddress | Gets or sets a location in the file, such as a bookmark, where this hyperlink jumps.
Target | Gets or sets the target to which the link should be redirected.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


Address Property

Aspose.Words

FieldHyperlink.Address Property

Gets or sets a location where this hyperlink jumps.

[Visual Basic]
Public Property Address As String
[C#]
public string Address {get; set;}

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


IsImageMap Property

Aspose.Words

FieldHyperlink.IsImageMap Property

Gets or sets whether to append coordinates to the hyperlink for a server-side image map.

[Visual Basic]
Public Property IsImageMap As Boolean
[C#]
public bool IsImageMap {get; set;}

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


OpenInNewWindow Property

Aspose.Words

FieldHyperlink.OpenInNewWindow Property

Gets or sets whether to open the destination site in a new web browser window.

[Visual Basic]
Public Property OpenInNewWindow As Boolean
[C#]
public bool OpenInNewWindow {get; set;}

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


ScreenTip Property

Aspose.Words

FieldHyperlink.ScreenTip Property

Gets or sets the ScreenTip text for the hyperlink.

[Visual Basic]
Public Property ScreenTip As String
[C#]
public string ScreenTip {get; set;}

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


SubAddress Property

Aspose.Words

FieldHyperlink.SubAddress Property

Gets or sets a location in the file, such as a bookmark, where this hyperlink jumps.

[Visual Basic]
Public Property SubAddress As String
[C#]
public string SubAddress {get; set;}

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


Target Property

Aspose.Words

FieldHyperlink.Target Property

Gets or sets the target to which the link should be redirected.

[Visual Basic]
Public Property Target As String
[C#]
public string Target {get; set;}

Example

Shows how to insert HYPERLINK fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a hyperlink with a document builder
FieldHyperlink fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);

// When link is clicked, open a document and place the cursor on the bookmarked location
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.docx";
fieldHyperlink.SubAddress = "My_Bookmark";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address + " on bookmark " + fieldHyperlink.SubAddress + " in a new window";

builder.Writeln();

// Open html file at a specific frame
fieldHyperlink = (FieldHyperlink)builder.InsertField(FieldType.FieldHyperlink, true);
fieldHyperlink.Address = MyDir + "Field.HyperlinkDestination.html";
fieldHyperlink.ScreenTip = "Open " + fieldHyperlink.Address;
fieldHyperlink.Target = "iframe_3";
fieldHyperlink.OpenInNewWindow = true;
fieldHyperlink.IsImageMap = false;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Hyperlink.docx");

See Also

FieldHyperlink Class | Aspose.Words.Fields Namespace


FieldIf Class

Implements the IF field.

For a list of all members of this type, see FieldIf Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldIf

[Visual Basic]
Public Class FieldIf
Inherits Field
[C#]
public class FieldIf : Field

Remarks

Compares the values designated by the expressions LeftExpression and RightExpression in comparison using the operator designated by ComparisonOperator.

A field in the following format will be used as a mail merge source: { IF 0 = 0 "{PatientsNameFML}" "" \* MERGEFORMAT }

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldIf Members | Aspose.Words.Fields Namespace


FieldIf Members

FieldIf overview

Public Instance Constructors

FieldIf Constructor Initializes a new instance of the FieldIf class.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FalseText | Gets or sets the text displayed if the comparison expression is false.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
TrueText | Gets or sets the text displayed if the comparison expression is true.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

EvaluateCondition | Evaluates the condition.
GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldIf Class | Aspose.Words.Fields Namespace


FieldIf Constructor

Initializes a new instance of the FieldIf class.

[Visual Basic]
Public Sub New()
[C#]
public FieldIf();

See Also

FieldIf Class | Aspose.Words.Fields Namespace


FieldIf Properties

The properties of the FieldIf class are listed below. For a complete list of FieldIf class members, see the FieldIf Members topic.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FalseText | Gets or sets the text displayed if the comparison expression is false.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
TrueText | Gets or sets the text displayed if the comparison expression is true.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldIf Class | Aspose.Words.Fields Namespace


ComparisonOperator Property

Aspose.Words

FieldIf.ComparisonOperator Property

Gets or sets the comparison operator.

[Visual Basic]
Public Property ComparisonOperator As String
[C#]
public string ComparisonOperator {get; set;}

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

See Also

FieldIf Class | Aspose.Words.Fields Namespace


FalseText Property

Aspose.Words

FieldIf.FalseText Property

Gets or sets the text displayed if the comparison expression is false.

[Visual Basic]
Public Property FalseText As String
[C#]
public string FalseText {get; set;}

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

See Also

FieldIf Class | Aspose.Words.Fields Namespace


LeftExpression Property

Aspose.Words

FieldIf.LeftExpression Property

Gets or sets the left part of the comparison expression.

[Visual Basic]
Public Property LeftExpression As String
[C#]
public string LeftExpression {get; set;}

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

See Also

FieldIf Class | Aspose.Words.Fields Namespace


RightExpression Property

Aspose.Words

FieldIf.RightExpression Property

Gets or sets the right part of the comparison expression.

[Visual Basic]
Public Property RightExpression As String
[C#]
public string RightExpression {get; set;}

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

See Also

FieldIf Class | Aspose.Words.Fields Namespace


TrueText Property

Aspose.Words

FieldIf.TrueText Property

Gets or sets the text displayed if the comparison expression is true.

[Visual Basic]
Public Property TrueText As String
[C#]
public string TrueText {get; set;}

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

See Also

FieldIf Class | Aspose.Words.Fields Namespace


FieldIf Methods

The methods of the FieldIf class are listed below. For a complete list of FieldIf class members, see the FieldIf Members topic.

Public Instance Methods

EvaluateCondition | Evaluates the condition.
GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldIf Class | Aspose.Words.Fields Namespace


FieldIf.EvaluateCondition Method

Evaluates the condition.

[Visual Basic]
Public Function EvaluateCondition() As FieldIfComparisonResult
[C#]
public FieldIfComparisonResult EvaluateCondition();

Return Value

A FieldIfComparisonResult value that represents the result of the condition evaluation.

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

See Also

FieldIf Class | Aspose.Words.Fields Namespace


FieldIfComparisonResult Enumeration

Specifies the result of the IF field condition evaluation.

[Visual Basic]
Public Enum FieldIfComparisonResult
[C#]
public enum FieldIfComparisonResult

Example

Shows how to insert an if field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Statement 1: ");

// Use document builder to insert an if field
FieldIf fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);

// The if field will output either the TrueText or FalseText string into the document, depending on the truth of the statement
// In this case, "0 = 1" is incorrect, so the output will be "False"
fieldIf.LeftExpression = "0";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "1";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  0 = 1 True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.False, fieldIf.EvaluateCondition());

// This time, the statement is correct, so the output will be "True"
builder.Write("\nStatement 2: ");
fieldIf = (FieldIf)builder.InsertField(FieldType.FieldIf, true);
fieldIf.LeftExpression = "5";
fieldIf.ComparisonOperator = "=";
fieldIf.RightExpression = "2 + 3";
fieldIf.TrueText = "True";
fieldIf.FalseText = "False";

Assert.AreEqual(" IF  5 = \"2 + 3\" True False", fieldIf.GetFieldCode());
Assert.AreEqual(FieldIfComparisonResult.True, fieldIf.EvaluateCondition());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.If.docx");

Members

Member Name | Description | Value
Error | There is an error in the condition. | 0
True | The condition is true. | 1
False | The condition is false. | 2

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fields Namespace


FieldImport Class

Implements the IMPORT field.

For a list of all members of this type, see FieldImport Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldImport

[Visual Basic]
Public Class FieldImport
Inherits Field
[C#]
public class FieldImport : Field

Remarks

Retrieves the picture contained in the document.

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldImport Members | Aspose.Words.Fields Namespace


FieldImport Members

FieldImport overview

Public Instance Constructors

FieldImport Constructor Initializes a new instance of the FieldImport class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
GraphicFilter | Gets or sets the name of the filter for the format of the graphic that is to be inserted.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the picture.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldImport Class | Aspose.Words.Fields Namespace


FieldImport Constructor

Initializes a new instance of the FieldImport class.

[Visual Basic]
Public Sub New()
[C#]
public FieldImport();

See Also

FieldImport Class | Aspose.Words.Fields Namespace


FieldImport Properties

The properties of the FieldImport class are listed below. For a complete list of FieldImport class members, see the FieldImport Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
GraphicFilter | Gets or sets the name of the filter for the format of the graphic that is to be inserted.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the picture.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldImport Class | Aspose.Words.Fields Namespace


GraphicFilter Property

Aspose.Words

FieldImport.GraphicFilter Property

Gets or sets the name of the filter for the format of the graphic that is to be inserted.

[Visual Basic]
Public Property GraphicFilter As String
[C#]
public string GraphicFilter {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldImport Class | Aspose.Words.Fields Namespace


IsLinked Property

Aspose.Words

FieldImport.IsLinked Property

Gets or sets whether to reduce the file size by not storing graphics data with the document.

[Visual Basic]
Public Property IsLinked As Boolean
[C#]
public bool IsLinked {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldImport Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldImport.SourceFullName Property

Gets or sets the location of the picture.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldImport Class | Aspose.Words.Fields Namespace


FieldInclude Class

Implements the INCLUDE field.

For a list of all members of this type, see FieldInclude Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldInclude

[Visual Basic]
Public Class FieldInclude
Inherits Field
[C#]
public class FieldInclude : Field

Remarks

Inserts all or part of the text and graphics contained in another document.

Example

Shows how to create an INCLUDE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add an INCLUDE field with document builder and import a portion of the document defined by a bookmark
FieldInclude fieldInclude = (FieldInclude)builder.InsertField(FieldType.FieldInclude, true);
fieldInclude.SourceFullName = MyDir + "Field.Include.Source.docx";
fieldInclude.BookmarkName = "Source_paragraph_2";
fieldInclude.LockFields = false;
fieldInclude.TextConverter = "Microsoft Word";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Include.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldInclude Members | Aspose.Words.Fields Namespace


FieldInclude Members

FieldInclude overview

Public Instance Constructors

FieldInclude Constructor Initializes a new instance of the FieldInclude class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark in the document to include.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
LockFields | Gets or sets whether to prevent fields in the included document from being updated.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the document.
Start (inherited from Field) | Gets the node that represents the start of the field.
TextConverter | Gets or sets the name of the text converter for the format of the included file.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


FieldInclude Constructor

Initializes a new instance of the FieldInclude class.

[Visual Basic]
Public Sub New()
[C#]
public FieldInclude();

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


FieldInclude Properties

The properties of the FieldInclude class are listed below. For a complete list of FieldInclude class members, see the FieldInclude Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark in the document to include.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
LockFields | Gets or sets whether to prevent fields in the included document from being updated.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the document.
Start (inherited from Field) | Gets the node that represents the start of the field.
TextConverter | Gets or sets the name of the text converter for the format of the included file.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldInclude.BookmarkName Property

Gets or sets the name of the bookmark in the document to include.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to create an INCLUDE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add an INCLUDE field with document builder and import a portion of the document defined by a bookmark
FieldInclude fieldInclude = (FieldInclude)builder.InsertField(FieldType.FieldInclude, true);
fieldInclude.SourceFullName = MyDir + "Field.Include.Source.docx";
fieldInclude.BookmarkName = "Source_paragraph_2";
fieldInclude.LockFields = false;
fieldInclude.TextConverter = "Microsoft Word";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Include.docx");

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


LockFields Property

Aspose.Words

FieldInclude.LockFields Property

Gets or sets whether to prevent fields in the included document from being updated.

[Visual Basic]
Public Property LockFields As Boolean
[C#]
public bool LockFields {get; set;}

Example

Shows how to create an INCLUDE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add an INCLUDE field with document builder and import a portion of the document defined by a bookmark
FieldInclude fieldInclude = (FieldInclude)builder.InsertField(FieldType.FieldInclude, true);
fieldInclude.SourceFullName = MyDir + "Field.Include.Source.docx";
fieldInclude.BookmarkName = "Source_paragraph_2";
fieldInclude.LockFields = false;
fieldInclude.TextConverter = "Microsoft Word";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Include.docx");

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldInclude.SourceFullName Property

Gets or sets the location of the document.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to create an INCLUDE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add an INCLUDE field with document builder and import a portion of the document defined by a bookmark
FieldInclude fieldInclude = (FieldInclude)builder.InsertField(FieldType.FieldInclude, true);
fieldInclude.SourceFullName = MyDir + "Field.Include.Source.docx";
fieldInclude.BookmarkName = "Source_paragraph_2";
fieldInclude.LockFields = false;
fieldInclude.TextConverter = "Microsoft Word";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Include.docx");

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


TextConverter Property

Aspose.Words

FieldInclude.TextConverter Property

Gets or sets the name of the text converter for the format of the included file.

[Visual Basic]
Public Property TextConverter As String
[C#]
public string TextConverter {get; set;}

Example

Shows how to create an INCLUDE field and set its properties.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add an INCLUDE field with document builder and import a portion of the document defined by a bookmark
FieldInclude fieldInclude = (FieldInclude)builder.InsertField(FieldType.FieldInclude, true);
fieldInclude.SourceFullName = MyDir + "Field.Include.Source.docx";
fieldInclude.BookmarkName = "Source_paragraph_2";
fieldInclude.LockFields = false;
fieldInclude.TextConverter = "Microsoft Word";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Include.docx");

See Also

FieldInclude Class | Aspose.Words.Fields Namespace


FieldIncludePicture Class

Implements the INCLUDEPICTURE field.

For a list of all members of this type, see FieldIncludePicture Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldIncludePicture

[Visual Basic]
Public Class FieldIncludePicture
Inherits Field
[C#]
public class FieldIncludePicture : Field

Remarks

Retrieves a picture and displays it as the field result.

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldIncludePicture Members | Aspose.Words.Fields Namespace


FieldIncludePicture Members

FieldIncludePicture overview

Public Instance Constructors

FieldIncludePicture Constructor Initializes a new instance of the FieldIncludePicture class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
GraphicFilter | Gets or sets the name of the filter for the format of the graphic that is to be inserted.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ResizeHorizontally | Gets or sets whether to resize the picture horizontally from the source.
ResizeVertically | Gets or sets whether to resize the picture vertically from the source.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the picture using an IRI.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


FieldIncludePicture Constructor

Initializes a new instance of the FieldIncludePicture class.

[Visual Basic]
Public Sub New()
[C#]
public FieldIncludePicture();

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


FieldIncludePicture Properties

The properties of the FieldIncludePicture class are listed below. For a complete list of FieldIncludePicture class members, see the FieldIncludePicture Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
GraphicFilter | Gets or sets the name of the filter for the format of the graphic that is to be inserted.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ResizeHorizontally | Gets or sets whether to resize the picture horizontally from the source.
ResizeVertically | Gets or sets whether to resize the picture vertically from the source.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the picture using an IRI.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


GraphicFilter Property

Aspose.Words

FieldIncludePicture.GraphicFilter Property

Gets or sets the name of the filter for the format of the graphic that is to be inserted.

[Visual Basic]
Public Property GraphicFilter As String
[C#]
public string GraphicFilter {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


IsLinked Property

Aspose.Words

FieldIncludePicture.IsLinked Property

Gets or sets whether to reduce the file size by not storing graphics data with the document.

[Visual Basic]
Public Property IsLinked As Boolean
[C#]
public bool IsLinked {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


ResizeHorizontally Property

Aspose.Words

FieldIncludePicture.ResizeHorizontally Property

Gets or sets whether to resize the picture horizontally from the source.

[Visual Basic]
Public Property ResizeHorizontally As Boolean
[C#]
public bool ResizeHorizontally {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


ResizeVertically Property

Aspose.Words

FieldIncludePicture.ResizeVertically Property

Gets or sets whether to resize the picture vertically from the source.

[Visual Basic]
Public Property ResizeVertically As Boolean
[C#]
public bool ResizeVertically {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldIncludePicture.SourceFullName Property

Gets or sets the location of the picture using an IRI.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to insert images using IMPORT and INCLUDEPICTURE fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldIncludePicture fieldIncludePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
fieldIncludePicture.SourceFullName = MyDir + @"Images\Watermark.png";

// Here we apply the PNG32.FLT filter
fieldIncludePicture.GraphicFilter = "PNG32";
fieldIncludePicture.IsLinked = true;
fieldIncludePicture.ResizeHorizontally = true;
fieldIncludePicture.ResizeVertically = true;

// We can do the same thing with an IMPORT field
FieldImport fieldImport = (FieldImport)builder.InsertField(FieldType.FieldImport, true);
fieldImport.GraphicFilter = "PNG32";
fieldImport.IsLinked = true;
fieldImport.SourceFullName = MyDir + @"Images\Watermark.png";

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.IncludePicture.docx");

See Also

FieldIncludePicture Class | Aspose.Words.Fields Namespace


FieldIncludeText Class

Implements the INCLUDETEXT field.

For a list of all members of this type, see FieldIncludeText Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldIncludeText

[Visual Basic]
Public Class FieldIncludeText
Inherits Field
[C#]
public class FieldIncludeText : Field

Remarks

Inserts all or part of the text and graphics contained in another document.

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldIncludeText Members | Aspose.Words.Fields Namespace


FieldIncludeText Members

FieldIncludeText overview

Public Instance Constructors

FieldIncludeText Constructor Initializes a new instance of the FieldIncludeText class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark in the document to include.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
Encoding | Gets or sets the encoding applied to the data within the referenced file.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
LockFields | Gets or sets whether to prevent fields in the included document from being updated.
MimeType | Gets or sets the MIME type of the referenced file.
NamespaceMappings | Gets or sets the namespace mappings for XPath queries.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the document using an IRI.
Start (inherited from Field) | Gets the node that represents the start of the field.
TextConverter | Gets or sets the name of the text converter for the format of the included file.
Type (inherited from Field) | Gets the Microsoft Word field type.
XPath | Gets or sets XPath for the desired portion of the XML file.
XslTransformation | Gets or sets the location of XSL Transformation to format XML data.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


FieldIncludeText Constructor

Initializes a new instance of the FieldIncludeText class.

[Visual Basic]
Public Sub New()
[C#]
public FieldIncludeText();

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


FieldIncludeText Properties

The properties of the FieldIncludeText class are listed below. For a complete list of FieldIncludeText class members, see the FieldIncludeText Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark in the document to include.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
Encoding | Gets or sets the encoding applied to the data within the referenced file.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
LockFields | Gets or sets whether to prevent fields in the included document from being updated.
MimeType | Gets or sets the MIME type of the referenced file.
NamespaceMappings | Gets or sets the namespace mappings for XPath queries.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the location of the document using an IRI.
Start (inherited from Field) | Gets the node that represents the start of the field.
TextConverter | Gets or sets the name of the text converter for the format of the included file.
Type (inherited from Field) | Gets the Microsoft Word field type.
XPath | Gets or sets XPath for the desired portion of the XML file.
XslTransformation | Gets or sets the location of XSL Transformation to format XML data.

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldIncludeText.BookmarkName Property

Gets or sets the name of the bookmark in the document to include.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


Encoding Property

Aspose.Words

FieldIncludeText.Encoding Property

Gets or sets the encoding applied to the data within the referenced file.

[Visual Basic]
Public Property Encoding As String
[C#]
public string Encoding {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


LockFields Property

Aspose.Words

FieldIncludeText.LockFields Property

Gets or sets whether to prevent fields in the included document from being updated.

[Visual Basic]
Public Property LockFields As Boolean
[C#]
public bool LockFields {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


MimeType Property

Aspose.Words

FieldIncludeText.MimeType Property

Gets or sets the MIME type of the referenced file.

[Visual Basic]
Public Property MimeType As String
[C#]
public string MimeType {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


NamespaceMappings Property

Aspose.Words

FieldIncludeText.NamespaceMappings Property

Gets or sets the namespace mappings for XPath queries.

[Visual Basic]
Public Property NamespaceMappings As String
[C#]
public string NamespaceMappings {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldIncludeText.SourceFullName Property

Gets or sets the location of the document using an IRI.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


TextConverter Property

Aspose.Words

FieldIncludeText.TextConverter Property

Gets or sets the name of the text converter for the format of the included file.

[Visual Basic]
Public Property TextConverter As String
[C#]
public string TextConverter {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


XPath Property

Aspose.Words

FieldIncludeText.XPath Property

Gets or sets XPath for the desired portion of the XML file.

[Visual Basic]
Public Property XPath As String
[C#]
public string XPath {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


XslTransformation Property

Aspose.Words

FieldIncludeText.XslTransformation Property

Gets or sets the location of XSL Transformation to format XML data.

[Visual Basic]
Public Property XslTransformation As String
[C#]
public string XslTransformation {get; set;}

Example

Shows how to create an INCLUDETEXT field and set its properties.

[C#]

public void FieldIncludeText()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert an include text field and perform an XSL transformation on an XML document
    FieldIncludeText fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.XslTransformation = MyDir + "Field.IncludeText.Source.xsl";

    builder.Writeln();

    // Use a document builder to insert an include text field and use an XPath to take specific elements
    fieldIncludeText = CreateFieldIncludeText(builder, MyDir + "Field.IncludeText.Source.xml", false, "text/xml", "XML", "ISO-8859-1");
    fieldIncludeText.NamespaceMappings = "xmlns:n='myNamespace'";
    fieldIncludeText.XPath = "/catalog/cd/title";

    doc.Save(ArtifactsDir + "Field.IncludeText.docx");
}

/// <summary>
/// Use a document builder to insert an INCLUDETEXT field and set its properties
/// </summary>
public FieldIncludeText CreateFieldIncludeText(DocumentBuilder builder, string sourceFullName, bool lockFields, string mimeType, string textConverter, string encoding)
{
    FieldIncludeText fieldIncludeText = (FieldIncludeText)builder.InsertField(FieldType.FieldIncludeText, true);
    fieldIncludeText.SourceFullName = sourceFullName;
    fieldIncludeText.LockFields = lockFields;
    fieldIncludeText.MimeType = mimeType;
    fieldIncludeText.TextConverter = textConverter;
    fieldIncludeText.Encoding = encoding;

    return fieldIncludeText;
}

See Also

FieldIncludeText Class | Aspose.Words.Fields Namespace


FieldIndex Class

Implements the INDEX field.

For a list of all members of this type, see FieldIndex Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldIndex

[Visual Basic]
Public Class FieldIndex
Inherits Field
[C#]
public class FieldIndex : Field

Remarks

Builds an index using the index entries specified by XE fields, and inserts that index at this place in the document.

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldIndex Members | Aspose.Words.Fields Namespace


FieldIndex Members

FieldIndex overview

Public Instance Constructors

FieldIndex Constructor Initializes a new instance of the FieldIndex class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark that marks the portion of the document used to build the index.
CrossReferenceSeparator | Gets or sets the character sequence that is used to separate cross references and other entries.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryType | Gets or sets an index entry type used to build the index.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HasPageNumberSeparator | Gets a value indicating whether a page number separator is overridden through the field's code.
HasSequenceName | Gets a value indicating whether a sequence should be used while the field's result building.
Heading | Gets or sets a heading that appears at the start of each set of entries for any given letter.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LanguageId | Gets or sets the language ID used to generate the index.
LetterRange | Gets or sets a range of letters to which limit the index.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NumberOfColumns | Gets or sets the number of columns per page used when building the index.
PageNumberListSeparator | Gets or sets the character sequence that is used to separate two page numbers in a page number list.
PageNumberSeparator | Gets or sets the character sequence that is used to separate an index entry and its page number.
PageRangeSeparator | Gets or sets the character sequence that is used to separate the start and end of a page range.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RunSubentriesOnSameLine | Gets or sets whether run subentries into the same line as the main entry.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceName | Gets or sets the name of a sequence whose number is included with the page number.
SequenceSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseYomi | Gets or sets whether to enable the use of yomi text for index entries.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


FieldIndex Constructor

Initializes a new instance of the FieldIndex class.

[Visual Basic]
Public Sub New()
[C#]
public FieldIndex();

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


FieldIndex Properties

The properties of the FieldIndex class are listed below. For a complete list of FieldIndex class members, see the FieldIndex Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark that marks the portion of the document used to build the index.
CrossReferenceSeparator | Gets or sets the character sequence that is used to separate cross references and other entries.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryType | Gets or sets an index entry type used to build the index.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HasPageNumberSeparator | Gets a value indicating whether a page number separator is overridden through the field's code.
HasSequenceName | Gets a value indicating whether a sequence should be used while the field's result building.
Heading | Gets or sets a heading that appears at the start of each set of entries for any given letter.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LanguageId | Gets or sets the language ID used to generate the index.
LetterRange | Gets or sets a range of letters to which limit the index.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NumberOfColumns | Gets or sets the number of columns per page used when building the index.
PageNumberListSeparator | Gets or sets the character sequence that is used to separate two page numbers in a page number list.
PageNumberSeparator | Gets or sets the character sequence that is used to separate an index entry and its page number.
PageRangeSeparator | Gets or sets the character sequence that is used to separate the start and end of a page range.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RunSubentriesOnSameLine | Gets or sets whether run subentries into the same line as the main entry.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceName | Gets or sets the name of a sequence whose number is included with the page number.
SequenceSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseYomi | Gets or sets whether to enable the use of yomi text for index entries.

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldIndex.BookmarkName Property

Gets or sets the name of the bookmark that marks the portion of the document used to build the index.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


CrossReferenceSeparator Property

Aspose.Words

FieldIndex.CrossReferenceSeparator Property

Gets or sets the character sequence that is used to separate cross references and other entries.

[Visual Basic]
Public Property CrossReferenceSeparator As String
[C#]
public string CrossReferenceSeparator {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


EntryType Property

Aspose.Words

FieldIndex.EntryType Property

Gets or sets an index entry type used to build the index.

[Visual Basic]
Public Property EntryType As String
[C#]
public string EntryType {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


HasPageNumberSeparator Property

Aspose.Words

FieldIndex.HasPageNumberSeparator Property

Gets a value indicating whether a page number separator is overridden through the field's code.

[Visual Basic]
Public ReadOnly Property HasPageNumberSeparator As Boolean
[C#]
public bool HasPageNumberSeparator {get;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


HasSequenceName Property

Aspose.Words

FieldIndex.HasSequenceName Property

Gets a value indicating whether a sequence should be used while the field's result building.

[Visual Basic]
Public ReadOnly Property HasSequenceName As Boolean
[C#]
public bool HasSequenceName {get;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


Heading Property

Aspose.Words

FieldIndex.Heading Property

Gets or sets a heading that appears at the start of each set of entries for any given letter.

[Visual Basic]
Public Property Heading As String
[C#]
public string Heading {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


LanguageId Property

Aspose.Words

FieldIndex.LanguageId Property

Gets or sets the language ID used to generate the index.

[Visual Basic]
Public Property LanguageId As String
[C#]
public string LanguageId {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


LetterRange Property

Aspose.Words

FieldIndex.LetterRange Property

Gets or sets a range of letters to which limit the index.

[Visual Basic]
Public Property LetterRange As String
[C#]
public string LetterRange {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


NumberOfColumns Property

Aspose.Words

FieldIndex.NumberOfColumns Property

Gets or sets the number of columns per page used when building the index.

[Visual Basic]
Public Property NumberOfColumns As String
[C#]
public string NumberOfColumns {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


PageNumberListSeparator Property

Aspose.Words

FieldIndex.PageNumberListSeparator Property

Gets or sets the character sequence that is used to separate two page numbers in a page number list.

[Visual Basic]
Public Property PageNumberListSeparator As String
[C#]
public string PageNumberListSeparator {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


PageNumberSeparator Property

Aspose.Words

FieldIndex.PageNumberSeparator Property

Gets or sets the character sequence that is used to separate an index entry and its page number.

[Visual Basic]
Public Property PageNumberSeparator As String
[C#]
public string PageNumberSeparator {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


PageRangeSeparator Property

Aspose.Words

FieldIndex.PageRangeSeparator Property

Gets or sets the character sequence that is used to separate the start and end of a page range.

[Visual Basic]
Public Property PageRangeSeparator As String
[C#]
public string PageRangeSeparator {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


RunSubentriesOnSameLine Property

Aspose.Words

FieldIndex.RunSubentriesOnSameLine Property

Gets or sets whether run subentries into the same line as the main entry.

[Visual Basic]
Public Property RunSubentriesOnSameLine As Boolean
[C#]
public bool RunSubentriesOnSameLine {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


SequenceName Property

Aspose.Words

FieldIndex.SequenceName Property

Gets or sets the name of a sequence whose number is included with the page number.

[Visual Basic]
Public Property SequenceName As String
[C#]
public string SequenceName {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


SequenceSeparator Property

Aspose.Words

FieldIndex.SequenceSeparator Property

Gets or sets the character sequence that is used to separate sequence numbers and page numbers.

[Visual Basic]
Public Property SequenceSeparator As String
[C#]
public string SequenceSeparator {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


UseYomi Property

Aspose.Words

FieldIndex.UseYomi Property

Gets or sets whether to enable the use of yomi text for index entries.

[Visual Basic]
Public Property UseYomi As Boolean
[C#]
public bool UseYomi {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldIndex Class | Aspose.Words.Fields Namespace


FieldInfo Class

Implements the INFO field.

For a list of all members of this type, see FieldInfo Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldInfo

[Visual Basic]
Public Class FieldInfo
Inherits Field
[C#]
public class FieldInfo : Field

Remarks

Inserts information about a document property.

Example

Shows how to work with INFO fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set the value of a document property
doc.BuiltInDocumentProperties.Comments = "My comment";

// We can access a property using its name and display it with an INFO field
// In this case it will be the Comments property
FieldInfo field = (FieldInfo)builder.InsertField(FieldType.FieldInfo, true);
field.InfoType = "Comments";
field.Update();

Assert.AreEqual(" INFO  Comments", field.GetFieldCode());
Assert.AreEqual("My comment", field.Result);

builder.Writeln();

// We can override the value of a document property by setting an INFO field's optional new value
field = (FieldInfo)builder.InsertField(FieldType.FieldInfo, true);
field.InfoType = "Comments";
field.NewValue = "New comment";
field.Update();

// Our field's new value has been applied to the corresponding property
Assert.AreEqual(" INFO  Comments \"New comment\"", field.GetFieldCode());
Assert.AreEqual("New comment", field.Result);
Assert.AreEqual("New comment", doc.BuiltInDocumentProperties.Comments);

doc.Save(ArtifactsDir + "Field.Info.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldInfo Members | Aspose.Words.Fields Namespace


FieldInfo Members

FieldInfo overview

Public Instance Constructors

FieldInfo Constructor Initializes a new instance of the FieldInfo class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InfoType | Gets or sets the type of the document property to insert.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NewValue | Gets or sets an optional value that updates the property.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldInfo Class | Aspose.Words.Fields Namespace


FieldInfo Constructor

Initializes a new instance of the FieldInfo class.

[Visual Basic]
Public Sub New()
[C#]
public FieldInfo();

See Also

FieldInfo Class | Aspose.Words.Fields Namespace


FieldInfo Properties

The properties of the FieldInfo class are listed below. For a complete list of FieldInfo class members, see the FieldInfo Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InfoType | Gets or sets the type of the document property to insert.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NewValue | Gets or sets an optional value that updates the property.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldInfo Class | Aspose.Words.Fields Namespace


InfoType Property

Aspose.Words

FieldInfo.InfoType Property

Gets or sets the type of the document property to insert.

[Visual Basic]
Public Property InfoType As String
[C#]
public string InfoType {get; set;}

Example

Shows how to work with INFO fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set the value of a document property
doc.BuiltInDocumentProperties.Comments = "My comment";

// We can access a property using its name and display it with an INFO field
// In this case it will be the Comments property
FieldInfo field = (FieldInfo)builder.InsertField(FieldType.FieldInfo, true);
field.InfoType = "Comments";
field.Update();

Assert.AreEqual(" INFO  Comments", field.GetFieldCode());
Assert.AreEqual("My comment", field.Result);

builder.Writeln();

// We can override the value of a document property by setting an INFO field's optional new value
field = (FieldInfo)builder.InsertField(FieldType.FieldInfo, true);
field.InfoType = "Comments";
field.NewValue = "New comment";
field.Update();

// Our field's new value has been applied to the corresponding property
Assert.AreEqual(" INFO  Comments \"New comment\"", field.GetFieldCode());
Assert.AreEqual("New comment", field.Result);
Assert.AreEqual("New comment", doc.BuiltInDocumentProperties.Comments);

doc.Save(ArtifactsDir + "Field.Info.docx");

See Also

FieldInfo Class | Aspose.Words.Fields Namespace


NewValue Property

Aspose.Words

FieldInfo.NewValue Property

Gets or sets an optional value that updates the property.

[Visual Basic]
Public Property NewValue As String
[C#]
public string NewValue {get; set;}

Example

Shows how to work with INFO fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set the value of a document property
doc.BuiltInDocumentProperties.Comments = "My comment";

// We can access a property using its name and display it with an INFO field
// In this case it will be the Comments property
FieldInfo field = (FieldInfo)builder.InsertField(FieldType.FieldInfo, true);
field.InfoType = "Comments";
field.Update();

Assert.AreEqual(" INFO  Comments", field.GetFieldCode());
Assert.AreEqual("My comment", field.Result);

builder.Writeln();

// We can override the value of a document property by setting an INFO field's optional new value
field = (FieldInfo)builder.InsertField(FieldType.FieldInfo, true);
field.InfoType = "Comments";
field.NewValue = "New comment";
field.Update();

// Our field's new value has been applied to the corresponding property
Assert.AreEqual(" INFO  Comments \"New comment\"", field.GetFieldCode());
Assert.AreEqual("New comment", field.Result);
Assert.AreEqual("New comment", doc.BuiltInDocumentProperties.Comments);

doc.Save(ArtifactsDir + "Field.Info.docx");

See Also

FieldInfo Class | Aspose.Words.Fields Namespace


FieldKeywords Class

Implements the KEYWORDS field.

For a list of all members of this type, see FieldKeywords Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldKeywords

[Visual Basic]
Public Class FieldKeywords
Inherits Field
[C#]
public class FieldKeywords : Field

Remarks

Retrieves, and optionally sets, the document's keywords, as recorded in the Keywords property of the built-in document properties.

Example

Shows to insert a KEYWORDS field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add some keywords, also referred to as "tags" in File Explorer
doc.BuiltInDocumentProperties.Keywords = "Keyword1, Keyword2";

// Add a KEYWORDS field which will display our keywords
FieldKeywords field = (FieldKeywords)builder.InsertField(FieldType.FieldKeyword, true);
field.Update();

Assert.AreEqual(" KEYWORDS ", field.GetFieldCode());
Assert.AreEqual("Keyword1, Keyword2", field.Result);

// We can set the Text property of our field to display a different value to the one within the document's properties
field.Text = "OverridingKeyword";
field.Update();

Assert.AreEqual(" KEYWORDS  OverridingKeyword", field.GetFieldCode());
Assert.AreEqual("OverridingKeyword", field.Result);

// Setting a KEYWORDS field's Text property also updates the document's keywords to our new value
Assert.AreEqual("OverridingKeyword", doc.BuiltInDocumentProperties.Keywords);

doc.Save(ArtifactsDir + "Field.Keywords.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldKeywords Members | Aspose.Words.Fields Namespace


FieldKeywords Members

FieldKeywords overview

Public Instance Constructors

FieldKeywords Constructor Initializes a new instance of the FieldKeywords class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the keywords.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldKeywords Class | Aspose.Words.Fields Namespace


FieldKeywords Constructor

Initializes a new instance of the FieldKeywords class.

[Visual Basic]
Public Sub New()
[C#]
public FieldKeywords();

See Also

FieldKeywords Class | Aspose.Words.Fields Namespace


FieldKeywords Properties

The properties of the FieldKeywords class are listed below. For a complete list of FieldKeywords class members, see the FieldKeywords Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the keywords.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldKeywords Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldKeywords.Text Property

Gets or sets the text of the keywords.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows to insert a KEYWORDS field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add some keywords, also referred to as "tags" in File Explorer
doc.BuiltInDocumentProperties.Keywords = "Keyword1, Keyword2";

// Add a KEYWORDS field which will display our keywords
FieldKeywords field = (FieldKeywords)builder.InsertField(FieldType.FieldKeyword, true);
field.Update();

Assert.AreEqual(" KEYWORDS ", field.GetFieldCode());
Assert.AreEqual("Keyword1, Keyword2", field.Result);

// We can set the Text property of our field to display a different value to the one within the document's properties
field.Text = "OverridingKeyword";
field.Update();

Assert.AreEqual(" KEYWORDS  OverridingKeyword", field.GetFieldCode());
Assert.AreEqual("OverridingKeyword", field.Result);

// Setting a KEYWORDS field's Text property also updates the document's keywords to our new value
Assert.AreEqual("OverridingKeyword", doc.BuiltInDocumentProperties.Keywords);

doc.Save(ArtifactsDir + "Field.Keywords.docx");

See Also

FieldKeywords Class | Aspose.Words.Fields Namespace


FieldLastSavedBy Class

Implements the LASTSAVEDBY field.

For a list of all members of this type, see FieldLastSavedBy Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldLastSavedBy

[Visual Basic]
Public Class FieldLastSavedBy
Inherits Field
[C#]
public class FieldLastSavedBy : Field

Remarks

Retrieves the name of the user who last modified and saved the current document, as recorded in the LastModifiedBy property of the built-in document properties.

Example

Shows how to use the LASTSAVEDBY field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// If we create a document in Microsoft Word, it will have the user's name in the "Last saved by" property
// This is the property that a LASTSAVEDBY field looks up and displays
// If we make a document programmatically, this property is null and needs to have a value assigned to it first
doc.BuiltInDocumentProperties.LastSavedBy = "John Doe";

// Insert a LASTSAVEDBY field using a document builder
FieldLastSavedBy field = (FieldLastSavedBy)builder.InsertField(FieldType.FieldLastSavedBy, true);

// The value from our document property appears here
Assert.AreEqual(" LASTSAVEDBY ", field.GetFieldCode());
Assert.AreEqual("John Doe", field.Result);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.LASTSAVEDBY.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldLastSavedBy Members | Aspose.Words.Fields Namespace


FieldLastSavedBy Members

FieldLastSavedBy overview

Public Instance Constructors

FieldLastSavedBy Constructor Initializes a new instance of the FieldLastSavedBy class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldLastSavedBy Class | Aspose.Words.Fields Namespace


FieldLastSavedBy Constructor

Initializes a new instance of the FieldLastSavedBy class.

[Visual Basic]
Public Sub New()
[C#]
public FieldLastSavedBy();

See Also

FieldLastSavedBy Class | Aspose.Words.Fields Namespace


FieldLink Class

Implements the LINK field.

For a list of all members of this type, see FieldLink Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldLink

[Visual Basic]
Public Class FieldLink
Inherits Field
[C#]
public class FieldLink : Field

Remarks

For information copied from another application, this field links that information to its original source file.

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldLink Members | Aspose.Words.Fields Namespace


FieldLink Members

FieldLink overview

Public Instance Constructors

FieldLink Constructor Initializes a new instance of the FieldLink class.

Public Instance Properties

AutoUpdate | Gets or sets whether to update this field automatically.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatUpdateType | Gets or sets a way the linked object updates its formatting.
InsertAsBitmap | Gets or sets whether to insert the linked object as a bitmap.
InsertAsHtml | Gets or sets whether to insert the linked object as HTML format text.
InsertAsPicture | Gets or sets whether to insert the linked object as a picture.
InsertAsRtf | Gets or sets whether to insert the linked object in rich-text format (RTF).
InsertAsText | Gets or sets whether to insert the linked object in text-only format.
InsertAsUnicode | Gets or sets whether to insert the linked object as Unicode text.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ProgId | Gets or sets the application type of the link information.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the name and location of the source file.
SourceItem | Gets or sets the portion of the source file that's being linked.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldLink Class | Aspose.Words.Fields Namespace


FieldLink Constructor

Initializes a new instance of the FieldLink class.

[Visual Basic]
Public Sub New()
[C#]
public FieldLink();

See Also

FieldLink Class | Aspose.Words.Fields Namespace


FieldLink Properties

The properties of the FieldLink class are listed below. For a complete list of FieldLink class members, see the FieldLink Members topic.

Public Instance Properties

AutoUpdate | Gets or sets whether to update this field automatically.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
FormatUpdateType | Gets or sets a way the linked object updates its formatting.
InsertAsBitmap | Gets or sets whether to insert the linked object as a bitmap.
InsertAsHtml | Gets or sets whether to insert the linked object as HTML format text.
InsertAsPicture | Gets or sets whether to insert the linked object as a picture.
InsertAsRtf | Gets or sets whether to insert the linked object in rich-text format (RTF).
InsertAsText | Gets or sets whether to insert the linked object in text-only format.
InsertAsUnicode | Gets or sets whether to insert the linked object as Unicode text.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLinked | Gets or sets whether to reduce the file size by not storing graphics data with the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ProgId | Gets or sets the application type of the link information.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SourceFullName | Gets or sets the name and location of the source file.
SourceItem | Gets or sets the portion of the source file that's being linked.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldLink Class | Aspose.Words.Fields Namespace


AutoUpdate Property

Aspose.Words

FieldLink.AutoUpdate Property

Gets or sets whether to update this field automatically.

[Visual Basic]
Public Property AutoUpdate As Boolean
[C#]
public bool AutoUpdate {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


FormatUpdateType Property

Aspose.Words

FieldLink.FormatUpdateType Property

Gets or sets a way the linked object updates its formatting.

[Visual Basic]
Public Property FormatUpdateType As String
[C#]
public string FormatUpdateType {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


InsertAsBitmap Property

Aspose.Words

FieldLink.InsertAsBitmap Property

Gets or sets whether to insert the linked object as a bitmap.

[Visual Basic]
Public Property InsertAsBitmap As Boolean
[C#]
public bool InsertAsBitmap {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


InsertAsHtml Property

Aspose.Words

FieldLink.InsertAsHtml Property

Gets or sets whether to insert the linked object as HTML format text.

[Visual Basic]
Public Property InsertAsHtml As Boolean
[C#]
public bool InsertAsHtml {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


InsertAsPicture Property

Aspose.Words

FieldLink.InsertAsPicture Property

Gets or sets whether to insert the linked object as a picture.

[Visual Basic]
Public Property InsertAsPicture As Boolean
[C#]
public bool InsertAsPicture {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


InsertAsRtf Property

Aspose.Words

FieldLink.InsertAsRtf Property

Gets or sets whether to insert the linked object in rich-text format (RTF).

[Visual Basic]
Public Property InsertAsRtf As Boolean
[C#]
public bool InsertAsRtf {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


InsertAsText Property

Aspose.Words

FieldLink.InsertAsText Property

Gets or sets whether to insert the linked object in text-only format.

[Visual Basic]
Public Property InsertAsText As Boolean
[C#]
public bool InsertAsText {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


InsertAsUnicode Property

Aspose.Words

FieldLink.InsertAsUnicode Property

Gets or sets whether to insert the linked object as Unicode text.

[Visual Basic]
Public Property InsertAsUnicode As Boolean
[C#]
public bool InsertAsUnicode {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


IsLinked Property

Aspose.Words

FieldLink.IsLinked Property

Gets or sets whether to reduce the file size by not storing graphics data with the document.

[Visual Basic]
Public Property IsLinked As Boolean
[C#]
public bool IsLinked {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


ProgId Property

Aspose.Words

FieldLink.ProgId Property

Gets or sets the application type of the link information.

[Visual Basic]
Public Property ProgId As String
[C#]
public string ProgId {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


SourceFullName Property

Aspose.Words

FieldLink.SourceFullName Property

Gets or sets the name and location of the source file.

[Visual Basic]
Public Property SourceFullName As String
[C#]
public string SourceFullName {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


SourceItem Property

Aspose.Words

FieldLink.SourceItem Property

Gets or sets the portion of the source file that's being linked.

[Visual Basic]
Public Property SourceItem As String
[C#]
public string SourceItem {get; set;}

Example

Shows how to insert linked objects as LINK, DDE and DDEAUTO fields and present them within the document in different ways.

[C#]

public void FieldLinkedObjectsAsText(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert fields containing text from another document and present them as text (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Word.Document.8", MyDir + "Document.doc", null, true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsText.docx");
}

public void FieldLinkedObjectsAsImage(InsertLinkedObjectAs insertLinkedObjectAs)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert one cell from a spreadsheet as an image (see InsertLinkedObjectAs enum).
    builder.Writeln("FieldLink:\n");
    InsertFieldLink(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "MySpreadsheet.xlsx",
        "Sheet1!R2C2", true);

    builder.Writeln("FieldDde:\n");
    InsertFieldDde(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true, true);

    builder.Writeln("FieldDdeAuto:\n");
    InsertFieldDdeAuto(builder, insertLinkedObjectAs, "Excel.Sheet", MyDir + "Document.Spreadsheet.xlsx",
        "Sheet1!R1C1", true);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.LinkedObjectsAsImage.docx");
}

/// <summary>
/// Use a document builder to insert a LINK field and set its properties according to parameters
/// </summary>
private void InsertFieldLink(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool shouldAutoUpdate)
{
    FieldLink field = (FieldLink)builder.InsertField(FieldType.FieldLink, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDE field and set its properties according to parameters
/// </summary>
private void InsertFieldDde(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs, string progId,
    string sourceFullName, string sourceItem, bool isLinked, bool shouldAutoUpdate)
{
    FieldDde field = (FieldDde)builder.InsertField(FieldType.FieldDDE, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.AutoUpdate = shouldAutoUpdate;
    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;

    builder.Writeln("\n");
}

/// <summary>
/// Use a document builder to insert a DDEAUTO field and set its properties according to parameters
/// </summary>
private void InsertFieldDdeAuto(DocumentBuilder builder, InsertLinkedObjectAs insertLinkedObjectAs,
    string progId, string sourceFullName, string sourceItem, bool isLinked)
{
    FieldDdeAuto field = (FieldDdeAuto)builder.InsertField(FieldType.FieldDDEAuto, true);

    switch (insertLinkedObjectAs)
    {
        case InsertLinkedObjectAs.Text:
            field.InsertAsText = true;
            break;
        case InsertLinkedObjectAs.Unicode:
            field.InsertAsUnicode = true;
            break;
        case InsertLinkedObjectAs.Html:
            field.InsertAsHtml = true;
            break;
        case InsertLinkedObjectAs.Rtf:
            field.InsertAsRtf = true;
            break;
        case InsertLinkedObjectAs.Picture:
            field.InsertAsPicture = true;
            break;
        case InsertLinkedObjectAs.Bitmap:
            field.InsertAsBitmap = true;
            break;
    }

    field.ProgId = progId;
    field.SourceFullName = sourceFullName;
    field.SourceItem = sourceItem;
    field.IsLinked = isLinked;
}

public enum InsertLinkedObjectAs
{
    // LinkedObjectAsText
    Text,
    Unicode,
    Html,
    Rtf,
    // LinkedObjectAsImage
    Picture,
    Bitmap
}

See Also

FieldLink Class | Aspose.Words.Fields Namespace


FieldListNum Class

Implements the LISTNUM field.

For a list of all members of this type, see FieldListNum Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldListNum

[Visual Basic]
Public Class FieldListNum
Inherits Field
[C#]
public class FieldListNum : Field

Example

Shows how to number paragraphs with LISTNUM fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a list num field using a document builder
FieldListNum fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Lists start counting at 1 by default, but we can change this number at any time
// In this case, we'll do a zero-based count
fieldListNum.StartingNumber = "0";
builder.Writeln("Paragraph 1");

// Placing several list num fields in one paragraph increases the list level instead of the current number, in this case resulting in "1)a)i)", list level 3
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.Writeln("Paragraph 2");

// The list level resets with new paragraphs, so to keep counting at a desired list level, we need to set the ListLevel property accordingly
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListLevel = "3";
builder.Writeln("Paragraph 3");

fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Setting this property to this particular value will emulate the AUTONUMOUT field
fieldListNum.ListName = "OutlineDefault";
Assert.IsTrue(fieldListNum.HasListName);

// Start counting from 1
fieldListNum.StartingNumber = "1";
builder.Writeln("Paragraph 4");

// Our fields keep track of the count automatically, but the ListName needs to be set with each new field
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListName = "OutlineDefault";
builder.Writeln("Paragraph 5");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldListNum.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldListNum Members | Aspose.Words.Fields Namespace


FieldListNum Members

FieldListNum overview

Public Instance Constructors

FieldListNum Constructor Initializes a new instance of the FieldListNum class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HasListName | Returns a value indicating whether the name of an abstract numbering definition is provided by the field's code.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
ListLevel | Gets or sets the level in the list, overriding the default behavior of the field.
ListName | Gets or sets the name of the abstract numbering definition used for the numbering.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
StartingNumber | Gets or sets the starting value for this field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


FieldListNum Constructor

Initializes a new instance of the FieldListNum class.

[Visual Basic]
Public Sub New()
[C#]
public FieldListNum();

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


FieldListNum Properties

The properties of the FieldListNum class are listed below. For a complete list of FieldListNum class members, see the FieldListNum Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HasListName | Returns a value indicating whether the name of an abstract numbering definition is provided by the field's code.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
ListLevel | Gets or sets the level in the list, overriding the default behavior of the field.
ListName | Gets or sets the name of the abstract numbering definition used for the numbering.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
StartingNumber | Gets or sets the starting value for this field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


HasListName Property

Aspose.Words

FieldListNum.HasListName Property

Returns a value indicating whether the name of an abstract numbering definition is provided by the field's code.

[Visual Basic]
Public ReadOnly Property HasListName As Boolean
[C#]
public bool HasListName {get;}

Example

Shows how to number paragraphs with LISTNUM fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a list num field using a document builder
FieldListNum fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Lists start counting at 1 by default, but we can change this number at any time
// In this case, we'll do a zero-based count
fieldListNum.StartingNumber = "0";
builder.Writeln("Paragraph 1");

// Placing several list num fields in one paragraph increases the list level instead of the current number, in this case resulting in "1)a)i)", list level 3
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.Writeln("Paragraph 2");

// The list level resets with new paragraphs, so to keep counting at a desired list level, we need to set the ListLevel property accordingly
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListLevel = "3";
builder.Writeln("Paragraph 3");

fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Setting this property to this particular value will emulate the AUTONUMOUT field
fieldListNum.ListName = "OutlineDefault";
Assert.IsTrue(fieldListNum.HasListName);

// Start counting from 1
fieldListNum.StartingNumber = "1";
builder.Writeln("Paragraph 4");

// Our fields keep track of the count automatically, but the ListName needs to be set with each new field
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListName = "OutlineDefault";
builder.Writeln("Paragraph 5");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldListNum.docx");

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


ListLevel Property

Aspose.Words

FieldListNum.ListLevel Property

Gets or sets the level in the list, overriding the default behavior of the field.

[Visual Basic]
Public Property ListLevel As String
[C#]
public string ListLevel {get; set;}

Example

Shows how to number paragraphs with LISTNUM fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a list num field using a document builder
FieldListNum fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Lists start counting at 1 by default, but we can change this number at any time
// In this case, we'll do a zero-based count
fieldListNum.StartingNumber = "0";
builder.Writeln("Paragraph 1");

// Placing several list num fields in one paragraph increases the list level instead of the current number, in this case resulting in "1)a)i)", list level 3
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.Writeln("Paragraph 2");

// The list level resets with new paragraphs, so to keep counting at a desired list level, we need to set the ListLevel property accordingly
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListLevel = "3";
builder.Writeln("Paragraph 3");

fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Setting this property to this particular value will emulate the AUTONUMOUT field
fieldListNum.ListName = "OutlineDefault";
Assert.IsTrue(fieldListNum.HasListName);

// Start counting from 1
fieldListNum.StartingNumber = "1";
builder.Writeln("Paragraph 4");

// Our fields keep track of the count automatically, but the ListName needs to be set with each new field
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListName = "OutlineDefault";
builder.Writeln("Paragraph 5");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldListNum.docx");

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


ListName Property

Aspose.Words

FieldListNum.ListName Property

Gets or sets the name of the abstract numbering definition used for the numbering.

[Visual Basic]
Public Property ListName As String
[C#]
public string ListName {get; set;}

Example

Shows how to number paragraphs with LISTNUM fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a list num field using a document builder
FieldListNum fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Lists start counting at 1 by default, but we can change this number at any time
// In this case, we'll do a zero-based count
fieldListNum.StartingNumber = "0";
builder.Writeln("Paragraph 1");

// Placing several list num fields in one paragraph increases the list level instead of the current number, in this case resulting in "1)a)i)", list level 3
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.Writeln("Paragraph 2");

// The list level resets with new paragraphs, so to keep counting at a desired list level, we need to set the ListLevel property accordingly
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListLevel = "3";
builder.Writeln("Paragraph 3");

fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Setting this property to this particular value will emulate the AUTONUMOUT field
fieldListNum.ListName = "OutlineDefault";
Assert.IsTrue(fieldListNum.HasListName);

// Start counting from 1
fieldListNum.StartingNumber = "1";
builder.Writeln("Paragraph 4");

// Our fields keep track of the count automatically, but the ListName needs to be set with each new field
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListName = "OutlineDefault";
builder.Writeln("Paragraph 5");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldListNum.docx");

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


StartingNumber Property

Aspose.Words

FieldListNum.StartingNumber Property

Gets or sets the starting value for this field.

[Visual Basic]
Public Property StartingNumber As String
[C#]
public string StartingNumber {get; set;}

Example

Shows how to number paragraphs with LISTNUM fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a list num field using a document builder
FieldListNum fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Lists start counting at 1 by default, but we can change this number at any time
// In this case, we'll do a zero-based count
fieldListNum.StartingNumber = "0";
builder.Writeln("Paragraph 1");

// Placing several list num fields in one paragraph increases the list level instead of the current number, in this case resulting in "1)a)i)", list level 3
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.InsertField(FieldType.FieldListNum, true);
builder.Writeln("Paragraph 2");

// The list level resets with new paragraphs, so to keep counting at a desired list level, we need to set the ListLevel property accordingly
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListLevel = "3";
builder.Writeln("Paragraph 3");

fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);

// Setting this property to this particular value will emulate the AUTONUMOUT field
fieldListNum.ListName = "OutlineDefault";
Assert.IsTrue(fieldListNum.HasListName);

// Start counting from 1
fieldListNum.StartingNumber = "1";
builder.Writeln("Paragraph 4");

// Our fields keep track of the count automatically, but the ListName needs to be set with each new field
fieldListNum = (FieldListNum)builder.InsertField(FieldType.FieldListNum, true);
fieldListNum.ListName = "OutlineDefault";
builder.Writeln("Paragraph 5");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldListNum.docx");

See Also

FieldListNum Class | Aspose.Words.Fields Namespace


FieldMacroButton Class

Implements the MACROBUTTON field.

Allows a macro or command to be run.

In Aspose.Words this field can also act as a merge field.

For a list of all members of this type, see FieldMacroButton Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldMacroButton

[Visual Basic]
Public Class FieldMacroButton
Inherits Field
[C#]
public class FieldMacroButton : Field

Example

Shows how to use MACROBUTTON fields that enable us to run macros by clicking.

[C#]

// Open a document that contains macros
Document doc = new Document(MyDir + "Document.HasMacro.docm");
DocumentBuilder builder = new DocumentBuilder(doc);
Assert.IsTrue(doc.HasMacros);

// Insert a MACROBUTTON field and reference by name a macro that exists within the input document
FieldMacroButton field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "MyMacro";
field.DisplayText = "Double click to run macro: " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  MyMacro Double click to run macro: MyMacro", field.GetFieldCode());

builder.InsertParagraph();

// Reference "ViewZoom200", a macro that was shipped with Microsoft Word, found under "Word commands"
// If our document has a macro of the same name as one from another source, the field will select ours to run
field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "ViewZoom200";
field.DisplayText = "Run " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  ViewZoom200 Run ViewZoom200", field.GetFieldCode());

// Save the document as a macro-enabled document type
doc.Save(ArtifactsDir + "Field.MacroButton.docm");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMacroButton Members | Aspose.Words.Fields Namespace


FieldMacroButton Members

FieldMacroButton overview

Public Instance Constructors

FieldMacroButton Constructor Initializes a new instance of the FieldMacroButton class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets the text to appear as the "button" that is selected to run the macro or command.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
MacroName | Gets or sets the name of the macro or command to run.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldMacroButton Class | Aspose.Words.Fields Namespace


FieldMacroButton Constructor

Initializes a new instance of the FieldMacroButton class.

[Visual Basic]
Public Sub New()
[C#]
public FieldMacroButton();

See Also

FieldMacroButton Class | Aspose.Words.Fields Namespace


FieldMacroButton Properties

The properties of the FieldMacroButton class are listed below. For a complete list of FieldMacroButton class members, see the FieldMacroButton Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets the text to appear as the "button" that is selected to run the macro or command.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
MacroName | Gets or sets the name of the macro or command to run.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldMacroButton Class | Aspose.Words.Fields Namespace


DisplayText Property

Aspose.Words

FieldMacroButton.DisplayText Property

Gets or sets the text to appear as the "button" that is selected to run the macro or command.

[Visual Basic]
Public Property DisplayText As String
[C#]
public string DisplayText {get; set;}

Example

Shows how to use MACROBUTTON fields that enable us to run macros by clicking.

[C#]

// Open a document that contains macros
Document doc = new Document(MyDir + "Document.HasMacro.docm");
DocumentBuilder builder = new DocumentBuilder(doc);
Assert.IsTrue(doc.HasMacros);

// Insert a MACROBUTTON field and reference by name a macro that exists within the input document
FieldMacroButton field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "MyMacro";
field.DisplayText = "Double click to run macro: " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  MyMacro Double click to run macro: MyMacro", field.GetFieldCode());

builder.InsertParagraph();

// Reference "ViewZoom200", a macro that was shipped with Microsoft Word, found under "Word commands"
// If our document has a macro of the same name as one from another source, the field will select ours to run
field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "ViewZoom200";
field.DisplayText = "Run " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  ViewZoom200 Run ViewZoom200", field.GetFieldCode());

// Save the document as a macro-enabled document type
doc.Save(ArtifactsDir + "Field.MacroButton.docm");

See Also

FieldMacroButton Class | Aspose.Words.Fields Namespace


MacroName Property

Aspose.Words

FieldMacroButton.MacroName Property

Gets or sets the name of the macro or command to run.

[Visual Basic]
Public Property MacroName As String
[C#]
public string MacroName {get; set;}

Example

Shows how to use MACROBUTTON fields that enable us to run macros by clicking.

[C#]

// Open a document that contains macros
Document doc = new Document(MyDir + "Document.HasMacro.docm");
DocumentBuilder builder = new DocumentBuilder(doc);
Assert.IsTrue(doc.HasMacros);

// Insert a MACROBUTTON field and reference by name a macro that exists within the input document
FieldMacroButton field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "MyMacro";
field.DisplayText = "Double click to run macro: " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  MyMacro Double click to run macro: MyMacro", field.GetFieldCode());

builder.InsertParagraph();

// Reference "ViewZoom200", a macro that was shipped with Microsoft Word, found under "Word commands"
// If our document has a macro of the same name as one from another source, the field will select ours to run
field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
field.MacroName = "ViewZoom200";
field.DisplayText = "Run " + field.MacroName;

Assert.AreEqual(" MACROBUTTON  ViewZoom200 Run ViewZoom200", field.GetFieldCode());

// Save the document as a macro-enabled document type
doc.Save(ArtifactsDir + "Field.MacroButton.docm");

See Also

FieldMacroButton Class | Aspose.Words.Fields Namespace


FieldMergeBarcode Class

Implements the MERGEBARCODE field.

For a list of all members of this type, see FieldMergeBarcode Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldMergeBarcode

[Visual Basic]
Public Class FieldMergeBarcode
Inherits Field
[C#]
public class FieldMergeBarcode : Field

Remarks

Mail merge a barcode.

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMergeBarcode Members | Aspose.Words.Fields Namespace


FieldMergeBarcode Members

FieldMergeBarcode overview

Public Instance Constructors

FieldMergeBarcode Constructor Initializes a new instance of the FieldMergeBarcode class.

Public Instance Properties

AddStartStopChar | Gets or sets whether to add Start/Stop characters for barcode types NW7 and CODE39.
BackgroundColor | Gets or sets the background color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
BarcodeType | Gets or sets the barcode type (QR, etc.)
BarcodeValue | Gets or sets the barcode value.
CaseCodeStyle | Gets or sets the style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets whether to display barcode data (text) along with image.
End (inherited from Field) | Gets the node that represents the field end.
ErrorCorrectionLevel | Gets or sets an error correction level of QR Code. Valid values are [0, 3].
FixCheckDigit | Gets or sets whether to fix the check digit if it’s invalid.
ForegroundColor | Gets or sets the foreground color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PosCodeStyle | Gets or sets the style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScalingFactor | Gets or sets a scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000]
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SymbolHeight | Gets or sets the height of the symbol. The units are in TWIPS (1/1440 inch).
SymbolRotation | Gets or sets the rotation of the barcode symbol. Valid values are [0, 3]
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


FieldMergeBarcode Constructor

Initializes a new instance of the FieldMergeBarcode class.

[Visual Basic]
Public Sub New()
[C#]
public FieldMergeBarcode();

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


FieldMergeBarcode Properties

The properties of the FieldMergeBarcode class are listed below. For a complete list of FieldMergeBarcode class members, see the FieldMergeBarcode Members topic.

Public Instance Properties

AddStartStopChar | Gets or sets whether to add Start/Stop characters for barcode types NW7 and CODE39.
BackgroundColor | Gets or sets the background color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
BarcodeType | Gets or sets the barcode type (QR, etc.)
BarcodeValue | Gets or sets the barcode value.
CaseCodeStyle | Gets or sets the style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DisplayText | Gets or sets whether to display barcode data (text) along with image.
End (inherited from Field) | Gets the node that represents the field end.
ErrorCorrectionLevel | Gets or sets an error correction level of QR Code. Valid values are [0, 3].
FixCheckDigit | Gets or sets whether to fix the check digit if it’s invalid.
ForegroundColor | Gets or sets the foreground color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PosCodeStyle | Gets or sets the style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
ScalingFactor | Gets or sets a scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000]
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SymbolHeight | Gets or sets the height of the symbol. The units are in TWIPS (1/1440 inch).
SymbolRotation | Gets or sets the rotation of the barcode symbol. Valid values are [0, 3]
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


AddStartStopChar Property

Aspose.Words

FieldMergeBarcode.AddStartStopChar Property

Gets or sets whether to add Start/Stop characters for barcode types NW7 and CODE39.

[Visual Basic]
Public Property AddStartStopChar As Boolean
[C#]
public bool AddStartStopChar {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


BackgroundColor Property

Aspose.Words

FieldMergeBarcode.BackgroundColor Property

Gets or sets the background color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]

[Visual Basic]
Public Property BackgroundColor As String
[C#]
public string BackgroundColor {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


BarcodeType Property

Aspose.Words

FieldMergeBarcode.BarcodeType Property

Gets or sets the barcode type (QR, etc.)

[Visual Basic]
Public Property BarcodeType As String
[C#]
public string BarcodeType {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


BarcodeValue Property

Aspose.Words

FieldMergeBarcode.BarcodeValue Property

Gets or sets the barcode value.

[Visual Basic]
Public Property BarcodeValue As String
[C#]
public string BarcodeValue {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


CaseCodeStyle Property

Aspose.Words

FieldMergeBarcode.CaseCodeStyle Property

Gets or sets the style of a Case Code for barcode type ITF14. The valid values are [STD|EXT|ADD]

[Visual Basic]
Public Property CaseCodeStyle As String
[C#]
public string CaseCodeStyle {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


DisplayText Property

Aspose.Words

FieldMergeBarcode.DisplayText Property

Gets or sets whether to display barcode data (text) along with image.

[Visual Basic]
Public Property DisplayText As Boolean
[C#]
public bool DisplayText {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


ErrorCorrectionLevel Property

Aspose.Words

FieldMergeBarcode.ErrorCorrectionLevel Property

Gets or sets an error correction level of QR Code. Valid values are [0, 3].

[Visual Basic]
Public Property ErrorCorrectionLevel As String
[C#]
public string ErrorCorrectionLevel {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


FixCheckDigit Property

Aspose.Words

FieldMergeBarcode.FixCheckDigit Property

Gets or sets whether to fix the check digit if it’s invalid.

[Visual Basic]
Public Property FixCheckDigit As Boolean
[C#]
public bool FixCheckDigit {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


ForegroundColor Property

Aspose.Words

FieldMergeBarcode.ForegroundColor Property

Gets or sets the foreground color of the barcode symbol. Valid values are in the range [0, 0xFFFFFF]

[Visual Basic]
Public Property ForegroundColor As String
[C#]
public string ForegroundColor {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


PosCodeStyle Property

Aspose.Words

FieldMergeBarcode.PosCodeStyle Property

Gets or sets the style of a Point of Sale barcode (barcode types UPCA|UPCE|EAN13|EAN8). The valid values (case insensitive) are [STD|SUP2|SUP5|CASE].

[Visual Basic]
Public Property PosCodeStyle As String
[C#]
public string PosCodeStyle {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


ScalingFactor Property

Aspose.Words

FieldMergeBarcode.ScalingFactor Property

Gets or sets a scaling factor for the symbol. The value is in whole percentage points and the valid values are [10, 1000]

[Visual Basic]
Public Property ScalingFactor As String
[C#]
public string ScalingFactor {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


SymbolHeight Property

Aspose.Words

FieldMergeBarcode.SymbolHeight Property

Gets or sets the height of the symbol. The units are in TWIPS (1/1440 inch).

[Visual Basic]
Public Property SymbolHeight As String
[C#]
public string SymbolHeight {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


SymbolRotation Property

Aspose.Words

FieldMergeBarcode.SymbolRotation Property

Gets or sets the rotation of the barcode symbol. Valid values are [0, 3]

[Visual Basic]
Public Property SymbolRotation As String
[C#]
public string SymbolRotation {get; set;}

Example

Shows how to use MERGEBARCODE fields to integrate barcodes into mail merge operations.

[C#]

public void FieldMergeBarcode_QR()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a QR code
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "QR";

    // In a DISPLAYBARCODE field, the BarcodeValue attribute decides what value the barcode will display
    // However in our MERGEBARCODE fields, it has the same function as the FieldName attribute of a MERGEFIELD
    field.BarcodeValue = "MyQRCode";
    field.BackgroundColor = "0xF8BD69";
    field.ForegroundColor = "0xB5413B";
    field.ErrorCorrectionLevel = "3";
    field.ScalingFactor = "250";
    field.SymbolHeight = "1000";
    field.SymbolRotation = "0";

    Assert.AreEqual(" MERGEBARCODE  MyQRCode QR \\b 0xF8BD69 \\f 0xB5413B \\q 3 \\s 250 \\h 1000 \\r 0",
        field.GetFieldCode());
    builder.Writeln();

    // Create a data source for our mail merge
    // This source is a data table, whose column names correspond to the FieldName attributes of MERGEFIELD fields
    // as well as BarcodeValue attributes of DISPLAYBARCODE fields
    DataTable table = CreateTable("Barcodes", new[] { "MyQRCode" },
        new[,] { { "ABC123" }, { "DEF456" } });

    // During the mail merge, all our MERGEBARCODE fields will be converted into DISPLAYBARCODE fields,
    // with values from the data table rows deposited into corresponding BarcodeValue attributes
    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"ABC123\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"DEF456\" QR \\q 3 \\s 250 \\h 1000 \\r 0 \\b 0xF8BD69 \\f 0xB5413B",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_QR.docx");
}

public void FieldMergeBarcode_EAN13()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a EAN13 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "EAN13";
    field.BarcodeValue = "MyEAN13Barcode";
    field.DisplayText = true;
    field.PosCodeStyle = "CASE";
    field.FixCheckDigit = true;

    Assert.AreEqual(" MERGEBARCODE  MyEAN13Barcode EAN13 \\t \\p CASE \\x", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyEAN13Barcode" },
        new[,] { { "501234567890" }, { "123456789012" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"501234567890\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"123456789012\" EAN13 \\t \\p CASE \\x",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_EAN13.docx");
}

public void FieldMergeBarcode_CODE39()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a CODE39 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "CODE39";
    field.BarcodeValue = "MyCODE39Barcode";
    field.AddStartStopChar = true;

    Assert.AreEqual(" MERGEBARCODE  MyCODE39Barcode CODE39 \\d", field.GetFieldCode());
    builder.Writeln();

    DataTable table = CreateTable("Barcodes", new[] { "MyCODE39Barcode" },
        new[,] { { "12345ABCDE" }, { "67890FGHIJ" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"12345ABCDE\" CODE39 \\d",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"67890FGHIJ\" CODE39 \\d",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_CODE39.docx");
}

public void FieldMergeBarcode_ITF14()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a ITF14 barcode
    FieldMergeBarcode field = (FieldMergeBarcode) builder.InsertField(FieldType.FieldMergeBarcode, true);
    field.BarcodeType = "ITF14";
    field.BarcodeValue = "MyITF14Barcode";
    field.CaseCodeStyle = "STD";

    Assert.AreEqual(" MERGEBARCODE  MyITF14Barcode ITF14 \\c STD", field.GetFieldCode());

    DataTable table = CreateTable("Barcodes", new[] { "MyITF14Barcode" },
        new[,] { { "09312345678907" }, { "1234567891234" } });

    doc.MailMerge.Execute(table);

    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[0].Type);
    Assert.AreEqual(FieldType.FieldDisplayBarcode, doc.Range.Fields[1].Type);

    Assert.AreEqual("DISPLAYBARCODE \"09312345678907\" ITF14 \\c STD",
        doc.Range.Fields[0].GetFieldCode());
    Assert.AreEqual("DISPLAYBARCODE \"1234567891234\" ITF14 \\c STD",
        doc.Range.Fields[1].GetFieldCode());

    doc.Save(ArtifactsDir + "Field.MergeBarcode_ITF14.docx");
}

/// <summary>
/// Creates a DataTable named by dataTableName, adds a column for every element in columnNames
/// and fills rows with data from dataSet
/// </summary>
public DataTable CreateTable(string dataTableName, string[] columnNames, object[,] dataSet)
{
    if (dataTableName != string.Empty || columnNames.Length != 0)
    {
        DataTable table = new DataTable(dataTableName);

        foreach (string columnName in columnNames)
        {
            table.Columns.Add(columnName);
        }

        foreach (object data in dataSet)
        {
            table.Rows.Add(data);
        }

        return table;
    }

    throw new ArgumentException("DataTable name and Column name must be declared.");
}

See Also

FieldMergeBarcode Class | Aspose.Words.Fields Namespace


FieldMergeField Class

Implements the MERGEFIELD field.

For a list of all members of this type, see FieldMergeField Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldMergeField

[Visual Basic]
Public Class FieldMergeField
Inherits Field
[C#]
public class FieldMergeField : Field

Remarks

Retrieves the name of a data field within the merge characters in a mail merge main document. When the main document is merged with the selected data source, information from the specified data field is inserted in place of the merge field.

Example

Shows how to use MERGEFIELD fields to perform a mail merge.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Courtesy Title";
fieldMergeField.IsMapped = true;
fieldMergeField.IsVerticalFormatting = false;
fieldMergeField.TextBefore = "Dear ";
fieldMergeField.TextAfter = " ";

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Last Name";
fieldMergeField.TextAfter = ":";

doc.UpdateFields();
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MergeField.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMergeField Members | Aspose.Words.Fields Namespace


FieldMergeField Members

FieldMergeField overview

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FieldName | Gets or sets the name of a data field.
FieldNameNoPrefix | Returns just the name of the data field. Any prefix is stripped to the prefix property.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsMapped | Gets or sets whether this field is a mapped field.
IsVerticalFormatting | Gets or sets whether to enable character conversion for vertical formatting.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
TextAfter | Gets or sets the text to be inserted after the field if the field is not blank.
TextBefore | Gets or sets the text to be inserted before the field if the field is not blank.
Type |

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


FieldMergeField Properties

The properties of the FieldMergeField class are listed below. For a complete list of FieldMergeField class members, see the FieldMergeField Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FieldName | Gets or sets the name of a data field.
FieldNameNoPrefix | Returns just the name of the data field. Any prefix is stripped to the prefix property.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsMapped | Gets or sets whether this field is a mapped field.
IsVerticalFormatting | Gets or sets whether to enable character conversion for vertical formatting.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
TextAfter | Gets or sets the text to be inserted after the field if the field is not blank.
TextBefore | Gets or sets the text to be inserted before the field if the field is not blank.
Type |

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


FieldName Property

Aspose.Words

FieldMergeField.FieldName Property

Gets or sets the name of a data field.

[Visual Basic]
Public Property FieldName As String
[C#]
public string FieldName {get; set;}

Example

Shows how to use MERGEFIELD fields to perform a mail merge.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Courtesy Title";
fieldMergeField.IsMapped = true;
fieldMergeField.IsVerticalFormatting = false;
fieldMergeField.TextBefore = "Dear ";
fieldMergeField.TextAfter = " ";

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Last Name";
fieldMergeField.TextAfter = ":";

doc.UpdateFields();
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MergeField.docx");

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


FieldNameNoPrefix Property

Aspose.Words

FieldMergeField.FieldNameNoPrefix Property

Returns just the name of the data field. Any prefix is stripped to the prefix property.

[Visual Basic]
Public ReadOnly Property FieldNameNoPrefix As String
[C#]
public string FieldNameNoPrefix {get;}

Example

Shows how to use MERGEFIELD fields to perform a mail merge.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Courtesy Title";
fieldMergeField.IsMapped = true;
fieldMergeField.IsVerticalFormatting = false;
fieldMergeField.TextBefore = "Dear ";
fieldMergeField.TextAfter = " ";

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Last Name";
fieldMergeField.TextAfter = ":";

doc.UpdateFields();
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MergeField.docx");

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


IsMapped Property

Aspose.Words

FieldMergeField.IsMapped Property

Gets or sets whether this field is a mapped field.

[Visual Basic]
Public Property IsMapped As Boolean
[C#]
public bool IsMapped {get; set;}

Example

Shows how to use MERGEFIELD fields to perform a mail merge.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Courtesy Title";
fieldMergeField.IsMapped = true;
fieldMergeField.IsVerticalFormatting = false;
fieldMergeField.TextBefore = "Dear ";
fieldMergeField.TextAfter = " ";

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Last Name";
fieldMergeField.TextAfter = ":";

doc.UpdateFields();
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MergeField.docx");

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


IsVerticalFormatting Property

Aspose.Words

FieldMergeField.IsVerticalFormatting Property

Gets or sets whether to enable character conversion for vertical formatting.

[Visual Basic]
Public Property IsVerticalFormatting As Boolean
[C#]
public bool IsVerticalFormatting {get; set;}

Example

Shows how to use MERGEFIELD fields to perform a mail merge.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Courtesy Title";
fieldMergeField.IsMapped = true;
fieldMergeField.IsVerticalFormatting = false;
fieldMergeField.TextBefore = "Dear ";
fieldMergeField.TextAfter = " ";

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Last Name";
fieldMergeField.TextAfter = ":";

doc.UpdateFields();
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MergeField.docx");

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


TextAfter Property

Aspose.Words

FieldMergeField.TextAfter Property

Gets or sets the text to be inserted after the field if the field is not blank.

[Visual Basic]
Public Property TextAfter As String
[C#]
public string TextAfter {get; set;}

Example

Shows how to use MERGEFIELD fields to perform a mail merge.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create data source for our merge fields
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Courtesy Title");
table.Columns.Add("First Name");
table.Columns.Add("Last Name");
table.Rows.Add("Mr.", "John", "Doe");
table.Rows.Add("Mrs.", "Jane", "Cardholder");

// Insert a merge field that corresponds to one of our columns and put text before and after it
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Courtesy Title";
fieldMergeField.IsMapped = true;
fieldMergeField.IsVerticalFormatting = false;
fieldMergeField.TextBefore = "Dear ";
fieldMergeField.TextAfter = " ";

// Insert another merge field for another column
// We don't need to use every column to perform a mail merge
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Last Name";
fieldMergeField.TextAfter = ":";

doc.UpdateFields();
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MergeField.docx");

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


TextBefore Property

Aspose.Words

FieldMergeField.TextBefore Property

Gets or sets the text to be inserted before the field if the field is not blank.

[Visual Basic]
Public Property TextBefore As String
[C#]
public string TextBefore {get; set;}

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


Type Property

Aspose.Words

FieldMergeField.Type Property

[Visual Basic]
Overrides Public ReadOnly Property Type As FieldType
[C#]
public override FieldType Type {get;}

See Also

FieldMergeField Class | Aspose.Words.Fields Namespace


FieldMergeRec Class

Implements the MERGEREC field.

For a list of all members of this type, see FieldMergeRec Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldMergeRec

[Visual Basic]
Public Class FieldMergeRec
Inherits Field
[C#]
public class FieldMergeRec : Field

Remarks

At the moment the MERGEREC and MERGESEQ fields implement the same functionality because we don't know for sure how to skip records in Aspose.Words mail merge.

Example

Shows how to number and count mail merge records in the output documents of a mail merge using MERGEREC and MERGESEQ fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a merge field
builder.Write("Dear ");
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
builder.Writeln(",");

// A MERGEREC field will print the row number of the data being merged
builder.Write("\nRow number of record in data source: ");
FieldMergeRec fieldMergeRec = (FieldMergeRec)builder.InsertField(FieldType.FieldMergeRec, true);

Assert.AreEqual(" MERGEREC ", fieldMergeRec.GetFieldCode());

// A MERGESEQ field will count the number of successful merges and print the current value on each respective page
// If no rows are skipped and the data source is not sorted, and no SKIP/SKIPIF/NEXT/NEXTIF fields are invoked,
// the MERGESEQ and MERGEREC fields will function the same
builder.Write("\nSuccessful merge number: ");
FieldMergeSeq fieldMergeSeq = (FieldMergeSeq)builder.InsertField(FieldType.FieldMergeSeq, true);

Assert.AreEqual(" MERGESEQ ", fieldMergeSeq.GetFieldCode());

// Insert a SKIPIF field, which will skip a merge if the name is "John Doe"
FieldSkipIf fieldSkipIf = (FieldSkipIf)builder.InsertField(FieldType.FieldSkipIf, true);
builder.MoveTo(fieldSkipIf.Separator);
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
fieldSkipIf.LeftExpression = "=";
fieldSkipIf.RightExpression = "John Doe";

// Create a data source with 3 rows, one of them having "John Doe" as a value for the "Name" column
// Since a SKIPIF field will be triggered once by that value, the output of our mail merge will have 2 pages instead of 3
// On page 1, the MERGESEQ and MERGEREC fields will both display "1"
// On page 2, the MERGEREC field will display "3" and the MERGESEQ field will display "2"
DataTable table = CreateTable("Employees", new[] { "Name" },
    new[,] { { "Jane Doe" }, { "John Doe" }, { "Joe Bloggs" } });

// Execute mail merge and save document
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MERGEREC.MERGESEQ.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMergeRec Members | Aspose.Words.Fields Namespace


FieldMergeRec Members

FieldMergeRec overview

Public Instance Constructors

FieldMergeRec Constructor Initializes a new instance of the FieldMergeRec class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldMergeRec Class | Aspose.Words.Fields Namespace


FieldMergeRec Constructor

Initializes a new instance of the FieldMergeRec class.

[Visual Basic]
Public Sub New()
[C#]
public FieldMergeRec();

See Also

FieldMergeRec Class | Aspose.Words.Fields Namespace


FieldMergeSeq Class

Implements the MERGESEQ field.

For a list of all members of this type, see FieldMergeSeq Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldMergeSeq

[Visual Basic]
Public Class FieldMergeSeq
Inherits Field
[C#]
public class FieldMergeSeq : Field

Remarks

At the moment the MERGEREC and MERGESEQ fields implement the same functionality because we don't know for sure how to skip records in Aspose.Words mail merge.

Example

Shows how to number and count mail merge records in the output documents of a mail merge using MERGEREC and MERGESEQ fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a merge field
builder.Write("Dear ");
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
builder.Writeln(",");

// A MERGEREC field will print the row number of the data being merged
builder.Write("\nRow number of record in data source: ");
FieldMergeRec fieldMergeRec = (FieldMergeRec)builder.InsertField(FieldType.FieldMergeRec, true);

Assert.AreEqual(" MERGEREC ", fieldMergeRec.GetFieldCode());

// A MERGESEQ field will count the number of successful merges and print the current value on each respective page
// If no rows are skipped and the data source is not sorted, and no SKIP/SKIPIF/NEXT/NEXTIF fields are invoked,
// the MERGESEQ and MERGEREC fields will function the same
builder.Write("\nSuccessful merge number: ");
FieldMergeSeq fieldMergeSeq = (FieldMergeSeq)builder.InsertField(FieldType.FieldMergeSeq, true);

Assert.AreEqual(" MERGESEQ ", fieldMergeSeq.GetFieldCode());

// Insert a SKIPIF field, which will skip a merge if the name is "John Doe"
FieldSkipIf fieldSkipIf = (FieldSkipIf)builder.InsertField(FieldType.FieldSkipIf, true);
builder.MoveTo(fieldSkipIf.Separator);
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
fieldSkipIf.LeftExpression = "=";
fieldSkipIf.RightExpression = "John Doe";

// Create a data source with 3 rows, one of them having "John Doe" as a value for the "Name" column
// Since a SKIPIF field will be triggered once by that value, the output of our mail merge will have 2 pages instead of 3
// On page 1, the MERGESEQ and MERGEREC fields will both display "1"
// On page 2, the MERGEREC field will display "3" and the MERGESEQ field will display "2"
DataTable table = CreateTable("Employees", new[] { "Name" },
    new[,] { { "Jane Doe" }, { "John Doe" }, { "Joe Bloggs" } });

// Execute mail merge and save document
doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.MERGEREC.MERGESEQ.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMergeSeq Members | Aspose.Words.Fields Namespace


FieldMergeSeq Members

FieldMergeSeq overview

Public Instance Constructors

FieldMergeSeq Constructor Initializes a new instance of the FieldMergeSeq class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldMergeSeq Class | Aspose.Words.Fields Namespace


FieldMergeSeq Constructor

Initializes a new instance of the FieldMergeSeq class.

[Visual Basic]
Public Sub New()
[C#]
public FieldMergeSeq();

See Also

FieldMergeSeq Class | Aspose.Words.Fields Namespace


FieldNext Class

Implements the NEXT field.

For a list of all members of this type, see FieldNext Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldNext

[Visual Basic]
Public Class FieldNext
Inherits Field
[C#]
public class FieldNext : Field

Remarks

Merges the next data record into the current resulting merged document, rather than starting a new merged document.

Example

Shows how to use NEXT/NEXTIF fields to merge more than one row into one page during a mail merge.

[C#]

public void FieldNext()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    // Create a data source for our mail merge with 3 rows,
    // This would normally amount to 3 pages in the output of a mail merge
    DataTable table = new DataTable("Employees");
    table.Columns.Add("Courtesy Title");
    table.Columns.Add("First Name");
    table.Columns.Add("Last Name");
    table.Rows.Add("Mr.", "John", "Doe");
    table.Rows.Add("Mrs.", "Jane", "Cardholder");
    table.Rows.Add("Mr.", "Joe", "Bloggs");

    // Insert a set of merge fields
    InsertMergeFields(builder, "First row: ");

    // If we have multiple merge fields with the same FieldName,
    // they will receive data from the same row of the data source and will display the same value after the merge
    // A NEXT field tells the mail merge instantly to move down one row,
    // so any upcoming merge fields will have data deposited from the next row
    // Make sure not to skip with a NEXT/NEXTIF field while on the last row
    FieldNext fieldNext = (FieldNext)builder.InsertField(FieldType.FieldNext, true);

    // These merge fields are the same as the ones as above but will take values from the second row
    InsertMergeFields(builder, "Second row: ");

    // A NEXTIF field has the same function as a NEXT field,
    // but it skips to the next row only if a condition expressed by the following 3 attributes is fulfilled
    FieldNextIf fieldNextIf = (FieldNextIf)builder.InsertField(FieldType.FieldNextIf, true);
    fieldNextIf.LeftExpression = "5";
    fieldNextIf.RightExpression = "2 + 3";
    fieldNextIf.ComparisonOperator = "=";

    // If the comparison asserted by the above field is correct,
    // the following 3 merge fields will take data from the third row
    // Otherwise, these fields will take data from row 2 again
    InsertMergeFields(builder, "Third row: ");

    // Our data source has 3 rows and we skipped rows twice, so our output will have one page
    // with data from all 3 rows
    doc.MailMerge.Execute(table);

    Assert.AreEqual(" NEXT ", fieldNext.GetFieldCode());
    Assert.AreEqual(" NEXTIF  5 = \"2 + 3\"", fieldNextIf.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.Next.docx");
}

/// <summary>
/// Uses a document builder to insert merge fields for a data table that has "Courtesy Title", "First Name" and "Last Name" columns
/// </summary>
public void InsertMergeFields(DocumentBuilder builder, string firstFieldTextBefore)
{
    InsertMergeField(builder, "Courtesy Title", firstFieldTextBefore, " ");
    InsertMergeField(builder, "First Name", null, " ");
    InsertMergeField(builder, "Last Name", null, null);
    builder.InsertParagraph();
}

/// <summary>
/// Uses a document builder to insert a merge field
/// </summary>
public void InsertMergeField(DocumentBuilder builder, string fieldName, string textBefore, string textAfter)
{
    FieldMergeField field = (FieldMergeField) builder.InsertField(FieldType.FieldMergeField, true);
    field.FieldName = fieldName;
    field.TextBefore = textBefore;
    field.TextAfter = textAfter;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldNext Members | Aspose.Words.Fields Namespace


FieldNext Members

FieldNext overview

Public Instance Constructors

FieldNext Constructor Initializes a new instance of the FieldNext class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldNext Class | Aspose.Words.Fields Namespace


FieldNext Constructor

Initializes a new instance of the FieldNext class.

[Visual Basic]
Public Sub New()
[C#]
public FieldNext();

See Also

FieldNext Class | Aspose.Words.Fields Namespace


FieldNextIf Class

Implements the NEXTIF field.

For a list of all members of this type, see FieldNextIf Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldNextIf

[Visual Basic]
Public Class FieldNextIf
Inherits Field
[C#]
public class FieldNextIf : Field

Remarks

Compares the values designated by the expressions LeftExpression and RightExpression in comparison using the operator designated by ComparisonOperator. If the comparison is true, the next data record is merged into the current merge document. (Merge fields that follow the NEXTIF in the main document are replaced by values from the next data record rather than the current data record.) If the comparison is false, the next data record is merged into a new merge document.

Example

Shows how to use NEXT/NEXTIF fields to merge more than one row into one page during a mail merge.

[C#]

public void FieldNext()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    // Create a data source for our mail merge with 3 rows,
    // This would normally amount to 3 pages in the output of a mail merge
    DataTable table = new DataTable("Employees");
    table.Columns.Add("Courtesy Title");
    table.Columns.Add("First Name");
    table.Columns.Add("Last Name");
    table.Rows.Add("Mr.", "John", "Doe");
    table.Rows.Add("Mrs.", "Jane", "Cardholder");
    table.Rows.Add("Mr.", "Joe", "Bloggs");

    // Insert a set of merge fields
    InsertMergeFields(builder, "First row: ");

    // If we have multiple merge fields with the same FieldName,
    // they will receive data from the same row of the data source and will display the same value after the merge
    // A NEXT field tells the mail merge instantly to move down one row,
    // so any upcoming merge fields will have data deposited from the next row
    // Make sure not to skip with a NEXT/NEXTIF field while on the last row
    FieldNext fieldNext = (FieldNext)builder.InsertField(FieldType.FieldNext, true);

    // These merge fields are the same as the ones as above but will take values from the second row
    InsertMergeFields(builder, "Second row: ");

    // A NEXTIF field has the same function as a NEXT field,
    // but it skips to the next row only if a condition expressed by the following 3 attributes is fulfilled
    FieldNextIf fieldNextIf = (FieldNextIf)builder.InsertField(FieldType.FieldNextIf, true);
    fieldNextIf.LeftExpression = "5";
    fieldNextIf.RightExpression = "2 + 3";
    fieldNextIf.ComparisonOperator = "=";

    // If the comparison asserted by the above field is correct,
    // the following 3 merge fields will take data from the third row
    // Otherwise, these fields will take data from row 2 again
    InsertMergeFields(builder, "Third row: ");

    // Our data source has 3 rows and we skipped rows twice, so our output will have one page
    // with data from all 3 rows
    doc.MailMerge.Execute(table);

    Assert.AreEqual(" NEXT ", fieldNext.GetFieldCode());
    Assert.AreEqual(" NEXTIF  5 = \"2 + 3\"", fieldNextIf.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.Next.docx");
}

/// <summary>
/// Uses a document builder to insert merge fields for a data table that has "Courtesy Title", "First Name" and "Last Name" columns
/// </summary>
public void InsertMergeFields(DocumentBuilder builder, string firstFieldTextBefore)
{
    InsertMergeField(builder, "Courtesy Title", firstFieldTextBefore, " ");
    InsertMergeField(builder, "First Name", null, " ");
    InsertMergeField(builder, "Last Name", null, null);
    builder.InsertParagraph();
}

/// <summary>
/// Uses a document builder to insert a merge field
/// </summary>
public void InsertMergeField(DocumentBuilder builder, string fieldName, string textBefore, string textAfter)
{
    FieldMergeField field = (FieldMergeField) builder.InsertField(FieldType.FieldMergeField, true);
    field.FieldName = fieldName;
    field.TextBefore = textBefore;
    field.TextAfter = textAfter;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldNextIf Members | Aspose.Words.Fields Namespace


FieldNextIf Members

FieldNextIf overview

Public Instance Constructors

FieldNextIf Constructor Initializes a new instance of the FieldNextIf class.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldNextIf Class | Aspose.Words.Fields Namespace


FieldNextIf Constructor

Initializes a new instance of the FieldNextIf class.

[Visual Basic]
Public Sub New()
[C#]
public FieldNextIf();

See Also

FieldNextIf Class | Aspose.Words.Fields Namespace


FieldNextIf Properties

The properties of the FieldNextIf class are listed below. For a complete list of FieldNextIf class members, see the FieldNextIf Members topic.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldNextIf Class | Aspose.Words.Fields Namespace


ComparisonOperator Property

Aspose.Words

FieldNextIf.ComparisonOperator Property

Gets or sets the comparison operator.

[Visual Basic]
Public Property ComparisonOperator As String
[C#]
public string ComparisonOperator {get; set;}

Example

Shows how to use NEXT/NEXTIF fields to merge more than one row into one page during a mail merge.

[C#]

public void FieldNext()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    // Create a data source for our mail merge with 3 rows,
    // This would normally amount to 3 pages in the output of a mail merge
    DataTable table = new DataTable("Employees");
    table.Columns.Add("Courtesy Title");
    table.Columns.Add("First Name");
    table.Columns.Add("Last Name");
    table.Rows.Add("Mr.", "John", "Doe");
    table.Rows.Add("Mrs.", "Jane", "Cardholder");
    table.Rows.Add("Mr.", "Joe", "Bloggs");

    // Insert a set of merge fields
    InsertMergeFields(builder, "First row: ");

    // If we have multiple merge fields with the same FieldName,
    // they will receive data from the same row of the data source and will display the same value after the merge
    // A NEXT field tells the mail merge instantly to move down one row,
    // so any upcoming merge fields will have data deposited from the next row
    // Make sure not to skip with a NEXT/NEXTIF field while on the last row
    FieldNext fieldNext = (FieldNext)builder.InsertField(FieldType.FieldNext, true);

    // These merge fields are the same as the ones as above but will take values from the second row
    InsertMergeFields(builder, "Second row: ");

    // A NEXTIF field has the same function as a NEXT field,
    // but it skips to the next row only if a condition expressed by the following 3 attributes is fulfilled
    FieldNextIf fieldNextIf = (FieldNextIf)builder.InsertField(FieldType.FieldNextIf, true);
    fieldNextIf.LeftExpression = "5";
    fieldNextIf.RightExpression = "2 + 3";
    fieldNextIf.ComparisonOperator = "=";

    // If the comparison asserted by the above field is correct,
    // the following 3 merge fields will take data from the third row
    // Otherwise, these fields will take data from row 2 again
    InsertMergeFields(builder, "Third row: ");

    // Our data source has 3 rows and we skipped rows twice, so our output will have one page
    // with data from all 3 rows
    doc.MailMerge.Execute(table);

    Assert.AreEqual(" NEXT ", fieldNext.GetFieldCode());
    Assert.AreEqual(" NEXTIF  5 = \"2 + 3\"", fieldNextIf.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.Next.docx");
}

/// <summary>
/// Uses a document builder to insert merge fields for a data table that has "Courtesy Title", "First Name" and "Last Name" columns
/// </summary>
public void InsertMergeFields(DocumentBuilder builder, string firstFieldTextBefore)
{
    InsertMergeField(builder, "Courtesy Title", firstFieldTextBefore, " ");
    InsertMergeField(builder, "First Name", null, " ");
    InsertMergeField(builder, "Last Name", null, null);
    builder.InsertParagraph();
}

/// <summary>
/// Uses a document builder to insert a merge field
/// </summary>
public void InsertMergeField(DocumentBuilder builder, string fieldName, string textBefore, string textAfter)
{
    FieldMergeField field = (FieldMergeField) builder.InsertField(FieldType.FieldMergeField, true);
    field.FieldName = fieldName;
    field.TextBefore = textBefore;
    field.TextAfter = textAfter;
}

See Also

FieldNextIf Class | Aspose.Words.Fields Namespace


LeftExpression Property

Aspose.Words

FieldNextIf.LeftExpression Property

Gets or sets the left part of the comparison expression.

[Visual Basic]
Public Property LeftExpression As String
[C#]
public string LeftExpression {get; set;}

Example

Shows how to use NEXT/NEXTIF fields to merge more than one row into one page during a mail merge.

[C#]

public void FieldNext()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    // Create a data source for our mail merge with 3 rows,
    // This would normally amount to 3 pages in the output of a mail merge
    DataTable table = new DataTable("Employees");
    table.Columns.Add("Courtesy Title");
    table.Columns.Add("First Name");
    table.Columns.Add("Last Name");
    table.Rows.Add("Mr.", "John", "Doe");
    table.Rows.Add("Mrs.", "Jane", "Cardholder");
    table.Rows.Add("Mr.", "Joe", "Bloggs");

    // Insert a set of merge fields
    InsertMergeFields(builder, "First row: ");

    // If we have multiple merge fields with the same FieldName,
    // they will receive data from the same row of the data source and will display the same value after the merge
    // A NEXT field tells the mail merge instantly to move down one row,
    // so any upcoming merge fields will have data deposited from the next row
    // Make sure not to skip with a NEXT/NEXTIF field while on the last row
    FieldNext fieldNext = (FieldNext)builder.InsertField(FieldType.FieldNext, true);

    // These merge fields are the same as the ones as above but will take values from the second row
    InsertMergeFields(builder, "Second row: ");

    // A NEXTIF field has the same function as a NEXT field,
    // but it skips to the next row only if a condition expressed by the following 3 attributes is fulfilled
    FieldNextIf fieldNextIf = (FieldNextIf)builder.InsertField(FieldType.FieldNextIf, true);
    fieldNextIf.LeftExpression = "5";
    fieldNextIf.RightExpression = "2 + 3";
    fieldNextIf.ComparisonOperator = "=";

    // If the comparison asserted by the above field is correct,
    // the following 3 merge fields will take data from the third row
    // Otherwise, these fields will take data from row 2 again
    InsertMergeFields(builder, "Third row: ");

    // Our data source has 3 rows and we skipped rows twice, so our output will have one page
    // with data from all 3 rows
    doc.MailMerge.Execute(table);

    Assert.AreEqual(" NEXT ", fieldNext.GetFieldCode());
    Assert.AreEqual(" NEXTIF  5 = \"2 + 3\"", fieldNextIf.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.Next.docx");
}

/// <summary>
/// Uses a document builder to insert merge fields for a data table that has "Courtesy Title", "First Name" and "Last Name" columns
/// </summary>
public void InsertMergeFields(DocumentBuilder builder, string firstFieldTextBefore)
{
    InsertMergeField(builder, "Courtesy Title", firstFieldTextBefore, " ");
    InsertMergeField(builder, "First Name", null, " ");
    InsertMergeField(builder, "Last Name", null, null);
    builder.InsertParagraph();
}

/// <summary>
/// Uses a document builder to insert a merge field
/// </summary>
public void InsertMergeField(DocumentBuilder builder, string fieldName, string textBefore, string textAfter)
{
    FieldMergeField field = (FieldMergeField) builder.InsertField(FieldType.FieldMergeField, true);
    field.FieldName = fieldName;
    field.TextBefore = textBefore;
    field.TextAfter = textAfter;
}

See Also

FieldNextIf Class | Aspose.Words.Fields Namespace


RightExpression Property

Aspose.Words

FieldNextIf.RightExpression Property

Gets or sets the right part of the comparison expression.

[Visual Basic]
Public Property RightExpression As String
[C#]
public string RightExpression {get; set;}

Example

Shows how to use NEXT/NEXTIF fields to merge more than one row into one page during a mail merge.

[C#]

public void FieldNext()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    // Create a data source for our mail merge with 3 rows,
    // This would normally amount to 3 pages in the output of a mail merge
    DataTable table = new DataTable("Employees");
    table.Columns.Add("Courtesy Title");
    table.Columns.Add("First Name");
    table.Columns.Add("Last Name");
    table.Rows.Add("Mr.", "John", "Doe");
    table.Rows.Add("Mrs.", "Jane", "Cardholder");
    table.Rows.Add("Mr.", "Joe", "Bloggs");

    // Insert a set of merge fields
    InsertMergeFields(builder, "First row: ");

    // If we have multiple merge fields with the same FieldName,
    // they will receive data from the same row of the data source and will display the same value after the merge
    // A NEXT field tells the mail merge instantly to move down one row,
    // so any upcoming merge fields will have data deposited from the next row
    // Make sure not to skip with a NEXT/NEXTIF field while on the last row
    FieldNext fieldNext = (FieldNext)builder.InsertField(FieldType.FieldNext, true);

    // These merge fields are the same as the ones as above but will take values from the second row
    InsertMergeFields(builder, "Second row: ");

    // A NEXTIF field has the same function as a NEXT field,
    // but it skips to the next row only if a condition expressed by the following 3 attributes is fulfilled
    FieldNextIf fieldNextIf = (FieldNextIf)builder.InsertField(FieldType.FieldNextIf, true);
    fieldNextIf.LeftExpression = "5";
    fieldNextIf.RightExpression = "2 + 3";
    fieldNextIf.ComparisonOperator = "=";

    // If the comparison asserted by the above field is correct,
    // the following 3 merge fields will take data from the third row
    // Otherwise, these fields will take data from row 2 again
    InsertMergeFields(builder, "Third row: ");

    // Our data source has 3 rows and we skipped rows twice, so our output will have one page
    // with data from all 3 rows
    doc.MailMerge.Execute(table);

    Assert.AreEqual(" NEXT ", fieldNext.GetFieldCode());
    Assert.AreEqual(" NEXTIF  5 = \"2 + 3\"", fieldNextIf.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.Next.docx");
}

/// <summary>
/// Uses a document builder to insert merge fields for a data table that has "Courtesy Title", "First Name" and "Last Name" columns
/// </summary>
public void InsertMergeFields(DocumentBuilder builder, string firstFieldTextBefore)
{
    InsertMergeField(builder, "Courtesy Title", firstFieldTextBefore, " ");
    InsertMergeField(builder, "First Name", null, " ");
    InsertMergeField(builder, "Last Name", null, null);
    builder.InsertParagraph();
}

/// <summary>
/// Uses a document builder to insert a merge field
/// </summary>
public void InsertMergeField(DocumentBuilder builder, string fieldName, string textBefore, string textAfter)
{
    FieldMergeField field = (FieldMergeField) builder.InsertField(FieldType.FieldMergeField, true);
    field.FieldName = fieldName;
    field.TextBefore = textBefore;
    field.TextAfter = textAfter;
}

See Also

FieldNextIf Class | Aspose.Words.Fields Namespace


FieldNoteRef Class

Implements the NOTEREF field.

For a list of all members of this type, see FieldNoteRef Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldNoteRef

[Visual Basic]
Public Class FieldNoteRef
Inherits Field
[C#]
public class FieldNoteRef : Field

Remarks

Inserts the mark of the footnote or endnote that is marked by the specified bookmark.

Example

Shows to insert NOTEREF fields and modify their appearance.

[C#]

public void FieldNoteRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Create a boomkark with a footnote for the NOTEREF field to reference
    InsertBookmarkWithFootnote(builder, "MyBookmark1", "Contents of MyBookmark1", "Footnote from MyBookmark1");

    // This NOTEREF field will display just the number of the footnote inside the referenced bookmark
    // Setting the InsertHyperlink attribute lets us jump to the bookmark by Ctrl + clicking the field
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h",
        InsertFieldNoteRef(builder, "MyBookmark2", true, false, false, "Hyperlink to Bookmark2, with footnote number ").GetFieldCode());

    // When using the \p flag, after the footnote number the field also displays the position of the bookmark relative to the field
    // Bookmark1 is above this field and contains footnote number 1, so the result will be "1 above" on update
    Assert.AreEqual(" NOTEREF  MyBookmark1 \\h \\p",
        InsertFieldNoteRef(builder, "MyBookmark1", true, true, false, "Bookmark1, with footnote number ").GetFieldCode());

    // Bookmark2 is below this field and contains footnote number 2, so the field will display "2 below"
    // The \f flag makes the number 2 appear in the same format as the footnote number label in the actual text
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h \\f \\p",
        InsertFieldNoteRef(builder, "MyBookmark2", true, true, true, "Bookmark2, with footnote number ").GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);
    InsertBookmarkWithFootnote(builder, "MyBookmark2", "Contents of MyBookmark2", "Footnote from MyBookmark2");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.NoteRef.docx");
}

/// <summary>
/// Uses a document builder to insert a NOTEREF field and sets its attributes
/// </summary>
private FieldNoteRef InsertFieldNoteRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, bool insertReferenceMark, string textBefore)
{
    builder.Write(textBefore);

    FieldNoteRef field = (FieldNoteRef)builder.InsertField(FieldType.FieldNoteRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertReferenceMark = insertReferenceMark;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark with a footnote at the end
/// </summary>
private void InsertBookmarkWithFootnote(DocumentBuilder builder, string bookmarkName, string bookmarkText, string footnoteText)
{
    builder.StartBookmark(bookmarkName);
    builder.Write(bookmarkText);
    builder.InsertFootnote(FootnoteType.Footnote, footnoteText);
    builder.EndBookmark(bookmarkName);
    builder.Writeln();
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldNoteRef Members | Aspose.Words.Fields Namespace


FieldNoteRef Members

FieldNoteRef overview

Public Instance Constructors

FieldNoteRef Constructor Initializes a new instance of the FieldNoteRef class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertHyperlink | Gets or sets whether to insert a hyperlink to the bookmarked paragraph.
InsertReferenceMark | Inserts the reference mark with the same character formatting as the Footnote Reference or Endnote Reference style.
InsertRelativePosition | Gets or sets whether to insert a relative position of the bookmarked paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


FieldNoteRef Constructor

Initializes a new instance of the FieldNoteRef class.

[Visual Basic]
Public Sub New()
[C#]
public FieldNoteRef();

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


FieldNoteRef Properties

The properties of the FieldNoteRef class are listed below. For a complete list of FieldNoteRef class members, see the FieldNoteRef Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertHyperlink | Gets or sets whether to insert a hyperlink to the bookmarked paragraph.
InsertReferenceMark | Inserts the reference mark with the same character formatting as the Footnote Reference or Endnote Reference style.
InsertRelativePosition | Gets or sets whether to insert a relative position of the bookmarked paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldNoteRef.BookmarkName Property

Gets or sets the name of the bookmark.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows to insert NOTEREF fields and modify their appearance.

[C#]

public void FieldNoteRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Create a boomkark with a footnote for the NOTEREF field to reference
    InsertBookmarkWithFootnote(builder, "MyBookmark1", "Contents of MyBookmark1", "Footnote from MyBookmark1");

    // This NOTEREF field will display just the number of the footnote inside the referenced bookmark
    // Setting the InsertHyperlink attribute lets us jump to the bookmark by Ctrl + clicking the field
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h",
        InsertFieldNoteRef(builder, "MyBookmark2", true, false, false, "Hyperlink to Bookmark2, with footnote number ").GetFieldCode());

    // When using the \p flag, after the footnote number the field also displays the position of the bookmark relative to the field
    // Bookmark1 is above this field and contains footnote number 1, so the result will be "1 above" on update
    Assert.AreEqual(" NOTEREF  MyBookmark1 \\h \\p",
        InsertFieldNoteRef(builder, "MyBookmark1", true, true, false, "Bookmark1, with footnote number ").GetFieldCode());

    // Bookmark2 is below this field and contains footnote number 2, so the field will display "2 below"
    // The \f flag makes the number 2 appear in the same format as the footnote number label in the actual text
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h \\f \\p",
        InsertFieldNoteRef(builder, "MyBookmark2", true, true, true, "Bookmark2, with footnote number ").GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);
    InsertBookmarkWithFootnote(builder, "MyBookmark2", "Contents of MyBookmark2", "Footnote from MyBookmark2");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.NoteRef.docx");
}

/// <summary>
/// Uses a document builder to insert a NOTEREF field and sets its attributes
/// </summary>
private FieldNoteRef InsertFieldNoteRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, bool insertReferenceMark, string textBefore)
{
    builder.Write(textBefore);

    FieldNoteRef field = (FieldNoteRef)builder.InsertField(FieldType.FieldNoteRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertReferenceMark = insertReferenceMark;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark with a footnote at the end
/// </summary>
private void InsertBookmarkWithFootnote(DocumentBuilder builder, string bookmarkName, string bookmarkText, string footnoteText)
{
    builder.StartBookmark(bookmarkName);
    builder.Write(bookmarkText);
    builder.InsertFootnote(FootnoteType.Footnote, footnoteText);
    builder.EndBookmark(bookmarkName);
    builder.Writeln();
}

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


InsertHyperlink Property

Aspose.Words

FieldNoteRef.InsertHyperlink Property

Gets or sets whether to insert a hyperlink to the bookmarked paragraph.

[Visual Basic]
Public Property InsertHyperlink As Boolean
[C#]
public bool InsertHyperlink {get; set;}

Example

Shows to insert NOTEREF fields and modify their appearance.

[C#]

public void FieldNoteRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Create a boomkark with a footnote for the NOTEREF field to reference
    InsertBookmarkWithFootnote(builder, "MyBookmark1", "Contents of MyBookmark1", "Footnote from MyBookmark1");

    // This NOTEREF field will display just the number of the footnote inside the referenced bookmark
    // Setting the InsertHyperlink attribute lets us jump to the bookmark by Ctrl + clicking the field
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h",
        InsertFieldNoteRef(builder, "MyBookmark2", true, false, false, "Hyperlink to Bookmark2, with footnote number ").GetFieldCode());

    // When using the \p flag, after the footnote number the field also displays the position of the bookmark relative to the field
    // Bookmark1 is above this field and contains footnote number 1, so the result will be "1 above" on update
    Assert.AreEqual(" NOTEREF  MyBookmark1 \\h \\p",
        InsertFieldNoteRef(builder, "MyBookmark1", true, true, false, "Bookmark1, with footnote number ").GetFieldCode());

    // Bookmark2 is below this field and contains footnote number 2, so the field will display "2 below"
    // The \f flag makes the number 2 appear in the same format as the footnote number label in the actual text
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h \\f \\p",
        InsertFieldNoteRef(builder, "MyBookmark2", true, true, true, "Bookmark2, with footnote number ").GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);
    InsertBookmarkWithFootnote(builder, "MyBookmark2", "Contents of MyBookmark2", "Footnote from MyBookmark2");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.NoteRef.docx");
}

/// <summary>
/// Uses a document builder to insert a NOTEREF field and sets its attributes
/// </summary>
private FieldNoteRef InsertFieldNoteRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, bool insertReferenceMark, string textBefore)
{
    builder.Write(textBefore);

    FieldNoteRef field = (FieldNoteRef)builder.InsertField(FieldType.FieldNoteRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertReferenceMark = insertReferenceMark;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark with a footnote at the end
/// </summary>
private void InsertBookmarkWithFootnote(DocumentBuilder builder, string bookmarkName, string bookmarkText, string footnoteText)
{
    builder.StartBookmark(bookmarkName);
    builder.Write(bookmarkText);
    builder.InsertFootnote(FootnoteType.Footnote, footnoteText);
    builder.EndBookmark(bookmarkName);
    builder.Writeln();
}

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


InsertReferenceMark Property

Aspose.Words

FieldNoteRef.InsertReferenceMark Property

Inserts the reference mark with the same character formatting as the Footnote Reference or Endnote Reference style.

[Visual Basic]
Public Property InsertReferenceMark As Boolean
[C#]
public bool InsertReferenceMark {get; set;}

Example

Shows to insert NOTEREF fields and modify their appearance.

[C#]

public void FieldNoteRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Create a boomkark with a footnote for the NOTEREF field to reference
    InsertBookmarkWithFootnote(builder, "MyBookmark1", "Contents of MyBookmark1", "Footnote from MyBookmark1");

    // This NOTEREF field will display just the number of the footnote inside the referenced bookmark
    // Setting the InsertHyperlink attribute lets us jump to the bookmark by Ctrl + clicking the field
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h",
        InsertFieldNoteRef(builder, "MyBookmark2", true, false, false, "Hyperlink to Bookmark2, with footnote number ").GetFieldCode());

    // When using the \p flag, after the footnote number the field also displays the position of the bookmark relative to the field
    // Bookmark1 is above this field and contains footnote number 1, so the result will be "1 above" on update
    Assert.AreEqual(" NOTEREF  MyBookmark1 \\h \\p",
        InsertFieldNoteRef(builder, "MyBookmark1", true, true, false, "Bookmark1, with footnote number ").GetFieldCode());

    // Bookmark2 is below this field and contains footnote number 2, so the field will display "2 below"
    // The \f flag makes the number 2 appear in the same format as the footnote number label in the actual text
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h \\f \\p",
        InsertFieldNoteRef(builder, "MyBookmark2", true, true, true, "Bookmark2, with footnote number ").GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);
    InsertBookmarkWithFootnote(builder, "MyBookmark2", "Contents of MyBookmark2", "Footnote from MyBookmark2");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.NoteRef.docx");
}

/// <summary>
/// Uses a document builder to insert a NOTEREF field and sets its attributes
/// </summary>
private FieldNoteRef InsertFieldNoteRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, bool insertReferenceMark, string textBefore)
{
    builder.Write(textBefore);

    FieldNoteRef field = (FieldNoteRef)builder.InsertField(FieldType.FieldNoteRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertReferenceMark = insertReferenceMark;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark with a footnote at the end
/// </summary>
private void InsertBookmarkWithFootnote(DocumentBuilder builder, string bookmarkName, string bookmarkText, string footnoteText)
{
    builder.StartBookmark(bookmarkName);
    builder.Write(bookmarkText);
    builder.InsertFootnote(FootnoteType.Footnote, footnoteText);
    builder.EndBookmark(bookmarkName);
    builder.Writeln();
}

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


InsertRelativePosition Property

Aspose.Words

FieldNoteRef.InsertRelativePosition Property

Gets or sets whether to insert a relative position of the bookmarked paragraph.

[Visual Basic]
Public Property InsertRelativePosition As Boolean
[C#]
public bool InsertRelativePosition {get; set;}

Example

Shows to insert NOTEREF fields and modify their appearance.

[C#]

public void FieldNoteRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Create a boomkark with a footnote for the NOTEREF field to reference
    InsertBookmarkWithFootnote(builder, "MyBookmark1", "Contents of MyBookmark1", "Footnote from MyBookmark1");

    // This NOTEREF field will display just the number of the footnote inside the referenced bookmark
    // Setting the InsertHyperlink attribute lets us jump to the bookmark by Ctrl + clicking the field
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h",
        InsertFieldNoteRef(builder, "MyBookmark2", true, false, false, "Hyperlink to Bookmark2, with footnote number ").GetFieldCode());

    // When using the \p flag, after the footnote number the field also displays the position of the bookmark relative to the field
    // Bookmark1 is above this field and contains footnote number 1, so the result will be "1 above" on update
    Assert.AreEqual(" NOTEREF  MyBookmark1 \\h \\p",
        InsertFieldNoteRef(builder, "MyBookmark1", true, true, false, "Bookmark1, with footnote number ").GetFieldCode());

    // Bookmark2 is below this field and contains footnote number 2, so the field will display "2 below"
    // The \f flag makes the number 2 appear in the same format as the footnote number label in the actual text
    Assert.AreEqual(" NOTEREF  MyBookmark2 \\h \\f \\p",
        InsertFieldNoteRef(builder, "MyBookmark2", true, true, true, "Bookmark2, with footnote number ").GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);
    InsertBookmarkWithFootnote(builder, "MyBookmark2", "Contents of MyBookmark2", "Footnote from MyBookmark2");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.NoteRef.docx");
}

/// <summary>
/// Uses a document builder to insert a NOTEREF field and sets its attributes
/// </summary>
private FieldNoteRef InsertFieldNoteRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, bool insertReferenceMark, string textBefore)
{
    builder.Write(textBefore);

    FieldNoteRef field = (FieldNoteRef)builder.InsertField(FieldType.FieldNoteRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertReferenceMark = insertReferenceMark;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark with a footnote at the end
/// </summary>
private void InsertBookmarkWithFootnote(DocumentBuilder builder, string bookmarkName, string bookmarkText, string footnoteText)
{
    builder.StartBookmark(bookmarkName);
    builder.Write(bookmarkText);
    builder.InsertFootnote(FootnoteType.Footnote, footnoteText);
    builder.EndBookmark(bookmarkName);
    builder.Writeln();
}

See Also

FieldNoteRef Class | Aspose.Words.Fields Namespace


FieldNumChars Class

Implements the NUMCHARS field.

For a list of all members of this type, see FieldNumChars Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldNumChars

[Visual Basic]
Public Class FieldNumChars
Inherits Field
[C#]
public class FieldNumChars : Field

Remarks

Retrieves the number of characters in the current document, as recorded in the Characters property of the built-in document properties.

Example

Shows how to use NUMCHARS, NUMWORDS, NUMPAGES and PAGE fields to track the size of our documents.

[C#]

// Open a document to which we want to add character/word/page counts
Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move the document builder to the footer, where we will store our fields
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Insert character and word counts
FieldNumChars fieldNumChars = (FieldNumChars)builder.InsertField(FieldType.FieldNumChars, true);
builder.Writeln(" characters");
FieldNumWords fieldNumWords = (FieldNumWords)builder.InsertField(FieldType.FieldNumWords, true);
builder.Writeln(" words");

// Insert a "Page x of y" page count
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Write("Page ");
FieldPage fieldPage = (FieldPage)builder.InsertField(FieldType.FieldPage, true);
builder.Write(" of ");
FieldNumPages fieldNumPages = (FieldNumPages)builder.InsertField(FieldType.FieldNumPages, true);

Assert.AreEqual(" NUMCHARS ", fieldNumChars.GetFieldCode());
Assert.AreEqual(" NUMWORDS ", fieldNumWords.GetFieldCode());
Assert.AreEqual(" NUMPAGES ", fieldNumPages.GetFieldCode());
Assert.AreEqual(" PAGE ", fieldPage.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Num.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldNumChars Members | Aspose.Words.Fields Namespace


FieldNumChars Members

FieldNumChars overview

Public Instance Constructors

FieldNumChars Constructor Initializes a new instance of the FieldNumChars class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldNumChars Class | Aspose.Words.Fields Namespace


FieldNumChars Constructor

Initializes a new instance of the FieldNumChars class.

[Visual Basic]
Public Sub New()
[C#]
public FieldNumChars();

See Also

FieldNumChars Class | Aspose.Words.Fields Namespace


FieldNumPages Class

Implements the NUMPAGES field.

For a list of all members of this type, see FieldNumPages Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldNumPages

[Visual Basic]
Public Class FieldNumPages
Inherits Field
[C#]
public class FieldNumPages : Field

Remarks

Retrieves the number of pages in the current document, as recorded in the Pages property of the built-in document properties.

Example

Shows how to use NUMCHARS, NUMWORDS, NUMPAGES and PAGE fields to track the size of our documents.

[C#]

// Open a document to which we want to add character/word/page counts
Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move the document builder to the footer, where we will store our fields
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Insert character and word counts
FieldNumChars fieldNumChars = (FieldNumChars)builder.InsertField(FieldType.FieldNumChars, true);
builder.Writeln(" characters");
FieldNumWords fieldNumWords = (FieldNumWords)builder.InsertField(FieldType.FieldNumWords, true);
builder.Writeln(" words");

// Insert a "Page x of y" page count
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Write("Page ");
FieldPage fieldPage = (FieldPage)builder.InsertField(FieldType.FieldPage, true);
builder.Write(" of ");
FieldNumPages fieldNumPages = (FieldNumPages)builder.InsertField(FieldType.FieldNumPages, true);

Assert.AreEqual(" NUMCHARS ", fieldNumChars.GetFieldCode());
Assert.AreEqual(" NUMWORDS ", fieldNumWords.GetFieldCode());
Assert.AreEqual(" NUMPAGES ", fieldNumPages.GetFieldCode());
Assert.AreEqual(" PAGE ", fieldPage.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Num.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldNumPages Members | Aspose.Words.Fields Namespace


FieldNumPages Members

FieldNumPages overview

Public Instance Constructors

FieldNumPages Constructor Initializes a new instance of the FieldNumPages class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldNumPages Class | Aspose.Words.Fields Namespace


FieldNumPages Constructor

Initializes a new instance of the FieldNumPages class.

[Visual Basic]
Public Sub New()
[C#]
public FieldNumPages();

See Also

FieldNumPages Class | Aspose.Words.Fields Namespace


FieldNumWords Class

Implements the NUMWORDS field.

For a list of all members of this type, see FieldNumWords Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldNumWords

[Visual Basic]
Public Class FieldNumWords
Inherits Field
[C#]
public class FieldNumWords : Field

Remarks

Retrieves the number of words in the current document, as recorded in the Words property of the built-in document properties.

Example

Shows how to use NUMCHARS, NUMWORDS, NUMPAGES and PAGE fields to track the size of our documents.

[C#]

// Open a document to which we want to add character/word/page counts
Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move the document builder to the footer, where we will store our fields
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Insert character and word counts
FieldNumChars fieldNumChars = (FieldNumChars)builder.InsertField(FieldType.FieldNumChars, true);
builder.Writeln(" characters");
FieldNumWords fieldNumWords = (FieldNumWords)builder.InsertField(FieldType.FieldNumWords, true);
builder.Writeln(" words");

// Insert a "Page x of y" page count
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Write("Page ");
FieldPage fieldPage = (FieldPage)builder.InsertField(FieldType.FieldPage, true);
builder.Write(" of ");
FieldNumPages fieldNumPages = (FieldNumPages)builder.InsertField(FieldType.FieldNumPages, true);

Assert.AreEqual(" NUMCHARS ", fieldNumChars.GetFieldCode());
Assert.AreEqual(" NUMWORDS ", fieldNumWords.GetFieldCode());
Assert.AreEqual(" NUMPAGES ", fieldNumPages.GetFieldCode());
Assert.AreEqual(" PAGE ", fieldPage.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Num.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldNumWords Members | Aspose.Words.Fields Namespace


FieldNumWords Members

FieldNumWords overview

Public Instance Constructors

FieldNumWords Constructor Initializes a new instance of the FieldNumWords class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldNumWords Class | Aspose.Words.Fields Namespace


FieldNumWords Constructor

Initializes a new instance of the FieldNumWords class.

[Visual Basic]
Public Sub New()
[C#]
public FieldNumWords();

See Also

FieldNumWords Class | Aspose.Words.Fields Namespace


FieldOcx Class

Implements the OCX field.

For a list of all members of this type, see FieldOcx Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldOcx

[Visual Basic]
Public Class FieldOcx
Inherits Field
[C#]
public class FieldOcx : Field

Example

Shows how to insert an OCX field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert an OCX field
FieldOcx field = (FieldOcx)builder.InsertField(FieldType.FieldOcx, true);

Assert.AreEqual(" OCX ", field.GetFieldCode());

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldOcx Members | Aspose.Words.Fields Namespace


FieldOcx Members

FieldOcx overview

Public Instance Constructors

FieldOcx Constructor Initializes a new instance of the FieldOcx class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldOcx Class | Aspose.Words.Fields Namespace


FieldOcx Constructor

Initializes a new instance of the FieldOcx class.

[Visual Basic]
Public Sub New()
[C#]
public FieldOcx();

See Also

FieldOcx Class | Aspose.Words.Fields Namespace


FieldOptions Class

Represents options to control field handling in a document.

For a list of all members of this type, see FieldOptions Members.

System.Object
Aspose.Words.Fields.FieldOptions

[Visual Basic]
Public Class FieldOptions
[C#]
public class FieldOptions

Example

Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.

[C#]

// Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
doc.MailMerge.Execute(new[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldOptions Members | Aspose.Words.Fields Namespace


FieldOptions Members

FieldOptions overview

Public Instance Properties

BarcodeGenerator | Gets or set custom barcode generator.
BuiltInTemplatesPaths | Gets or sets paths of MS Word built-in templates.
CurrentUser | Gets or sets the current user information.
CustomTocStyleSeparator | Gets or sets custom style separator for the \t switch in TOC field.
DefaultDocumentAuthor | Gets or sets default document author's name. If author's name is already specified in built-in document properties, this option is not considered.
FieldUpdateCultureProvider | Gets or sets a provider that returns a culture object specific for each particular field.
FieldUpdateCultureSource | Specifies what culture to use to format the field result.
FileName | Gets or sets the file name of the document.
IsBidiTextSupportedOnUpdate | Gets or sets the value indicating whether bidirectional text is fully supported during field update or not.
LegacyNumberFormat | Gets or sets the value indicating whether legacy (early than AW 13.10) number format for fields is enabled or not.
PreProcessCulture | Gets or sets the culture to preprocess field values.
ResultFormatter | Allows to control how the field result is formatted.
ToaCategories | Gets or sets the table of authorities categories.
UseInvariantCultureNumberFormat | Gets or sets the value indicating that number format is parsed using invariant culture or not
UserPromptRespondent | Gets or sets the respondent to user prompts during field update.

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


FieldOptions Properties

The properties of the FieldOptions class are listed below. For a complete list of FieldOptions class members, see the FieldOptions Members topic.

Public Instance Properties

BarcodeGenerator | Gets or set custom barcode generator.
BuiltInTemplatesPaths | Gets or sets paths of MS Word built-in templates.
CurrentUser | Gets or sets the current user information.
CustomTocStyleSeparator | Gets or sets custom style separator for the \t switch in TOC field.
DefaultDocumentAuthor | Gets or sets default document author's name. If author's name is already specified in built-in document properties, this option is not considered.
FieldUpdateCultureProvider | Gets or sets a provider that returns a culture object specific for each particular field.
FieldUpdateCultureSource | Specifies what culture to use to format the field result.
FileName | Gets or sets the file name of the document.
IsBidiTextSupportedOnUpdate | Gets or sets the value indicating whether bidirectional text is fully supported during field update or not.
LegacyNumberFormat | Gets or sets the value indicating whether legacy (early than AW 13.10) number format for fields is enabled or not.
PreProcessCulture | Gets or sets the culture to preprocess field values.
ResultFormatter | Allows to control how the field result is formatted.
ToaCategories | Gets or sets the table of authorities categories.
UseInvariantCultureNumberFormat | Gets or sets the value indicating that number format is parsed using invariant culture or not
UserPromptRespondent | Gets or sets the respondent to user prompts during field update.

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


BarcodeGenerator Property

Aspose.Words

FieldOptions.BarcodeGenerator Property

Gets or set custom barcode generator.

[Visual Basic]
Public Property BarcodeGenerator As IBarcodeGenerator
[C#]
public IBarcodeGenerator BarcodeGenerator {get; set;}

Remarks

Custom barcode generator should implement public interface IBarcodeGenerator.

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


BuiltInTemplatesPaths Property

Aspose.Words

FieldOptions.BuiltInTemplatesPaths Property

Gets or sets paths of MS Word built-in templates.

[Visual Basic]
Public Property BuiltInTemplatesPaths As String()
[C#]
public string[] BuiltInTemplatesPaths {get; set;}

Remarks

This property is used by the AUTOTEXT and GLOSSARY fields, if referenced auto text entry is not found in the AttachedTemplate template.

By defalut MS Word stores built-in templates in c:\Users\<username>\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx and C:\Users\<username>\AppData\Roaming\Microsoft\Templates\Normal.dotm files.

Example

Shows how to insert a building block into a document and display it with AUTOTEXT and GLOSSARY fields.

[C#]

Document doc = new Document();

// Create a glossary document and add an AutoText building block
doc.GlossaryDocument = new GlossaryDocument();
BuildingBlock buildingBlock = new BuildingBlock(doc.GlossaryDocument);
buildingBlock.Name = "MyBlock";
buildingBlock.Gallery = BuildingBlockGallery.AutoText;
buildingBlock.Category = "General";
buildingBlock.Description = "MyBlock description";
buildingBlock.Behavior = BuildingBlockBehavior.Paragraph;
doc.GlossaryDocument.AppendChild(buildingBlock);

// Create a source and add it as text content to our building block
Document buildingBlockSource = new Document();
DocumentBuilder buildingBlockSourceBuilder = new DocumentBuilder(buildingBlockSource);
buildingBlockSourceBuilder.Writeln("Hello World!");

Node buildingBlockContent = doc.GlossaryDocument.ImportNode(buildingBlockSource.FirstSection, true);
buildingBlock.AppendChild(buildingBlockContent);

// Create an advance field using document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldAutoText fieldAutoText = (FieldAutoText)builder.InsertField(FieldType.FieldAutoText, true);

// Refer to our building block by name
fieldAutoText.EntryName = "MyBlock";

Assert.AreEqual(" AUTOTEXT  MyBlock", fieldAutoText.GetFieldCode());

// Put additional templates here
doc.FieldOptions.BuiltInTemplatesPaths = new[] { MyDir + "Document.BusinessBrochureTemplate.dotx" };

// We can also display our building block with a GLOSSARY field
FieldGlossary fieldGlossary = (FieldGlossary)builder.InsertField(FieldType.FieldGlossary, true);
fieldGlossary.EntryName = "MyBlock";

Assert.AreEqual(" GLOSSARY  MyBlock", fieldGlossary.GetFieldCode());

// The text content of our building block will be visible in the output
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.AutoText.dotx");

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


CurrentUser Property

Aspose.Words

FieldOptions.CurrentUser Property

Gets or sets the current user information.

[Visual Basic]
Public Property CurrentUser As UserInformation
[C#]
public UserInformation CurrentUser {get; set;}

Example

Shows how to set user details and display them with fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set user information
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
userInformation.Initials = "J. D.";
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Insert fields that reference our user information
Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result);
Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result);

// The field options object also has a static default user value that fields from many documents can refer to
UserInformation.DefaultUser.Name = "Default User";
UserInformation.DefaultUser.Initials = "D. U.";
UserInformation.DefaultUser.Address = "One Microsoft Way";
doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result);
Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result);

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


CustomTocStyleSeparator Property

Aspose.Words

FieldOptions.CustomTocStyleSeparator Property

Gets or sets custom style separator for the \t switch in TOC field.

[Visual Basic]
Public Property CustomTocStyleSeparator As String
[C#]
public string CustomTocStyleSeparator {get; set;}

Remarks

By default, custom styles defined by the \t switch in the TOC field are separated by a delimiter taken from the current culture. This property overrides that behaviour by specifying a user defined delimiter.

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


DefaultDocumentAuthor Property

Aspose.Words

FieldOptions.DefaultDocumentAuthor Property

Gets or sets default document author's name. If author's name is already specified in built-in document properties, this option is not considered.

[Visual Basic]
Public Property DefaultDocumentAuthor As String
[C#]
public string DefaultDocumentAuthor {get; set;}

Example

Shows how to display a document creator's name with an AUTHOR field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// If we open an existing document, the document's author's full name will be displayed by the field
// If we create a document programmatically, we need to set this attribute to the author's name so our field has something to display
doc.FieldOptions.DefaultDocumentAuthor = "Joe Bloggs";

builder.Write("This document was created by ");
FieldAuthor field = (FieldAuthor)builder.InsertField(FieldType.FieldAuthor, true);
field.Update();

Assert.AreEqual(" AUTHOR ", field.GetFieldCode());
Assert.AreEqual("Joe Bloggs", field.Result);

// If this property has a value, it will supersede the one we set above
doc.BuiltInDocumentProperties.Author = "John Doe";
field.Update();

Assert.AreEqual(" AUTHOR ", field.GetFieldCode());
Assert.AreEqual("John Doe", field.Result);

// Our field can also override the document's built in author name like this
field.AuthorName = "Jane Doe";
field.Update();

Assert.AreEqual(" AUTHOR  \"Jane Doe\"", field.GetFieldCode());
Assert.AreEqual("Jane Doe", field.Result);

// The author name in the built in properties was changed by the field, but the default document author stays the same
Assert.AreEqual("Jane Doe", doc.BuiltInDocumentProperties.Author);
Assert.AreEqual("Joe Bloggs", doc.FieldOptions.DefaultDocumentAuthor);

doc.Save(ArtifactsDir + "Field.AUTHOR.docx");

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


FieldUpdateCultureProvider Property

Aspose.Words

FieldOptions.FieldUpdateCultureProvider Property

Gets or sets a provider that returns a culture object specific for each particular field.

[Visual Basic]
Public Property FieldUpdateCultureProvider As IFieldUpdateCultureProvider
[C#]
public IFieldUpdateCultureProvider FieldUpdateCultureProvider {get; set;}

Remarks

The provider is requested when the value of FieldUpdateCultureSource is FieldUpdateCultureSource.FieldCode.

If the provider is present, then the culture object it returns is used for the field update. Otherwise, a system culture is used.

Example

Shows how to specifying a culture defining date/time formatting on per field basis

[C#]

[Test]
public void DefineDateTimeFormatting()
{
    Document doc = new Document(MyDir + "Field.UpdateDateTimeFormatting.docx");

    doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
    // Set a provider that return a culture object specific for each particular field
    doc.FieldOptions.FieldUpdateCultureProvider = new FieldUpdateCultureProvider();

    FieldTime fieldDate = (FieldTime) doc.Range.Fields[0];
    if (fieldDate.LocaleId != (int) EditingLanguage.Russian)
        fieldDate.LocaleId = (int) EditingLanguage.Russian;

    doc.Save(ArtifactsDir + "Field.UpdateDateTimeFormatting.pdf");
}

/// <summary>
/// Provides a CultureInfo object that should be used during the update of a particular field.
/// </summary>
private class FieldUpdateCultureProvider : IFieldUpdateCultureProvider
{
    /// <summary>
    /// Returns a CultureInfo object to be used during the field's update.
    /// </summary>
    public CultureInfo GetCulture(string name, Field field)
    {
        switch (name)
        {
            case "ru-RU":
                CultureInfo culture = new CultureInfo(name, false);
                DateTimeFormatInfo format = culture.DateTimeFormat;

                format.MonthNames = new []{"месяц 1", "месяц 2", "месяц 3", "месяц 4", "месяц 5", "месяц 6", "месяц 7", "месяц 8", "месяц 9", "месяц 10", "месяц 11", "месяц 12", ""};
                format.MonthGenitiveNames = format.MonthNames;
                format.AbbreviatedMonthNames = new []{"мес 1", "мес 2", "мес 3", "мес 4", "мес 5", "мес 6", "мес 7", "мес 8", "мес 9", "мес 10", "мес 11", "мес 12", ""};
                format.AbbreviatedMonthGenitiveNames = format.AbbreviatedMonthNames;

                format.DayNames = new []{"день недели 7", "день недели 1", "день недели 2", "день недели 3", "день недели 4", "день недели 5", "день недели 6"};
                format.AbbreviatedDayNames = new []{"день 7", "день 1", "день 2", "день 3", "день 4", "день 5", "день 6"};
                format.ShortestDayNames = new []{"д7", "д1", "д2", "д3", "д4", "д5", "д6"};

                format.AMDesignator = "До полудня";
                format.PMDesignator = "После полудня";

                const string pattern = "yyyy MM (MMMM) dd (dddd) hh:mm:ss tt";
                format.LongDatePattern = pattern;
                format.LongTimePattern = pattern;
                format.ShortDatePattern = pattern;
                format.ShortTimePattern = pattern;

                return culture;
            case "en-US":
                return new CultureInfo(name, false);
            default:
                return null;
        }
    }
}

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


FieldUpdateCultureSource Property

Aspose.Words

FieldOptions.FieldUpdateCultureSource Property

Specifies what culture to use to format the field result.

[Visual Basic]
Public Property FieldUpdateCultureSource As FieldUpdateCultureSource
[C#]
public FieldUpdateCultureSource FieldUpdateCultureSource {get; set;}

Remarks

By default, the culture of the current thread is used.

The setting affects only date/time fields with \\@ format switch.

Example

Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.

[C#]

// Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
doc.MailMerge.Execute(new[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


FileName Property

Aspose.Words

FieldOptions.FileName Property

Gets or sets the file name of the document.

[Visual Basic]
Public Property FileName As String
[C#]
public string FileName {get; set;}

Remarks

This property is used by the FILENAME field with higher priority than the OriginalFileName property.

Example

Shows how to use FieldOptions to override the default value for the FILENAME field.

[C#]

Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToDocumentEnd();
builder.Writeln();

// This FILENAME field will display the file name of the document we opened
FieldFileName field = (FieldFileName)builder.InsertField(FieldType.FieldFileName, true);
field.Update();

Assert.AreEqual(" FILENAME ", field.GetFieldCode());
Assert.AreEqual("Document.docx", field.Result);

builder.Writeln();

// By default, the FILENAME field does not show the full path, and we can change this
field = (FieldFileName)builder.InsertField(FieldType.FieldFileName, true);
field.IncludeFullPath = true;

// We can override the values displayed by our FILENAME fields by setting this attribute
Assert.IsNull(doc.FieldOptions.FileName);
doc.FieldOptions.FileName = "Field.FileName.docx";
field.Update();

Assert.AreEqual(" FILENAME  \\p", field.GetFieldCode());
Assert.AreEqual("Field.FileName.docx", field.Result);

doc.UpdateFields();
doc.Save(ArtifactsDir + "" + doc.FieldOptions.FileName);

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


IsBidiTextSupportedOnUpdate Property

Aspose.Words

FieldOptions.IsBidiTextSupportedOnUpdate Property

Gets or sets the value indicating whether bidirectional text is fully supported during field update or not.

[Visual Basic]
Public Property IsBidiTextSupportedOnUpdate As Boolean
[C#]
public bool IsBidiTextSupportedOnUpdate {get; set;}

Remarks

When this property is set to true, additional steps are performed to produce Right-To-Left language (i.e. Arabic or Hebrew) compatible field result during its update.

When this property is set to false and Right-To-Left language is used, correctness of field result after its update is not guaranteed.

The default value is false.

Example

Shows how to use FieldOptions to ensure that bi-directional text is properly supported during the field update.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Ensure that any field operation involving right-to-left text is performed correctly
doc.FieldOptions.IsBidiTextSupportedOnUpdate = true;

// Use a document builder to insert a field which contains right-to-left text
FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "עֶשְׂרִים", "שְׁלוֹשִׁים", "אַרְבָּעִים", "חֲמִשִּׁים", "שִׁשִּׁים" }, 0);
comboBox.CalculateOnExit = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldOptionsBidi.docx");

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


LegacyNumberFormat Property

Aspose.Words

FieldOptions.LegacyNumberFormat Property

Gets or sets the value indicating whether legacy (early than AW 13.10) number format for fields is enabled or not.

[Visual Basic]
Public Property LegacyNumberFormat As Boolean
[C#]
public bool LegacyNumberFormat {get; set;}

Remarks

When this property is set to true, template symbol "#" worked as in .net: Replaces the pound sign with the corresponding digit if one is present; otherwise, no symbols appears in the result string.

When this property is set to false, template symbol "#" works as MS Word: This format item specifies the requisite numeric places to display in the result. If the result does not include a digit in that place, MS Word displays a space. For example, { = 9 + 6 \# $### } displays $ 15.

The default value is false.

Example

Shows how use FieldOptions to change the number format.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Field field = builder.InsertField("= 2 + 3 \\# $##");

Assert.AreEqual("$ 5", field.Result);

doc.FieldOptions.LegacyNumberFormat = true;
field.Update();

Assert.AreEqual("$5", field.Result);

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


PreProcessCulture Property

Aspose.Words

FieldOptions.PreProcessCulture Property

Gets or sets the culture to preprocess field values.

[Visual Basic]
Public Property PreProcessCulture As CultureInfo
[C#]
public CultureInfo PreProcessCulture {get; set;}

Remarks

Currently this property only affects value of the DOCPROPERTY field.

The default value is null. When this property is set to null, the DOCPROPERTY field's value is preprocessed with the culture controlled by the FieldUpdateCultureSource property.

Example

Shows how to set the preprocess culture.

[C#]

Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

doc.FieldOptions.PreProcessCulture = new CultureInfo("de-DE");

Field field = builder.InsertField(" DOCPROPERTY CreateTime");

// Conforming to the German culture, the date/time will be presented in the "dd.mm.yyyy hh:mm" format
Assert.IsTrue(Regex.Match(field.Result, @"\d{2}[.]\d{2}[.]\d{4} \d{2}[:]\d{2}").Success);

doc.FieldOptions.PreProcessCulture = CultureInfo.InvariantCulture;
field.Update();

// After switching to the invariant culture, the date/time will be presented in the "mm/dd/yyyy hh:mm" format
Assert.IsTrue(Regex.Match(field.Result, @"\d{2}[/]\d{2}[/]\d{4} \d{2}[:]\d{2}").Success);

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


ResultFormatter Property

Aspose.Words

FieldOptions.ResultFormatter Property

Allows to control how the field result is formatted.

[Visual Basic]
Public Property ResultFormatter As IFieldResultFormatter
[C#]
public IFieldResultFormatter ResultFormatter {get; set;}

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


ToaCategories Property

Aspose.Words

FieldOptions.ToaCategories Property

Gets or sets the table of authorities categories.

[Visual Basic]
Public Property ToaCategories As ToaCategories
[C#]
public ToaCategories ToaCategories {get; set;}

Example

Shows how to specify a table of authorities categories for a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// There are default category values we can use, or we can make our own like this
ToaCategories toaCategories = new ToaCategories();
doc.FieldOptions.ToaCategories = toaCategories;

toaCategories[1] = "My Category 1"; // Replaces default value "Cases"
toaCategories[2] = "My Category 2"; // Replaces default value "Statutes"

// Even if we changed the categories in the FieldOptions object, the default categories are still available here
Assert.AreEqual("Cases", ToaCategories.DefaultCategories[1]);
Assert.AreEqual("Statutes", ToaCategories.DefaultCategories[2]);

// Insert 2 tables of authorities, one per category
builder.InsertField("TOA \\c 1 \\h", null);
builder.InsertField("TOA \\c 2 \\h", null);
builder.InsertBreak(BreakType.PageBreak);

// Insert table of authorities entries across 2 categories
builder.InsertField("TA \\c 2 \\l \"entry 1\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 1 \\l \"entry 2\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 2 \\l \"entry 3\"");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TableOfAuthorities.Categories.docx");

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


UseInvariantCultureNumberFormat Property

Aspose.Words

FieldOptions.UseInvariantCultureNumberFormat Property

Gets or sets the value indicating that number format is parsed using invariant culture or not

[Visual Basic]
Public Property UseInvariantCultureNumberFormat As Boolean
[C#]
public bool UseInvariantCultureNumberFormat {get; set;}

Example

Shows how to format numbers according to the invariant culture.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
Field field = builder.InsertField(" = 1234567,89 \\# $#,###,###.##");
field.Update();

// The combination of field, number format and thread culture can sometimes produce an unsuitable result
Assert.IsFalse(doc.FieldOptions.UseInvariantCultureNumberFormat);
Assert.AreEqual("$1234567,89 .     ", field.Result);

// We can set this attribute to avoid changing the whole thread culture just for numeric formats
doc.FieldOptions.UseInvariantCultureNumberFormat = true;
field.Update();
Assert.AreEqual("$1.234.567,89", field.Result);

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


UserPromptRespondent Property

Aspose.Words

FieldOptions.UserPromptRespondent Property

Gets or sets the respondent to user prompts during field update.

[Visual Basic]
Public Property UserPromptRespondent As IFieldUserPromptRespondent
[C#]
public IFieldUserPromptRespondent UserPromptRespondent {get; set;}

Remarks

If the value of this property is set to null, the fields that require user response on prompting (such as ASK or FILLIN) are not updated.

The default value is null.

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

See Also

FieldOptions Class | Aspose.Words.Fields Namespace


FieldPage Class

Implements the PAGE field.

For a list of all members of this type, see FieldPage Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldPage

[Visual Basic]
Public Class FieldPage
Inherits Field
[C#]
public class FieldPage : Field

Remarks

Retrieves the number of the current page.

Example

Shows how to use NUMCHARS, NUMWORDS, NUMPAGES and PAGE fields to track the size of our documents.

[C#]

// Open a document to which we want to add character/word/page counts
Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// Move the document builder to the footer, where we will store our fields
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// Insert character and word counts
FieldNumChars fieldNumChars = (FieldNumChars)builder.InsertField(FieldType.FieldNumChars, true);
builder.Writeln(" characters");
FieldNumWords fieldNumWords = (FieldNumWords)builder.InsertField(FieldType.FieldNumWords, true);
builder.Writeln(" words");

// Insert a "Page x of y" page count
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Write("Page ");
FieldPage fieldPage = (FieldPage)builder.InsertField(FieldType.FieldPage, true);
builder.Write(" of ");
FieldNumPages fieldNumPages = (FieldNumPages)builder.InsertField(FieldType.FieldNumPages, true);

Assert.AreEqual(" NUMCHARS ", fieldNumChars.GetFieldCode());
Assert.AreEqual(" NUMWORDS ", fieldNumWords.GetFieldCode());
Assert.AreEqual(" NUMPAGES ", fieldNumPages.GetFieldCode());
Assert.AreEqual(" PAGE ", fieldPage.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Num.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldPage Members | Aspose.Words.Fields Namespace


FieldPage Members

FieldPage overview

Public Instance Constructors

FieldPage Constructor Initializes a new instance of the FieldPage class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldPage Class | Aspose.Words.Fields Namespace


FieldPage Constructor

Initializes a new instance of the FieldPage class.

[Visual Basic]
Public Sub New()
[C#]
public FieldPage();

See Also

FieldPage Class | Aspose.Words.Fields Namespace


FieldPageRef Class

Implements the PAGEREF field.

For a list of all members of this type, see FieldPageRef Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldPageRef

[Visual Basic]
Public Class FieldPageRef
Inherits Field
[C#]
public class FieldPageRef : Field

Remarks

Inserts the number of the page containing the specified bookmark for a cross-reference.

Example

Shows to insert PAGEREF fields and present them in different ways.

[C#]

public void FieldPageRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    InsertAndNameBookmark(builder, "MyBookmark1");

    // This field will display just the page number where the bookmark starts
    // Setting InsertHyperlink attribute makes the field function as a link to the bookmark
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h",
        InsertFieldPageRef(builder, "MyBookmark3", true, false, "Hyperlink to Bookmark3, on page: ").GetFieldCode());

    // Setting the \p flag makes the field display the relative position of the bookmark to the field instead of a page number
    // Bookmark1 is on the same page and above this field, so the result will be "above" on update
    Assert.AreEqual(" PAGEREF  MyBookmark1 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark1", true, true, "Bookmark1 is ").GetFieldCode());

    // Bookmark2 will be on the same page and below this field, so the field will display "below"
    Assert.AreEqual(" PAGEREF  MyBookmark2 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark2", true, true, "Bookmark2 is ").GetFieldCode());

    // Bookmark3 will be on a different page, so the field will display "on page 2"
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark3", true, true, "Bookmark3 is ").GetFieldCode());

    InsertAndNameBookmark(builder, "MyBookmark2");
    builder.InsertBreak(BreakType.PageBreak);
    InsertAndNameBookmark(builder, "MyBookmark3");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.PageRef.docx");
}

/// <summary>
/// Uses a document builder to insert a PAGEREF field and sets its attributes
/// </summary>
private FieldPageRef InsertFieldPageRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, string textBefore)
{
    builder.Write(textBefore);

    FieldPageRef field = (FieldPageRef)builder.InsertField(FieldType.FieldPageRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark
/// </summary>
private void InsertAndNameBookmark(DocumentBuilder builder, string bookmarkName)
{
    builder.StartBookmark(bookmarkName);
    builder.Writeln(string.Format("Contents of bookmark \"{0}\".", bookmarkName));
    builder.EndBookmark(bookmarkName);
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldPageRef Members | Aspose.Words.Fields Namespace


FieldPageRef Members

FieldPageRef overview

Public Instance Constructors

FieldPageRef Constructor Initializes a new instance of the FieldPageRef class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertHyperlink | Gets or sets whether to insert a hyperlink to the bookmarked paragraph.
InsertRelativePosition | Gets or sets whether to insert a relative position of the bookmarked paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldPageRef Class | Aspose.Words.Fields Namespace


FieldPageRef Constructor

Initializes a new instance of the FieldPageRef class.

[Visual Basic]
Public Sub New()
[C#]
public FieldPageRef();

See Also

FieldPageRef Class | Aspose.Words.Fields Namespace


FieldPageRef Properties

The properties of the FieldPageRef class are listed below. For a complete list of FieldPageRef class members, see the FieldPageRef Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertHyperlink | Gets or sets whether to insert a hyperlink to the bookmarked paragraph.
InsertRelativePosition | Gets or sets whether to insert a relative position of the bookmarked paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldPageRef Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldPageRef.BookmarkName Property

Gets or sets the name of the bookmark.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows to insert PAGEREF fields and present them in different ways.

[C#]

public void FieldPageRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    InsertAndNameBookmark(builder, "MyBookmark1");

    // This field will display just the page number where the bookmark starts
    // Setting InsertHyperlink attribute makes the field function as a link to the bookmark
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h",
        InsertFieldPageRef(builder, "MyBookmark3", true, false, "Hyperlink to Bookmark3, on page: ").GetFieldCode());

    // Setting the \p flag makes the field display the relative position of the bookmark to the field instead of a page number
    // Bookmark1 is on the same page and above this field, so the result will be "above" on update
    Assert.AreEqual(" PAGEREF  MyBookmark1 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark1", true, true, "Bookmark1 is ").GetFieldCode());

    // Bookmark2 will be on the same page and below this field, so the field will display "below"
    Assert.AreEqual(" PAGEREF  MyBookmark2 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark2", true, true, "Bookmark2 is ").GetFieldCode());

    // Bookmark3 will be on a different page, so the field will display "on page 2"
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark3", true, true, "Bookmark3 is ").GetFieldCode());

    InsertAndNameBookmark(builder, "MyBookmark2");
    builder.InsertBreak(BreakType.PageBreak);
    InsertAndNameBookmark(builder, "MyBookmark3");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.PageRef.docx");
}

/// <summary>
/// Uses a document builder to insert a PAGEREF field and sets its attributes
/// </summary>
private FieldPageRef InsertFieldPageRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, string textBefore)
{
    builder.Write(textBefore);

    FieldPageRef field = (FieldPageRef)builder.InsertField(FieldType.FieldPageRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark
/// </summary>
private void InsertAndNameBookmark(DocumentBuilder builder, string bookmarkName)
{
    builder.StartBookmark(bookmarkName);
    builder.Writeln(string.Format("Contents of bookmark \"{0}\".", bookmarkName));
    builder.EndBookmark(bookmarkName);
}

See Also

FieldPageRef Class | Aspose.Words.Fields Namespace


InsertHyperlink Property

Aspose.Words

FieldPageRef.InsertHyperlink Property

Gets or sets whether to insert a hyperlink to the bookmarked paragraph.

[Visual Basic]
Public Property InsertHyperlink As Boolean
[C#]
public bool InsertHyperlink {get; set;}

Example

Shows to insert PAGEREF fields and present them in different ways.

[C#]

public void FieldPageRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    InsertAndNameBookmark(builder, "MyBookmark1");

    // This field will display just the page number where the bookmark starts
    // Setting InsertHyperlink attribute makes the field function as a link to the bookmark
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h",
        InsertFieldPageRef(builder, "MyBookmark3", true, false, "Hyperlink to Bookmark3, on page: ").GetFieldCode());

    // Setting the \p flag makes the field display the relative position of the bookmark to the field instead of a page number
    // Bookmark1 is on the same page and above this field, so the result will be "above" on update
    Assert.AreEqual(" PAGEREF  MyBookmark1 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark1", true, true, "Bookmark1 is ").GetFieldCode());

    // Bookmark2 will be on the same page and below this field, so the field will display "below"
    Assert.AreEqual(" PAGEREF  MyBookmark2 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark2", true, true, "Bookmark2 is ").GetFieldCode());

    // Bookmark3 will be on a different page, so the field will display "on page 2"
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark3", true, true, "Bookmark3 is ").GetFieldCode());

    InsertAndNameBookmark(builder, "MyBookmark2");
    builder.InsertBreak(BreakType.PageBreak);
    InsertAndNameBookmark(builder, "MyBookmark3");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.PageRef.docx");
}

/// <summary>
/// Uses a document builder to insert a PAGEREF field and sets its attributes
/// </summary>
private FieldPageRef InsertFieldPageRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, string textBefore)
{
    builder.Write(textBefore);

    FieldPageRef field = (FieldPageRef)builder.InsertField(FieldType.FieldPageRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark
/// </summary>
private void InsertAndNameBookmark(DocumentBuilder builder, string bookmarkName)
{
    builder.StartBookmark(bookmarkName);
    builder.Writeln(string.Format("Contents of bookmark \"{0}\".", bookmarkName));
    builder.EndBookmark(bookmarkName);
}

See Also

FieldPageRef Class | Aspose.Words.Fields Namespace


InsertRelativePosition Property

Aspose.Words

FieldPageRef.InsertRelativePosition Property

Gets or sets whether to insert a relative position of the bookmarked paragraph.

[Visual Basic]
Public Property InsertRelativePosition As Boolean
[C#]
public bool InsertRelativePosition {get; set;}

Example

Shows to insert PAGEREF fields and present them in different ways.

[C#]

public void FieldPageRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    InsertAndNameBookmark(builder, "MyBookmark1");

    // This field will display just the page number where the bookmark starts
    // Setting InsertHyperlink attribute makes the field function as a link to the bookmark
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h",
        InsertFieldPageRef(builder, "MyBookmark3", true, false, "Hyperlink to Bookmark3, on page: ").GetFieldCode());

    // Setting the \p flag makes the field display the relative position of the bookmark to the field instead of a page number
    // Bookmark1 is on the same page and above this field, so the result will be "above" on update
    Assert.AreEqual(" PAGEREF  MyBookmark1 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark1", true, true, "Bookmark1 is ").GetFieldCode());

    // Bookmark2 will be on the same page and below this field, so the field will display "below"
    Assert.AreEqual(" PAGEREF  MyBookmark2 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark2", true, true, "Bookmark2 is ").GetFieldCode());

    // Bookmark3 will be on a different page, so the field will display "on page 2"
    Assert.AreEqual(" PAGEREF  MyBookmark3 \\h \\p",
        InsertFieldPageRef(builder, "MyBookmark3", true, true, "Bookmark3 is ").GetFieldCode());

    InsertAndNameBookmark(builder, "MyBookmark2");
    builder.InsertBreak(BreakType.PageBreak);
    InsertAndNameBookmark(builder, "MyBookmark3");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.PageRef.docx");
}

/// <summary>
/// Uses a document builder to insert a PAGEREF field and sets its attributes
/// </summary>
private FieldPageRef InsertFieldPageRef(DocumentBuilder builder, string bookmarkName, bool insertHyperlink, bool insertRelativePosition, string textBefore)
{
    builder.Write(textBefore);

    FieldPageRef field = (FieldPageRef)builder.InsertField(FieldType.FieldPageRef, true);
    field.BookmarkName = bookmarkName;
    field.InsertHyperlink = insertHyperlink;
    field.InsertRelativePosition = insertRelativePosition;
    builder.Writeln();

    return field;
}

/// <summary>
/// Uses a document builder to insert a named bookmark
/// </summary>
private void InsertAndNameBookmark(DocumentBuilder builder, string bookmarkName)
{
    builder.StartBookmark(bookmarkName);
    builder.Writeln(string.Format("Contents of bookmark \"{0}\".", bookmarkName));
    builder.EndBookmark(bookmarkName);
}

See Also

FieldPageRef Class | Aspose.Words.Fields Namespace


FieldPrint Class

Implements the PRINT field.

For a list of all members of this type, see FieldPrint Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldPrint

[Visual Basic]
Public Class FieldPrint
Inherits Field
[C#]
public class FieldPrint : Field

Remarks

An instruction to send the printer-specific control code characters to the selected printer when the document is printed.

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldPrint Members | Aspose.Words.Fields Namespace


FieldPrint Members

FieldPrint overview

Public Instance Constructors

FieldPrint Constructor Initializes a new instance of the FieldPrint class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PostScriptGroup | Gets or sets the drawing rectangle that the PostScript instructions operate on.
PrinterInstructions | Gets or sets the printer-specific control code characters or PostScript instructions.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldPrint Class | Aspose.Words.Fields Namespace


FieldPrint Constructor

Initializes a new instance of the FieldPrint class.

[Visual Basic]
Public Sub New()
[C#]
public FieldPrint();

See Also

FieldPrint Class | Aspose.Words.Fields Namespace


FieldPrint Properties

The properties of the FieldPrint class are listed below. For a complete list of FieldPrint class members, see the FieldPrint Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PostScriptGroup | Gets or sets the drawing rectangle that the PostScript instructions operate on.
PrinterInstructions | Gets or sets the printer-specific control code characters or PostScript instructions.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldPrint Class | Aspose.Words.Fields Namespace


PostScriptGroup Property

Aspose.Words

FieldPrint.PostScriptGroup Property

Gets or sets the drawing rectangle that the PostScript instructions operate on.

[Visual Basic]
Public Property PostScriptGroup As String
[C#]
public string PostScriptGroup {get; set;}

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

See Also

FieldPrint Class | Aspose.Words.Fields Namespace


PrinterInstructions Property

Aspose.Words

FieldPrint.PrinterInstructions Property

Gets or sets the printer-specific control code characters or PostScript instructions.

[Visual Basic]
Public Property PrinterInstructions As String
[C#]
public string PrinterInstructions {get; set;}

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

See Also

FieldPrint Class | Aspose.Words.Fields Namespace


FieldPrintDate Class

Implements the PRINTDATE field.

For a list of all members of this type, see FieldPrintDate Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldPrintDate

[Visual Basic]
Public Class FieldPrintDate
Inherits Field
[C#]
public class FieldPrintDate : Field

Remarks

Retrieves the date and time on which the document was last printed. By default, the Gregorian calendar is used.

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldPrintDate Members | Aspose.Words.Fields Namespace


FieldPrintDate Members

FieldPrintDate overview

Public Instance Constructors

FieldPrintDate Constructor Initializes a new instance of the FieldPrintDate class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldPrintDate Class | Aspose.Words.Fields Namespace


FieldPrintDate Constructor

Initializes a new instance of the FieldPrintDate class.

[Visual Basic]
Public Sub New()
[C#]
public FieldPrintDate();

See Also

FieldPrintDate Class | Aspose.Words.Fields Namespace


FieldPrintDate Properties

The properties of the FieldPrintDate class are listed below. For a complete list of FieldPrintDate class members, see the FieldPrintDate Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

See Also

FieldPrintDate Class | Aspose.Words.Fields Namespace


UseLunarCalendar Property

Aspose.Words

FieldPrintDate.UseLunarCalendar Property

Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.

[Visual Basic]
Public Property UseLunarCalendar As Boolean
[C#]
public bool UseLunarCalendar {get; set;}

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

See Also

FieldPrintDate Class | Aspose.Words.Fields Namespace


UseSakaEraCalendar Property

Aspose.Words

FieldPrintDate.UseSakaEraCalendar Property

Gets or sets whether to use the Saka Era calendar.

[Visual Basic]
Public Property UseSakaEraCalendar As Boolean
[C#]
public bool UseSakaEraCalendar {get; set;}

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

See Also

FieldPrintDate Class | Aspose.Words.Fields Namespace


UseUmAlQuraCalendar Property

Aspose.Words

FieldPrintDate.UseUmAlQuraCalendar Property

Gets or sets whether to use the Um-al-Qura calendar.

[Visual Basic]
Public Property UseUmAlQuraCalendar As Boolean
[C#]
public bool UseUmAlQuraCalendar {get; set;}

Example

Shows to insert a PRINT field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("My paragraph");

// The PRINT field can send instructions to the printer that we use to print our document
FieldPrint field = (FieldPrint)builder.InsertField(FieldType.FieldPrint, true);

// Set the area for the printer to perform instructions over
// In this case it will be the paragraph that contains our PRINT field
field.PostScriptGroup = "para";

// When our document is printed using a printer that supports PostScript,
// this command will turn the entire area that we specified in field.PostScriptGroup white
field.PrinterInstructions = "erasepage";

Assert.AreEqual(" PRINT  erasepage \\p para", field.GetFieldCode());

builder.InsertParagraph();

// PRINTDATE field will display "0/0/0000" by default
// When a document is printed by a printer or printed as a PDF (but not exported as PDF),
// these fields will display the date/time of the printing operation, in various calendars
FieldPrintDate fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseLunarCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\h", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseSakaEraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\s", fieldPrintDate.GetFieldCode());

fieldPrintDate = (FieldPrintDate)builder.InsertField(FieldType.FieldPrintDate, true);
fieldPrintDate.UseUmAlQuraCalendar = true;
builder.Writeln();

Assert.AreEqual(" PRINTDATE  \\u", fieldPrintDate.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Print.docx");

See Also

FieldPrintDate Class | Aspose.Words.Fields Namespace


FieldPrivate Class

Implements the PRIVATE field.

For a list of all members of this type, see FieldPrivate Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldPrivate

[Visual Basic]
Public Class FieldPrivate
Inherits Field
[C#]
public class FieldPrivate : Field

Remarks

Provides a private storage area. This field is used to store data for documents converted from other file formats.

Example

Shows how to process PRIVATE fields.

[C#]

public void FieldPrivate()
{
    // Open a Corel WordPerfect document that was converted to .docx format
    Document doc = new Document(MyDir + "Field.FromWpd.docx");

    // WordPerfect 5.x/6.x documents like the one we opened may contain PRIVATE fields
    // The PRIVATE field is a WordPerfect artifact that is preserved when a file is opened and saved in Microsoft Word
    // However, they have no functionality in Microsoft Word
    FieldPrivate field = (FieldPrivate)doc.Range.Fields[0];
    Assert.AreEqual(" PRIVATE \"My value\" ", field.GetFieldCode());

    // PRIVATE fields can also be inserted by a document builder
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField(FieldType.FieldPrivate, true);

    // It is strongly advised against using them to attempt to hide or store private information
    // Unless backward compatibility with older versions of WordPerfect is necessary, these fields can safely be removed
    // This can be done using a document visitor implementation
    Assert.AreEqual(2, doc.Range.Fields.Count);

    FieldPrivateRemover remover = new FieldPrivateRemover();
    doc.Accept(remover);

    Assert.AreEqual(2, remover.GetFieldsRemovedCount());
    Assert.AreEqual(0, doc.Range.Fields.Count);
}

/// <summary>
/// Visitor implementation that removes all PRIVATE fields that it comes across.
/// </summary>
public class FieldPrivateRemover : DocumentVisitor
{
    public FieldPrivateRemover()
    {
        mFieldsRemovedCount = 0;
    }

    public int GetFieldsRemovedCount()
    {
        return mFieldsRemovedCount;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// If the node belongs to a PRIVATE field, the entire field is removed.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (fieldEnd.FieldType == FieldType.FieldPrivate)
        {
            fieldEnd.GetField().Remove();
            mFieldsRemovedCount++;
        }

        return VisitorAction.Continue;
    }

    private int mFieldsRemovedCount;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldPrivate Members | Aspose.Words.Fields Namespace


FieldPrivate Members

FieldPrivate overview

Public Instance Constructors

FieldPrivate Constructor Initializes a new instance of the FieldPrivate class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldPrivate Class | Aspose.Words.Fields Namespace


FieldPrivate Constructor

Initializes a new instance of the FieldPrivate class.

[Visual Basic]
Public Sub New()
[C#]
public FieldPrivate();

See Also

FieldPrivate Class | Aspose.Words.Fields Namespace


FieldQuote Class

Implements the QUOTE field.

For a list of all members of this type, see FieldQuote Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldQuote

[Visual Basic]
Public Class FieldQuote
Inherits Field
[C#]
public class FieldQuote : Field

Remarks

Retrieves the specified text.

Example

Shows to use the QUOTE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a QUOTE field, which will display content from the Text attribute
FieldQuote field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
field.Text = "\"Quoted text\"";

Assert.AreEqual(" QUOTE  \"\\\"Quoted text\\\"\"", field.GetFieldCode());

builder.InsertParagraph();

// Insert a QUOTE field with a nested DATE field
// DATE fields normally update their value to the current date every time the document is opened
// Nesting the DATE field inside the QUOTE field like this will freeze its value to the date when we created the document
builder.Write("Document creation date: ");
field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
builder.MoveTo(field.Separator);
builder.InsertField(FieldType.FieldDate, true);

Assert.AreEqual(" QUOTE \u0013 DATE \u0014" + System.DateTime.Now.Date.ToShortDateString() + "\u0015", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Quote.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldQuote Members | Aspose.Words.Fields Namespace


FieldQuote Members

FieldQuote overview

Public Instance Constructors

FieldQuote Constructor Initializes a new instance of the FieldQuote class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text to retrieve.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldQuote Class | Aspose.Words.Fields Namespace


FieldQuote Constructor

Initializes a new instance of the FieldQuote class.

[Visual Basic]
Public Sub New()
[C#]
public FieldQuote();

See Also

FieldQuote Class | Aspose.Words.Fields Namespace


FieldQuote Properties

The properties of the FieldQuote class are listed below. For a complete list of FieldQuote class members, see the FieldQuote Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text to retrieve.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldQuote Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldQuote.Text Property

Gets or sets the text to retrieve.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows to use the QUOTE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a QUOTE field, which will display content from the Text attribute
FieldQuote field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
field.Text = "\"Quoted text\"";

Assert.AreEqual(" QUOTE  \"\\\"Quoted text\\\"\"", field.GetFieldCode());

builder.InsertParagraph();

// Insert a QUOTE field with a nested DATE field
// DATE fields normally update their value to the current date every time the document is opened
// Nesting the DATE field inside the QUOTE field like this will freeze its value to the date when we created the document
builder.Write("Document creation date: ");
field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
builder.MoveTo(field.Separator);
builder.InsertField(FieldType.FieldDate, true);

Assert.AreEqual(" QUOTE \u0013 DATE \u0014" + System.DateTime.Now.Date.ToShortDateString() + "\u0015", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.Quote.docx");

See Also

FieldQuote Class | Aspose.Words.Fields Namespace


FieldRD Class

Implements the RD field.

For a list of all members of this type, see FieldRD Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldRD

[Visual Basic]
Public Class FieldRD
Inherits Field
[C#]
public class FieldRD : Field

Remarks

Identifies a file to include when you create a table of contents, a table of authorities, or an index with the TOC, TOA, or INDEX field

Example

Shows to insert an RD field to source table of contents entries from an external document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a table of contents and, on the following page, one entry
builder.InsertField(FieldType.FieldTOC, true);
builder.InsertBreak(BreakType.PageBreak);
builder.CurrentParagraph.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln("TOC entry from within this document");

// Insert an RD field, designating an external document that our TOC field will look in for more entries
FieldRD field = (FieldRD)builder.InsertField(FieldType.FieldRefDoc, true);
field.FileName = "ReferencedDocument.docx";
field.IsPathRelative = true;
field.Update();

Assert.AreEqual(" RD  ReferencedDocument.docx \\f", field.GetFieldCode());

// Create the document and insert a TOC entry, which will end up in the TOC of our original document
Document referencedDoc = new Document();
DocumentBuilder refDocBuilder = new DocumentBuilder(referencedDoc);
refDocBuilder.CurrentParagraph.ParagraphFormat.StyleName = "Heading 1";
refDocBuilder.Writeln("TOC entry from referenced document");
referencedDoc.Save(ArtifactsDir + "ReferencedDocument.docx");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.RefDoc.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldRD Members | Aspose.Words.Fields Namespace


FieldRD Members

FieldRD overview

Public Instance Constructors

FieldRD Constructor Initializes a new instance of the FieldRD class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FileName | Gets or sets the name of the file to include when generating a table of contents, table of authorities, or index.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsPathRelative | Gets or sets whether the path is relative to the current document.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldRD Class | Aspose.Words.Fields Namespace


FieldRD Constructor

Initializes a new instance of the FieldRD class.

[Visual Basic]
Public Sub New()
[C#]
public FieldRD();

See Also

FieldRD Class | Aspose.Words.Fields Namespace


FieldRD Properties

The properties of the FieldRD class are listed below. For a complete list of FieldRD class members, see the FieldRD Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
FileName | Gets or sets the name of the file to include when generating a table of contents, table of authorities, or index.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsPathRelative | Gets or sets whether the path is relative to the current document.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldRD Class | Aspose.Words.Fields Namespace


FileName Property

Aspose.Words

FieldRD.FileName Property

Gets or sets the name of the file to include when generating a table of contents, table of authorities, or index.

[Visual Basic]
Public Property FileName As String
[C#]
public string FileName {get; set;}

Example

Shows to insert an RD field to source table of contents entries from an external document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a table of contents and, on the following page, one entry
builder.InsertField(FieldType.FieldTOC, true);
builder.InsertBreak(BreakType.PageBreak);
builder.CurrentParagraph.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln("TOC entry from within this document");

// Insert an RD field, designating an external document that our TOC field will look in for more entries
FieldRD field = (FieldRD)builder.InsertField(FieldType.FieldRefDoc, true);
field.FileName = "ReferencedDocument.docx";
field.IsPathRelative = true;
field.Update();

Assert.AreEqual(" RD  ReferencedDocument.docx \\f", field.GetFieldCode());

// Create the document and insert a TOC entry, which will end up in the TOC of our original document
Document referencedDoc = new Document();
DocumentBuilder refDocBuilder = new DocumentBuilder(referencedDoc);
refDocBuilder.CurrentParagraph.ParagraphFormat.StyleName = "Heading 1";
refDocBuilder.Writeln("TOC entry from referenced document");
referencedDoc.Save(ArtifactsDir + "ReferencedDocument.docx");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.RefDoc.docx");

See Also

FieldRD Class | Aspose.Words.Fields Namespace


IsPathRelative Property

Aspose.Words

FieldRD.IsPathRelative Property

Gets or sets whether the path is relative to the current document.

[Visual Basic]
Public Property IsPathRelative As Boolean
[C#]
public bool IsPathRelative {get; set;}

Example

Shows to insert an RD field to source table of contents entries from an external document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert a table of contents and, on the following page, one entry
builder.InsertField(FieldType.FieldTOC, true);
builder.InsertBreak(BreakType.PageBreak);
builder.CurrentParagraph.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln("TOC entry from within this document");

// Insert an RD field, designating an external document that our TOC field will look in for more entries
FieldRD field = (FieldRD)builder.InsertField(FieldType.FieldRefDoc, true);
field.FileName = "ReferencedDocument.docx";
field.IsPathRelative = true;
field.Update();

Assert.AreEqual(" RD  ReferencedDocument.docx \\f", field.GetFieldCode());

// Create the document and insert a TOC entry, which will end up in the TOC of our original document
Document referencedDoc = new Document();
DocumentBuilder refDocBuilder = new DocumentBuilder(referencedDoc);
refDocBuilder.CurrentParagraph.ParagraphFormat.StyleName = "Heading 1";
refDocBuilder.Writeln("TOC entry from referenced document");
referencedDoc.Save(ArtifactsDir + "ReferencedDocument.docx");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.RefDoc.docx");

See Also

FieldRD Class | Aspose.Words.Fields Namespace


FieldRef Class

Implements the REF field.

For a list of all members of this type, see FieldRef Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldRef

[Visual Basic]
Public Class FieldRef
Inherits Field
[C#]
public class FieldRef : Field

Remarks

Inserts the text or graphics represented by the specified bookmark.

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldRef Members | Aspose.Words.Fields Namespace


FieldRef Members

FieldRef overview

Public Instance Constructors

FieldRef Constructor Initializes a new instance of the FieldRef class.

Public Instance Properties

BookmarkName | Gets or sets the referenced bookmark's name.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IncludeNoteOrComment | Gets or sets whether to increment footnote, endnote, and annotation numbers that are marked by the bookmark, and insert the corresponding footnote, endnote, and comment text.
InsertHyperlink | Gets or sets whether to create a hyperlink to the bookmarked paragraph.
InsertParagraphNumber | Gets or sets whether to insert the paragraph number of the referenced paragraph exactly as it appears in the document.
InsertParagraphNumberInFullContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in full context.
InsertParagraphNumberInRelativeContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in relative context.
InsertRelativePosition | Gets or sets whether to insert the relative position of the referenced paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NumberSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SuppressNonDelimiters | Gets or sets whether to suppress non-delimiter characters.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldRef Class | Aspose.Words.Fields Namespace


FieldRef Constructor

Initializes a new instance of the FieldRef class.

[Visual Basic]
Public Sub New()
[C#]
public FieldRef();

See Also

FieldRef Class | Aspose.Words.Fields Namespace


FieldRef Properties

The properties of the FieldRef class are listed below. For a complete list of FieldRef class members, see the FieldRef Members topic.

Public Instance Properties

BookmarkName | Gets or sets the referenced bookmark's name.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IncludeNoteOrComment | Gets or sets whether to increment footnote, endnote, and annotation numbers that are marked by the bookmark, and insert the corresponding footnote, endnote, and comment text.
InsertHyperlink | Gets or sets whether to create a hyperlink to the bookmarked paragraph.
InsertParagraphNumber | Gets or sets whether to insert the paragraph number of the referenced paragraph exactly as it appears in the document.
InsertParagraphNumberInFullContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in full context.
InsertParagraphNumberInRelativeContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in relative context.
InsertRelativePosition | Gets or sets whether to insert the relative position of the referenced paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
NumberSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
SuppressNonDelimiters | Gets or sets whether to suppress non-delimiter characters.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldRef Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldRef.BookmarkName Property

Gets or sets the referenced bookmark's name.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


IncludeNoteOrComment Property

Aspose.Words

FieldRef.IncludeNoteOrComment Property

Gets or sets whether to increment footnote, endnote, and annotation numbers that are marked by the bookmark, and insert the corresponding footnote, endnote, and comment text.

[Visual Basic]
Public Property IncludeNoteOrComment As Boolean
[C#]
public bool IncludeNoteOrComment {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


InsertHyperlink Property

Aspose.Words

FieldRef.InsertHyperlink Property

Gets or sets whether to create a hyperlink to the bookmarked paragraph.

[Visual Basic]
Public Property InsertHyperlink As Boolean
[C#]
public bool InsertHyperlink {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


InsertParagraphNumber Property

Aspose.Words

FieldRef.InsertParagraphNumber Property

Gets or sets whether to insert the paragraph number of the referenced paragraph exactly as it appears in the document.

[Visual Basic]
Public Property InsertParagraphNumber As Boolean
[C#]
public bool InsertParagraphNumber {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


InsertParagraphNumberInFullContext Property

Aspose.Words

FieldRef.InsertParagraphNumberInFullContext Property

Gets or sets whether to insert the paragraph number of the referenced paragraph in full context.

[Visual Basic]
Public Property InsertParagraphNumberInFullContext As Boolean
[C#]
public bool InsertParagraphNumberInFullContext {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


InsertParagraphNumberInRelativeContext Property

Aspose.Words

FieldRef.InsertParagraphNumberInRelativeContext Property

Gets or sets whether to insert the paragraph number of the referenced paragraph in relative context.

[Visual Basic]
Public Property InsertParagraphNumberInRelativeContext As Boolean
[C#]
public bool InsertParagraphNumberInRelativeContext {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


InsertRelativePosition Property

Aspose.Words

FieldRef.InsertRelativePosition Property

Gets or sets whether to insert the relative position of the referenced paragraph.

[Visual Basic]
Public Property InsertRelativePosition As Boolean
[C#]
public bool InsertRelativePosition {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


NumberSeparator Property

Aspose.Words

FieldRef.NumberSeparator Property

Gets or sets the character sequence that is used to separate sequence numbers and page numbers.

[Visual Basic]
Public Property NumberSeparator As String
[C#]
public string NumberSeparator {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


SuppressNonDelimiters Property

Aspose.Words

FieldRef.SuppressNonDelimiters Property

Gets or sets whether to suppress non-delimiter characters.

[Visual Basic]
Public Property SuppressNonDelimiters As Boolean
[C#]
public bool SuppressNonDelimiters {get; set;}

Example

Shows how to insert REF fields to reference bookmarks and present them in various ways.

[C#]

[Ignore("WORDSNET-18067")]
public void FieldRef()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert the bookmark that all our REF fields will reference and leave it at the end of the document
    builder.StartBookmark("MyBookmark");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #1");
    builder.Write("Text that will appear in REF field");
    builder.InsertFootnote(FootnoteType.Footnote, "MyBookmark footnote #2");
    builder.EndBookmark("MyBookmark");
    builder.MoveToDocumentStart();

    // We will apply a custom list format, where the amount of angle brackets indicates the list level we are currently at
    // Note that the angle brackets count as non-delimiter characters
    builder.ListFormat.ApplyNumberDefault();
    builder.ListFormat.ListLevel.NumberFormat = "> \x0000";

    // Insert a REF field that will contain the text within our bookmark, act as a hyperlink, and clone the bookmark's footnotes
    FieldRef field = InsertFieldRef(builder, "MyBookmark", "", "\n");
    field.IncludeNoteOrComment = true;
    field.InsertHyperlink = true;

    Assert.AreEqual(" REF  MyBookmark \\f \\h", field.GetFieldCode());

    // Insert a REF field and display whether the referenced bookmark is above or below it
    field = InsertFieldRef(builder, "MyBookmark", "The referenced paragraph is ", " this field.\n");
    field.InsertRelativePosition = true;

    Assert.AreEqual(" REF  MyBookmark \\p", field.GetFieldCode());

    // Display the list number of the bookmark, as it appears in the document
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number is ", "\n");
    field.InsertParagraphNumber = true;

    Assert.AreEqual(" REF  MyBookmark \\n", field.GetFieldCode());

    // Display the list number of the bookmark, but with non-delimiter characters omitted
    // In this case they are the angle brackets
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's paragraph number, non-delimiters suppressed, is ", "\n");
    field.InsertParagraphNumber = true;
    field.SuppressNonDelimiters = true;

    Assert.AreEqual(" REF  MyBookmark \\n \\t", field.GetFieldCode());

    // Move down one list level
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">> \x0001";

    // Display the list number of the bookmark as well as the numbers of all the list levels above it
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's full context paragraph number is ", "\n");
    field.InsertParagraphNumberInFullContext = true;

    Assert.AreEqual(" REF  MyBookmark \\w", field.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Display the list level numbers between this REF field and the bookmark that it is referencing
    field = InsertFieldRef(builder, "MyBookmark", "The bookmark's relative paragraph number is ", "\n");
    field.InsertParagraphNumberInRelativeContext = true;

    Assert.AreEqual(" REF  MyBookmark \\r", field.GetFieldCode());

    // The bookmark, which is at the end of the document, will show up as a list item here
    builder.Writeln("List level above bookmark");
    builder.ListFormat.ListLevelNumber++;
    builder.ListFormat.ListLevel.NumberFormat = ">>> \x0002";

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.Ref.docx");
}

/// <summary>
/// Get the document builder to insert a REF field, reference a bookmark with it, and add text before and after
/// </summary>
private FieldRef InsertFieldRef(DocumentBuilder builder, string bookmarkName, string textBefore, string textAfter)
{
    builder.Write(textBefore);
    FieldRef field = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    field.BookmarkName = bookmarkName;
    builder.Write(textAfter);
    return field;
}

See Also

FieldRef Class | Aspose.Words.Fields Namespace


FieldRevNum Class

Implements the REVNUM field.

For a list of all members of this type, see FieldRevNum Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldRevNum

[Visual Basic]
Public Class FieldRevNum
Inherits Field
[C#]
public class FieldRevNum : Field

Remarks

Retrieves the document's revision number, as recorded in the Revision property of the built-in document properties.

Example

Builds and inserts a field into the document before the specified inline node

[C#]

Document doc = new Document();
Run run = DocumentHelper.InsertNewRun(doc, " Hello World!", 0);

FieldBuilder fieldBuilder = new FieldBuilder(FieldType.FieldRevisionNum);
fieldBuilder.BuildAndInsert(run);

doc.UpdateFields();

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldRevNum Members | Aspose.Words.Fields Namespace


FieldRevNum Members

FieldRevNum overview

Public Instance Constructors

FieldRevNum Constructor Initializes a new instance of the FieldRevNum class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldRevNum Class | Aspose.Words.Fields Namespace


FieldRevNum Constructor

Initializes a new instance of the FieldRevNum class.

[Visual Basic]
Public Sub New()
[C#]
public FieldRevNum();

See Also

FieldRevNum Class | Aspose.Words.Fields Namespace


FieldSaveDate Class

Implements the SAVEDATE field.

For a list of all members of this type, see FieldSaveDate Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSaveDate

[Visual Basic]
Public Class FieldSaveDate
Inherits Field
[C#]
public class FieldSaveDate : Field

Remarks

Retrieves the date and time on which the document was last saved. By default, the Gregorian calendar is used.

Example

Shows how to insert SAVEDATE fields the date and time a document was last saved.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was last saved:");

// Insert a SAVEDATE field and display, using the Lunar Calendar, the date the document was last saved
builder.Write("According to the Lunar Calendar - ");
FieldSaveDate fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseLunarCalendar = true;
Assert.AreEqual(" SAVEDATE  \\h", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\u", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseSakaEraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\s", fieldSaveDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SaveDate.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSaveDate Members | Aspose.Words.Fields Namespace


FieldSaveDate Members

FieldSaveDate overview

Public Instance Constructors

FieldSaveDate Constructor Initializes a new instance of the FieldSaveDate class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSaveDate Class | Aspose.Words.Fields Namespace


FieldSaveDate Constructor

Initializes a new instance of the FieldSaveDate class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSaveDate();

See Also

FieldSaveDate Class | Aspose.Words.Fields Namespace


FieldSaveDate Properties

The properties of the FieldSaveDate class are listed below. For a complete list of FieldSaveDate class members, see the FieldSaveDate Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseLunarCalendar | Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.
UseSakaEraCalendar | Gets or sets whether to use the Saka Era calendar.
UseUmAlQuraCalendar | Gets or sets whether to use the Um-al-Qura calendar.

See Also

FieldSaveDate Class | Aspose.Words.Fields Namespace


UseLunarCalendar Property

Aspose.Words

FieldSaveDate.UseLunarCalendar Property

Gets or sets whether to use the Hijri Lunar or Hebrew Lunar calendar.

[Visual Basic]
Public Property UseLunarCalendar As Boolean
[C#]
public bool UseLunarCalendar {get; set;}

Example

Shows how to insert SAVEDATE fields the date and time a document was last saved.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was last saved:");

// Insert a SAVEDATE field and display, using the Lunar Calendar, the date the document was last saved
builder.Write("According to the Lunar Calendar - ");
FieldSaveDate fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseLunarCalendar = true;
Assert.AreEqual(" SAVEDATE  \\h", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\u", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseSakaEraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\s", fieldSaveDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SaveDate.docx");

See Also

FieldSaveDate Class | Aspose.Words.Fields Namespace


UseSakaEraCalendar Property

Aspose.Words

FieldSaveDate.UseSakaEraCalendar Property

Gets or sets whether to use the Saka Era calendar.

[Visual Basic]
Public Property UseSakaEraCalendar As Boolean
[C#]
public bool UseSakaEraCalendar {get; set;}

Example

Shows how to insert SAVEDATE fields the date and time a document was last saved.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was last saved:");

// Insert a SAVEDATE field and display, using the Lunar Calendar, the date the document was last saved
builder.Write("According to the Lunar Calendar - ");
FieldSaveDate fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseLunarCalendar = true;
Assert.AreEqual(" SAVEDATE  \\h", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\u", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseSakaEraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\s", fieldSaveDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SaveDate.docx");

See Also

FieldSaveDate Class | Aspose.Words.Fields Namespace


UseUmAlQuraCalendar Property

Aspose.Words

FieldSaveDate.UseUmAlQuraCalendar Property

Gets or sets whether to use the Um-al-Qura calendar.

[Visual Basic]
Public Property UseUmAlQuraCalendar As Boolean
[C#]
public bool UseUmAlQuraCalendar {get; set;}

Example

Shows how to insert SAVEDATE fields the date and time a document was last saved.

[C#]

// Open an existing document and move a document builder to the end
Document doc = new Document(MyDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln(" Date this document was last saved:");

// Insert a SAVEDATE field and display, using the Lunar Calendar, the date the document was last saved
builder.Write("According to the Lunar Calendar - ");
FieldSaveDate fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseLunarCalendar = true;
Assert.AreEqual(" SAVEDATE  \\h", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Umm al-Qura Calendar
builder.Write("According to the Umm al-Qura calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseUmAlQuraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\u", fieldSaveDate.GetFieldCode());
builder.Writeln();

// Display the date using the Indian National Calendar
builder.Write("According to the Indian National calendar - ");
fieldSaveDate = (FieldSaveDate)builder.InsertField(FieldType.FieldSaveDate, true);
fieldSaveDate.UseSakaEraCalendar = true;
Assert.AreEqual(" SAVEDATE  \\s", fieldSaveDate.GetFieldCode());
builder.Writeln();

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SaveDate.docx");

See Also

FieldSaveDate Class | Aspose.Words.Fields Namespace


FieldSection Class

Implements the SECTION field.

For a list of all members of this type, see FieldSection Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSection

[Visual Basic]
Public Class FieldSection
Inherits Field
[C#]
public class FieldSection : Field

Remarks

Retrieves the number of the current section.

Example

Shows how to use SECTION and SECTIONPAGES fields to facilitate page numbering separated by sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Move the document builder to the header that appears across all pages and align to the top right
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;

// A SECTION field displays the number of the section it is placed in
builder.Write("Section ");
FieldSection fieldSection = (FieldSection)builder.InsertField(FieldType.FieldSection, true);

Assert.AreEqual(" SECTION ", fieldSection.GetFieldCode());

// A PAGE field displays the number of the page it is placed in
builder.Write("\nPage ");
FieldPage fieldPage = (FieldPage)builder.InsertField(FieldType.FieldPage, true);

Assert.AreEqual(" PAGE ", fieldPage.GetFieldCode());

// A SECTIONPAGES field displays the number of pages that the section it is in spans across
builder.Write(" of ");
FieldSectionPages fieldSectionPages = (FieldSectionPages)builder.InsertField(FieldType.FieldSectionPages, true);

Assert.AreEqual(" SECTIONPAGES ", fieldSectionPages.GetFieldCode());

// Move out of the header back into the main document and insert two pages
// Both these pages will be in the first section and our three fields will keep track of the numbers in each header
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// We can insert a new section with the document builder like this
// This will change the values displayed in the SECTION and SECTIONPAGES fields in all upcoming headers
builder.InsertBreak(BreakType.SectionBreakNewPage);

// The PAGE field will keep counting pages across the whole document
// We can manually reset its count after a new section is added to keep track of pages section-by-section
builder.CurrentSection.PageSetup.RestartPageNumbering = true;
builder.InsertBreak(BreakType.PageBreak);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SECTION.SECTIONPAGES.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSection Members | Aspose.Words.Fields Namespace


FieldSection Members

FieldSection overview

Public Instance Constructors

FieldSection Constructor Initializes a new instance of the FieldSection class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSection Class | Aspose.Words.Fields Namespace


FieldSection Constructor

Initializes a new instance of the FieldSection class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSection();

See Also

FieldSection Class | Aspose.Words.Fields Namespace


FieldSectionPages Class

Implements the SECTIONPAGES field.

For a list of all members of this type, see FieldSectionPages Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSectionPages

[Visual Basic]
Public Class FieldSectionPages
Inherits Field
[C#]
public class FieldSectionPages : Field

Remarks

Retrieves the number of the current page within the current section.

Example

Shows how to use SECTION and SECTIONPAGES fields to facilitate page numbering separated by sections.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Move the document builder to the header that appears across all pages and align to the top right
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;

// A SECTION field displays the number of the section it is placed in
builder.Write("Section ");
FieldSection fieldSection = (FieldSection)builder.InsertField(FieldType.FieldSection, true);

Assert.AreEqual(" SECTION ", fieldSection.GetFieldCode());

// A PAGE field displays the number of the page it is placed in
builder.Write("\nPage ");
FieldPage fieldPage = (FieldPage)builder.InsertField(FieldType.FieldPage, true);

Assert.AreEqual(" PAGE ", fieldPage.GetFieldCode());

// A SECTIONPAGES field displays the number of pages that the section it is in spans across
builder.Write(" of ");
FieldSectionPages fieldSectionPages = (FieldSectionPages)builder.InsertField(FieldType.FieldSectionPages, true);

Assert.AreEqual(" SECTIONPAGES ", fieldSectionPages.GetFieldCode());

// Move out of the header back into the main document and insert two pages
// Both these pages will be in the first section and our three fields will keep track of the numbers in each header
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// We can insert a new section with the document builder like this
// This will change the values displayed in the SECTION and SECTIONPAGES fields in all upcoming headers
builder.InsertBreak(BreakType.SectionBreakNewPage);

// The PAGE field will keep counting pages across the whole document
// We can manually reset its count after a new section is added to keep track of pages section-by-section
builder.CurrentSection.PageSetup.RestartPageNumbering = true;
builder.InsertBreak(BreakType.PageBreak);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SECTION.SECTIONPAGES.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSectionPages Members | Aspose.Words.Fields Namespace


FieldSectionPages Members

FieldSectionPages overview

Public Instance Constructors

FieldSectionPages Constructor Initializes a new instance of the FieldSectionPages class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSectionPages Class | Aspose.Words.Fields Namespace


FieldSectionPages Constructor

Initializes a new instance of the FieldSectionPages class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSectionPages();

See Also

FieldSectionPages Class | Aspose.Words.Fields Namespace


FieldSeparator Class

Represents a Word field separator that separates the field code from the field result.

For a list of all members of this type, see FieldSeparator Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.Fields.FieldChar
Aspose.Words.Fields.FieldSeparator

[Visual Basic]
Public Class FieldSeparator
Inherits FieldChar
[C#]
public class FieldSeparator : FieldChar

Remarks

FieldSeparator is an inline-level node and represented by the FieldSeparatorChar control character in the document.

FieldSeparator can only be a child of Paragraph.

A complete field in a Microsoft Word document is a complex structure consisting of a field start character, field code, field separator character, field result and field end character. Some fields only have field start, field code and field end.

To easily insert a new field into a document, use the InsertField method.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSeparator Members | Aspose.Words.Fields Namespace


FieldSeparator Members

FieldSeparator overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType (inherited from FieldChar) | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty (inherited from FieldChar) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked (inherited from FieldChar) | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns FieldSeparator.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField (inherited from FieldChar) | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldSeparator Class | Aspose.Words.Fields Namespace


FieldSeparator Properties

The properties of the FieldSeparator class are listed below. For a complete list of FieldSeparator class members, see the FieldSeparator Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType (inherited from FieldChar) | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty (inherited from FieldChar) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked (inherited from FieldChar) | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns FieldSeparator.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

FieldSeparator Class | Aspose.Words.Fields Namespace


NodeType Property

Aspose.Words

FieldSeparator.NodeType Property

Returns FieldSeparator.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

FieldSeparator Class | Aspose.Words.Fields Namespace


FieldSeparator Methods

The methods of the FieldSeparator class are listed below. For a complete list of FieldSeparator class members, see the FieldSeparator Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField (inherited from FieldChar) | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldSeparator Class | Aspose.Words.Fields Namespace


FieldSeparator.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls VisitFieldSeparator.

For more info see the Visitor design pattern.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldSeparator Class | Aspose.Words.Fields Namespace


FieldSeq Class

Implements the SEQ field.

For a list of all members of this type, see FieldSeq Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSeq

[Visual Basic]
Public Class FieldSeq
Inherits Field
[C#]
public class FieldSeq : Field

Remarks

Sequentially numbers chapters, tables, figures, and other user-defined lists of items in a document.

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSeq Members | Aspose.Words.Fields Namespace


FieldSeq Members

FieldSeq overview

Public Instance Constructors

FieldSeq Constructor Initializes a new instance of the FieldSeq class.

Public Instance Properties

BookmarkName | Gets or sets a bookmark name that refers to an item elsewhere in the document rather than in the current location.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertNextNumber | Gets or sets whether to insert the next sequence number for the specified item.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ResetHeadingLevel | Gets or sets an integer number representing a heading level to reset the sequence number to. Returns -1 if the number is absent.
ResetNumber | Gets or sets an integer number to reset the sequence number to. Returns -1 if the number is absent.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceIdentifier | Gets or sets the name assigned to the series of items that are to be numbered.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


FieldSeq Constructor

Initializes a new instance of the FieldSeq class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSeq();

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


FieldSeq Properties

The properties of the FieldSeq class are listed below. For a complete list of FieldSeq class members, see the FieldSeq Members topic.

Public Instance Properties

BookmarkName | Gets or sets a bookmark name that refers to an item elsewhere in the document rather than in the current location.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertNextNumber | Gets or sets whether to insert the next sequence number for the specified item.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
ResetHeadingLevel | Gets or sets an integer number representing a heading level to reset the sequence number to. Returns -1 if the number is absent.
ResetNumber | Gets or sets an integer number to reset the sequence number to. Returns -1 if the number is absent.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceIdentifier | Gets or sets the name assigned to the series of items that are to be numbered.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldSeq.BookmarkName Property

Gets or sets a bookmark name that refers to an item elsewhere in the document rather than in the current location.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


InsertNextNumber Property

Aspose.Words

FieldSeq.InsertNextNumber Property

Gets or sets whether to insert the next sequence number for the specified item.

[Visual Basic]
Public Property InsertNextNumber As Boolean
[C#]
public bool InsertNextNumber {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


ResetHeadingLevel Property

Aspose.Words

FieldSeq.ResetHeadingLevel Property

Gets or sets an integer number representing a heading level to reset the sequence number to. Returns -1 if the number is absent.

[Visual Basic]
Public Property ResetHeadingLevel As String
[C#]
public string ResetHeadingLevel {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


ResetNumber Property

Aspose.Words

FieldSeq.ResetNumber Property

Gets or sets an integer number to reset the sequence number to. Returns -1 if the number is absent.

[Visual Basic]
Public Property ResetNumber As String
[C#]
public string ResetNumber {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


SequenceIdentifier Property

Aspose.Words

FieldSeq.SequenceIdentifier Property

Gets or sets the name assigned to the series of items that are to be numbered.

[Visual Basic]
Public Property SequenceIdentifier As String
[C#]
public string SequenceIdentifier {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldSeq Class | Aspose.Words.Fields Namespace


FieldSet Class

Implements the SET field.

For a list of all members of this type, see FieldSet Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSet

[Visual Basic]
Public Class FieldSet
Inherits Field
[C#]
public class FieldSet : Field

Remarks

Assigns new text to a bookmark.

Example

Shows to alter a bookmark's text with a SET field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartBookmark("MyBookmark");
builder.Writeln("Bookmark contents");
builder.EndBookmark("MyBookmark");

Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
bookmark.Text = "Old text";

FieldSet field = (FieldSet)builder.InsertField(FieldType.FieldSet, false);
field.BookmarkName = "MyBookmark";
field.BookmarkText = "New text";

Assert.AreEqual(" SET  MyBookmark \"New text\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SET.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSet Members | Aspose.Words.Fields Namespace


FieldSet Members

FieldSet overview

Public Instance Constructors

FieldSet Constructor Initializes a new instance of the FieldSet class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
BookmarkText | Gets or sets the new text of the bookmark.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSet Class | Aspose.Words.Fields Namespace


FieldSet Constructor

Initializes a new instance of the FieldSet class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSet();

See Also

FieldSet Class | Aspose.Words.Fields Namespace


FieldSet Properties

The properties of the FieldSet class are listed below. For a complete list of FieldSet class members, see the FieldSet Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark.
BookmarkText | Gets or sets the new text of the bookmark.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldSet Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldSet.BookmarkName Property

Gets or sets the name of the bookmark.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows to alter a bookmark's text with a SET field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartBookmark("MyBookmark");
builder.Writeln("Bookmark contents");
builder.EndBookmark("MyBookmark");

Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
bookmark.Text = "Old text";

FieldSet field = (FieldSet)builder.InsertField(FieldType.FieldSet, false);
field.BookmarkName = "MyBookmark";
field.BookmarkText = "New text";

Assert.AreEqual(" SET  MyBookmark \"New text\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SET.docx");

See Also

FieldSet Class | Aspose.Words.Fields Namespace


BookmarkText Property

Aspose.Words

FieldSet.BookmarkText Property

Gets or sets the new text of the bookmark.

[Visual Basic]
Public Property BookmarkText As String
[C#]
public string BookmarkText {get; set;}

Example

Shows to alter a bookmark's text with a SET field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartBookmark("MyBookmark");
builder.Writeln("Bookmark contents");
builder.EndBookmark("MyBookmark");

Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
bookmark.Text = "Old text";

FieldSet field = (FieldSet)builder.InsertField(FieldType.FieldSet, false);
field.BookmarkName = "MyBookmark";
field.BookmarkText = "New text";

Assert.AreEqual(" SET  MyBookmark \"New text\"", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.SET.docx");

See Also

FieldSet Class | Aspose.Words.Fields Namespace


FieldShape Class

Implements the SHAPE field.

For a list of all members of this type, see FieldShape Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldShape

[Visual Basic]
Public Class FieldShape
Inherits Field
[C#]
public class FieldShape : Field

Remarks

Retrieves the specified text.

Example

Shows how to create RTL lists with BIDIOUTLINE fields.

[C#]

// Create a blank document and a document builder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use our builder to insert a BIDIOUTLINE field
// This field numbers paragraphs like the AUTONUM/LISTNUM fields,
// but is only visible when a RTL editing language is enabled, such as Hebrew or Arabic
// The following field will display ".1", the RTL equivalent of list number "1."
FieldBidiOutline field = (FieldBidiOutline)builder.InsertField(FieldType.FieldBidiOutline, true);
Assert.AreEqual(" BIDIOUTLINE ", field.GetFieldCode());
builder.Writeln("שלום");

// Add two more BIDIOUTLINE fields, which will be automatically numbered ".2" and ".3"
builder.InsertField(FieldType.FieldBidiOutline, true);
builder.Writeln("שלום");
builder.InsertField(FieldType.FieldBidiOutline, true);
builder.Writeln("שלום");

// Set the horizontal text alignment for every paragraph in the document to RTL
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
{
    para.ParagraphFormat.Bidi = true;
}

// If a RTL editing language is enabled in Microsoft Word, out fields will display numbers
// Otherwise, they will appear as "###"
doc.Save(ArtifactsDir + "Field.BIDIOUTLINE.docx");
Shows how some older Microsoft Word fields such as SHAPE and EMBED are handled.
[C#]

// Open a document that was created in Microsoft Word 2003
Document doc = new Document(MyDir + "Field.Legacy.doc");

// If we open the document in Word and press Alt+F9, we will see a SHAPE and an EMBED field
// A SHAPE field is the anchor/canvas for an autoshape object with the "In line with text" wrapping style enabled
// An EMBED field has the same function, but for an embedded object, such as a spreadsheet from an external Excel document
// However, these fields will not appear in the document's Fields collection
Assert.AreEqual(0, doc.Range.Fields.Count);

// These fields are supported only by old versions of Microsoft Word
// As such, they are converted into shapes during the document importation process and can instead be found in the collection of Shape nodes
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
Assert.AreEqual(3, shapes.Count);

// The first Shape node corresponds to what was the SHAPE field in the input document: the inline canvas for an autoshape
Shape shape = (Shape)shapes[0];
Assert.AreEqual(ShapeType.Image, shape.ShapeType);

// The next Shape node is the autoshape that is within the canvas
shape = (Shape)shapes[1];
Assert.AreEqual(ShapeType.Can, shape.ShapeType);

// The third Shape is what was the EMBED field that contained the external spreadsheet
shape = (Shape)shapes[2];
Assert.AreEqual(ShapeType.OleObject, shape.ShapeType);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldShape Members | Aspose.Words.Fields Namespace


FieldShape Members

FieldShape overview

Public Instance Constructors

FieldShape Constructor Initializes a new instance of the FieldShape class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text to retrieve.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldShape Class | Aspose.Words.Fields Namespace


FieldShape Constructor

Initializes a new instance of the FieldShape class.

[Visual Basic]
Public Sub New()
[C#]
public FieldShape();

See Also

FieldShape Class | Aspose.Words.Fields Namespace


FieldShape Properties

The properties of the FieldShape class are listed below. For a complete list of FieldShape class members, see the FieldShape Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text to retrieve.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldShape Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldShape.Text Property

Gets or sets the text to retrieve.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to create RTL lists with BIDIOUTLINE fields.

[C#]

// Create a blank document and a document builder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use our builder to insert a BIDIOUTLINE field
// This field numbers paragraphs like the AUTONUM/LISTNUM fields,
// but is only visible when a RTL editing language is enabled, such as Hebrew or Arabic
// The following field will display ".1", the RTL equivalent of list number "1."
FieldBidiOutline field = (FieldBidiOutline)builder.InsertField(FieldType.FieldBidiOutline, true);
Assert.AreEqual(" BIDIOUTLINE ", field.GetFieldCode());
builder.Writeln("שלום");

// Add two more BIDIOUTLINE fields, which will be automatically numbered ".2" and ".3"
builder.InsertField(FieldType.FieldBidiOutline, true);
builder.Writeln("שלום");
builder.InsertField(FieldType.FieldBidiOutline, true);
builder.Writeln("שלום");

// Set the horizontal text alignment for every paragraph in the document to RTL
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
{
    para.ParagraphFormat.Bidi = true;
}

// If a RTL editing language is enabled in Microsoft Word, out fields will display numbers
// Otherwise, they will appear as "###"
doc.Save(ArtifactsDir + "Field.BIDIOUTLINE.docx");
Shows how some older Microsoft Word fields such as SHAPE and EMBED are handled.
[C#]

// Open a document that was created in Microsoft Word 2003
Document doc = new Document(MyDir + "Field.Legacy.doc");

// If we open the document in Word and press Alt+F9, we will see a SHAPE and an EMBED field
// A SHAPE field is the anchor/canvas for an autoshape object with the "In line with text" wrapping style enabled
// An EMBED field has the same function, but for an embedded object, such as a spreadsheet from an external Excel document
// However, these fields will not appear in the document's Fields collection
Assert.AreEqual(0, doc.Range.Fields.Count);

// These fields are supported only by old versions of Microsoft Word
// As such, they are converted into shapes during the document importation process and can instead be found in the collection of Shape nodes
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
Assert.AreEqual(3, shapes.Count);

// The first Shape node corresponds to what was the SHAPE field in the input document: the inline canvas for an autoshape
Shape shape = (Shape)shapes[0];
Assert.AreEqual(ShapeType.Image, shape.ShapeType);

// The next Shape node is the autoshape that is within the canvas
shape = (Shape)shapes[1];
Assert.AreEqual(ShapeType.Can, shape.ShapeType);

// The third Shape is what was the EMBED field that contained the external spreadsheet
shape = (Shape)shapes[2];
Assert.AreEqual(ShapeType.OleObject, shape.ShapeType);

See Also

FieldShape Class | Aspose.Words.Fields Namespace


FieldSkipIf Class

Implements the SKIPIF field.

For a list of all members of this type, see FieldSkipIf Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSkipIf

[Visual Basic]
Public Class FieldSkipIf
Inherits Field
[C#]
public class FieldSkipIf : Field

Remarks

Compares the values designated by the expressions LeftExpression and RightExpression in comparison using the operator designated by ComparisonOperator. If the comparison is true, SKIPIF cancels the current merge document, moves to the next data record in the data source, and starts a new merge document. If the comparison is false, the current merge document is continued.

Example

Shows how to skip pages in a mail merge using the SKIPIF field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a data table that will be the source for our mail merge
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Name");
table.Columns.Add("Department");
table.Rows.Add("John Doe", "Sales");
table.Rows.Add("Jane Doe", "Accounting");
table.Rows.Add("John Cardholder", "HR");

// Insert a SKIPIF field, which will skip a page of a mail merge if the condition is fulfilled
// We will move to the SKIPIF field's separator character and insert a MERGEFIELD at that place to create a nested field
FieldSkipIf fieldSkipIf = (FieldSkipIf) builder.InsertField(FieldType.FieldSkipIf, true);
builder.MoveTo(fieldSkipIf.Separator);
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Department";

// The MERGEFIELD refers to the "Department" column in our data table, and our SKIPIF field will check if its value equals to "HR"
// One of three rows satisfies that condition, so we will expect the result of our mail merge to have two pages
fieldSkipIf.LeftExpression = "=";
fieldSkipIf.RightExpression = "HR";

// Add some content to our mail merge and execute it
builder.MoveToDocumentEnd();
builder.Write("Dear ");
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
builder.Writeln(", ");

doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.SKIPIF.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSkipIf Members | Aspose.Words.Fields Namespace


FieldSkipIf Members

FieldSkipIf overview

Public Instance Constructors

FieldSkipIf Constructor Initializes a new instance of the FieldSkipIf class.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSkipIf Class | Aspose.Words.Fields Namespace


FieldSkipIf Constructor

Initializes a new instance of the FieldSkipIf class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSkipIf();

See Also

FieldSkipIf Class | Aspose.Words.Fields Namespace


FieldSkipIf Properties

The properties of the FieldSkipIf class are listed below. For a complete list of FieldSkipIf class members, see the FieldSkipIf Members topic.

Public Instance Properties

ComparisonOperator | Gets or sets the comparison operator.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LeftExpression | Gets or sets the left part of the comparison expression.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
RightExpression | Gets or sets the right part of the comparison expression.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldSkipIf Class | Aspose.Words.Fields Namespace


ComparisonOperator Property

Aspose.Words

FieldSkipIf.ComparisonOperator Property

Gets or sets the comparison operator.

[Visual Basic]
Public Property ComparisonOperator As String
[C#]
public string ComparisonOperator {get; set;}

Example

Shows how to skip pages in a mail merge using the SKIPIF field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a data table that will be the source for our mail merge
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Name");
table.Columns.Add("Department");
table.Rows.Add("John Doe", "Sales");
table.Rows.Add("Jane Doe", "Accounting");
table.Rows.Add("John Cardholder", "HR");

// Insert a SKIPIF field, which will skip a page of a mail merge if the condition is fulfilled
// We will move to the SKIPIF field's separator character and insert a MERGEFIELD at that place to create a nested field
FieldSkipIf fieldSkipIf = (FieldSkipIf) builder.InsertField(FieldType.FieldSkipIf, true);
builder.MoveTo(fieldSkipIf.Separator);
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Department";

// The MERGEFIELD refers to the "Department" column in our data table, and our SKIPIF field will check if its value equals to "HR"
// One of three rows satisfies that condition, so we will expect the result of our mail merge to have two pages
fieldSkipIf.LeftExpression = "=";
fieldSkipIf.RightExpression = "HR";

// Add some content to our mail merge and execute it
builder.MoveToDocumentEnd();
builder.Write("Dear ");
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
builder.Writeln(", ");

doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.SKIPIF.docx");

See Also

FieldSkipIf Class | Aspose.Words.Fields Namespace


LeftExpression Property

Aspose.Words

FieldSkipIf.LeftExpression Property

Gets or sets the left part of the comparison expression.

[Visual Basic]
Public Property LeftExpression As String
[C#]
public string LeftExpression {get; set;}

Example

Shows how to skip pages in a mail merge using the SKIPIF field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a data table that will be the source for our mail merge
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Name");
table.Columns.Add("Department");
table.Rows.Add("John Doe", "Sales");
table.Rows.Add("Jane Doe", "Accounting");
table.Rows.Add("John Cardholder", "HR");

// Insert a SKIPIF field, which will skip a page of a mail merge if the condition is fulfilled
// We will move to the SKIPIF field's separator character and insert a MERGEFIELD at that place to create a nested field
FieldSkipIf fieldSkipIf = (FieldSkipIf) builder.InsertField(FieldType.FieldSkipIf, true);
builder.MoveTo(fieldSkipIf.Separator);
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Department";

// The MERGEFIELD refers to the "Department" column in our data table, and our SKIPIF field will check if its value equals to "HR"
// One of three rows satisfies that condition, so we will expect the result of our mail merge to have two pages
fieldSkipIf.LeftExpression = "=";
fieldSkipIf.RightExpression = "HR";

// Add some content to our mail merge and execute it
builder.MoveToDocumentEnd();
builder.Write("Dear ");
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
builder.Writeln(", ");

doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.SKIPIF.docx");

See Also

FieldSkipIf Class | Aspose.Words.Fields Namespace


RightExpression Property

Aspose.Words

FieldSkipIf.RightExpression Property

Gets or sets the right part of the comparison expression.

[Visual Basic]
Public Property RightExpression As String
[C#]
public string RightExpression {get; set;}

Example

Shows how to skip pages in a mail merge using the SKIPIF field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a data table that will be the source for our mail merge
System.Data.DataTable table = new System.Data.DataTable("Employees");
table.Columns.Add("Name");
table.Columns.Add("Department");
table.Rows.Add("John Doe", "Sales");
table.Rows.Add("Jane Doe", "Accounting");
table.Rows.Add("John Cardholder", "HR");

// Insert a SKIPIF field, which will skip a page of a mail merge if the condition is fulfilled
// We will move to the SKIPIF field's separator character and insert a MERGEFIELD at that place to create a nested field
FieldSkipIf fieldSkipIf = (FieldSkipIf) builder.InsertField(FieldType.FieldSkipIf, true);
builder.MoveTo(fieldSkipIf.Separator);
FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Department";

// The MERGEFIELD refers to the "Department" column in our data table, and our SKIPIF field will check if its value equals to "HR"
// One of three rows satisfies that condition, so we will expect the result of our mail merge to have two pages
fieldSkipIf.LeftExpression = "=";
fieldSkipIf.RightExpression = "HR";

// Add some content to our mail merge and execute it
builder.MoveToDocumentEnd();
builder.Write("Dear ");
fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
fieldMergeField.FieldName = "Name";
builder.Writeln(", ");

doc.MailMerge.Execute(table);
doc.Save(ArtifactsDir + "Field.SKIPIF.docx");

See Also

FieldSkipIf Class | Aspose.Words.Fields Namespace


FieldStart Class

Represents a start of a Word field in a document.

For a list of all members of this type, see FieldStart Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.Fields.FieldChar
Aspose.Words.Fields.FieldStart

[Visual Basic]
Public Class FieldStart
Inherits FieldChar
[C#]
public class FieldStart : FieldChar

Remarks

FieldStart is an inline-level node and represented by the FieldStartChar control character in the document.

FieldStart can only be a child of Paragraph.

A complete field in a Microsoft Word document is a complex structure consisting of a field start character, field code, field separator character, field result and field end character. Some fields only have field start, field code and field end.

To easily insert a new field into a document, use the InsertField method.

Example

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}
Finds all hyperlinks in a Word document and changes their URL and display name.
[C#]

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Fields;
using NUnit.Framework;

namespace ApiExamples
{
    /// <summary>
    /// Shows how to replace hyperlinks in a Word document.
    /// </summary>
    public class ExReplaceHyperlinks : ApiExampleBase
    {
        /// <summary>
        /// Finds all hyperlinks in a Word document and changes their URL and display name.
        /// </summary>
        public void ReplaceHyperlinks()
        {
            // Specify your document name here.
            Document doc = new Document(MyDir + "ReplaceHyperlinks.doc");

            // Hyperlinks in a Word documents are fields, select all field start nodes so we can find the hyperlinks.
            NodeList fieldStarts = doc.SelectNodes("//FieldStart");
            foreach (FieldStart fieldStart in fieldStarts.OfType<FieldStart>())
            {
                if (fieldStart.FieldType.Equals(FieldType.FieldHyperlink))
                {
                    // The field is a hyperlink field, use the "facade" class to help to deal with the field.
                    Hyperlink hyperlink = new Hyperlink(fieldStart);

                    // Some hyperlinks can be local (links to bookmarks inside the document), ignore these.
                    if (hyperlink.IsLocal)
                        continue;

                    // The Hyperlink class allows to set the target URL and the display name
                    // of the link easily by setting the properties.
                    hyperlink.Target = NewUrl;
                    hyperlink.Name = NewName;
                }
            }

            doc.Save(ArtifactsDir + "ReplaceHyperlinks.doc");
        }

        private const String NewUrl = @"http://www.aspose.com";
        private const String NewName = "Aspose - The .NET & Java Component Publisher";
    }

    /// <summary>
    /// This "facade" class makes it easier to work with a hyperlink field in a Word document.
    ///
    /// A hyperlink is represented by a HYPERLINK field in a Word document. A field in Aspose.Words
    /// consists of several nodes and it might be difficult to work with all those nodes directly.
    /// Note this is a simple implementation and will work only if the hyperlink code and name
    /// each consist of one Run only.
    ///
    /// [FieldStart][Run - field code][FieldSeparator][Run - field result][FieldEnd]
    ///
    /// The field code contains a String in one of these formats:
    /// HYPERLINK "url"
    /// HYPERLINK \l "bookmark name"
    ///
    /// The field result contains text that is displayed to the user.
    /// </summary>
    internal class Hyperlink
    {
        internal Hyperlink(FieldStart fieldStart)
        {
            if (fieldStart == null)
                throw new ArgumentNullException("fieldStart");
            if (!fieldStart.FieldType.Equals(FieldType.FieldHyperlink))
                throw new ArgumentException("Field start type must be FieldHyperlink.");

            mFieldStart = fieldStart;

            // Find the field separator node.
            mFieldSeparator = FindNextSibling(mFieldStart, NodeType.FieldSeparator);
            if (mFieldSeparator == null)
                throw new InvalidOperationException("Cannot find field separator.");

            // Find the field end node. Normally field end will always be found, but in the example document
            // there happens to be a paragraph break included in the hyperlink and this puts the field end
            // in the next paragraph. It will be much more complicated to handle fields which span several
            // paragraphs correctly, but in this case allowing field end to be null is enough for our purposes.
            mFieldEnd = FindNextSibling(mFieldSeparator, NodeType.FieldEnd);

            // Field code looks something like [ HYPERLINK "http:\\www.myurl.com" ], but it can consist of several runs.
            String fieldCode = GetTextSameParent(mFieldStart.NextSibling, mFieldSeparator);
            Match match = gRegex.Match(fieldCode.Trim());
            mIsLocal = (match.Groups[1].Length > 0); //The link is local if \l is present in the field code.
            mTarget = match.Groups[2].Value;
        }

        /// <summary>
        /// Gets or sets the display name of the hyperlink.
        /// </summary>
        internal String Name
        {
            get { return GetTextSameParent(mFieldSeparator, mFieldEnd); }
            set
            {
                // Hyperlink display name is stored in the field result which is a Run
                // node between field separator and field end.
                Run fieldResult = (Run) mFieldSeparator.NextSibling;
                fieldResult.Text = value;

                // But sometimes the field result can consist of more than one run, delete these runs.
                RemoveSameParent(fieldResult.NextSibling, mFieldEnd);
            }
        }

        /// <summary>
        /// Gets or sets the target url or bookmark name of the hyperlink.
        /// </summary>
        internal String Target
        {
            get
            {
                return mTarget;
            }
            set
            {
                mTarget = value;
                UpdateFieldCode();
            }
        }

        /// <summary>
        /// True if the hyperlinks target is a bookmark inside the document. False if the hyperlink is a url.
        /// </summary>
        internal bool IsLocal
        {
            get { return mIsLocal; }
            set
            {
                mIsLocal = value;
                UpdateFieldCode();
            }
        }

        private void UpdateFieldCode()
        {
            // Field code is stored in a Run node between field start and field separator.
            Run fieldCode = (Run) mFieldStart.NextSibling;
            fieldCode.Text = String.Format("HYPERLINK {0}\"{1}\"", ((mIsLocal) ? "\\l " : ""), mTarget);

            // But sometimes the field code can consist of more than one run, delete these runs.
            RemoveSameParent(fieldCode.NextSibling, mFieldSeparator);
        }

        /// <summary>
        /// Goes through siblings starting from the start node until it finds a node of the specified type or null.
        /// </summary>
        private static Node FindNextSibling(Node startNode, NodeType nodeType)
        {
            for (Node node = startNode; node != null; node = node.NextSibling)
            {
                if (node.NodeType.Equals(nodeType))
                    return node;
            }

            return null;
        }

        /// <summary>
        /// Retrieves text from start up to but not including the end node.
        /// </summary>
        private static String GetTextSameParent(Node startNode, Node endNode)
        {
            if ((endNode != null) && (startNode.ParentNode != endNode.ParentNode))
                throw new ArgumentException("Start and end nodes are expected to have the same parent.");

            StringBuilder builder = new StringBuilder();
            for (Node child = startNode; !child.Equals(endNode); child = child.NextSibling)
                builder.Append(child.GetText());

            return builder.ToString();
        }

        /// <summary>
        /// Removes nodes from start up to but not including the end node.
        /// Start and end are assumed to have the same parent.
        /// </summary>
        private static void RemoveSameParent(Node startNode, Node endNode)
        {
            if ((endNode != null) && (startNode.ParentNode != endNode.ParentNode))
                throw new ArgumentException("Start and end nodes are expected to have the same parent.");

            Node curChild = startNode;
            while ((curChild != null) && (curChild != endNode))
            {
                Node nextChild = curChild.NextSibling;
                curChild.Remove();
                curChild = nextChild;
            }
        }

        private readonly Node mFieldStart;
        private readonly Node mFieldSeparator;
        private readonly Node mFieldEnd;
        private bool mIsLocal;
        private String mTarget;

        /// <summary>
        /// RK I am notoriously bad at regexes. It seems I don't understand their way of thinking.
        /// </summary>
        private static readonly Regex gRegex = new Regex(
            "\\S+" + // one or more non spaces HYPERLINK or other word in other languages
            "\\s+" + // one or more spaces
            "(?:\"\"\\s+)?" + // non capturing optional "" and one or more spaces, found in one of the customers files.
            "(\\\\l\\s+)?" + // optional \l flag followed by one or more spaces
            "\"" + // one apostrophe
            "([^\"]+)" + // one or more chars except apostrophe (hyperlink target)
            "\"" // one closing apostrophe
        );
    }
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldStart Members | Aspose.Words.Fields Namespace


FieldStart Members

FieldStart overview

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType (inherited from FieldChar) | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty (inherited from FieldChar) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked (inherited from FieldChar) | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns FieldStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField (inherited from FieldChar) | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldStart Class | Aspose.Words.Fields Namespace


FieldStart Properties

The properties of the FieldStart class are listed below. For a complete list of FieldStart class members, see the FieldStart Members topic.

Public Instance Properties

Document (inherited from Node) | Gets the document to which this node belongs.
FieldType (inherited from FieldChar) | Returns the type of the field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsDirty (inherited from FieldChar) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsLocked (inherited from FieldChar) | Gets or sets whether the parent field is locked (should not recalculate its result).
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns FieldStart.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

FieldStart Class | Aspose.Words.Fields Namespace


NodeType Property

Aspose.Words

FieldStart.NodeType Property

Returns FieldStart.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

FieldStart Class | Aspose.Words.Fields Namespace


FieldStart Methods

The methods of the FieldStart class are listed below. For a complete list of FieldStart class members, see the FieldStart Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetField (inherited from FieldChar) | Returns a field for the field char.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FieldStart Class | Aspose.Words.Fields Namespace


FieldStart.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
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

Shows how to work with a document's field collection.

[C#]

public void FieldCollection()
{
    // Open a document that has fields
    Document doc = new Document(MyDir + "Document.ContainsFields.docx");

    // Get the collection that contains all the fields in a document
    FieldCollection fields = doc.Range.Fields;
    Assert.AreEqual(6, fields.Count);

    // Iterate over the field collection and print contents and type of every field using a custom visitor implementation
    FieldVisitor fieldVisitor = new FieldVisitor();

    using (IEnumerator<Field> fieldEnumerator = fields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            if (fieldEnumerator.Current != null)
            {
                fieldEnumerator.Current.Start.Accept(fieldVisitor);
                fieldEnumerator.Current.Separator?.Accept(fieldVisitor);
                fieldEnumerator.Current.End.Accept(fieldVisitor);
            }
            else
            {
                Console.WriteLine("There are no fields in the document.");
            }
        }
    }

    Console.WriteLine(fieldVisitor.GetText());

    // Get a field to remove itself
    fields[0].Remove();
    Assert.AreEqual(5, fields.Count);

    // Remove a field by reference
    Field lastField = fields[3];
    fields.Remove(lastField);
    Assert.AreEqual(4, fields.Count);

    // Remove a field by index
    fields.RemoveAt(2);
    Assert.AreEqual(3, fields.Count);

    // Remove all fields from the document
    fields.Clear();
    Assert.AreEqual(0, fields.Count);
}

/// <summary>
/// Document visitor implementation that prints field info
/// </summary>
public class FieldVisitor : DocumentVisitor
{
    public FieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        mBuilder.AppendLine("Found field: " + fieldStart.FieldType);
        mBuilder.AppendLine("\tField code: " + fieldStart.GetField().GetFieldCode());
        mBuilder.AppendLine("\tDisplayed as: " + fieldStart.GetField().Result);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        mBuilder.AppendLine("\tFound separator: " + fieldSeparator.GetText());

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        mBuilder.AppendLine("End of field: " + fieldEnd.FieldType);

        return VisitorAction.Continue;
    }

    private readonly StringBuilder mBuilder;
}

See Also

FieldStart Class | Aspose.Words.Fields Namespace


FieldStyleRef Class

Implements the STYLEREF field.

For a list of all members of this type, see FieldStyleRef Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldStyleRef

[Visual Basic]
Public Class FieldStyleRef
Inherits Field
[C#]
public class FieldStyleRef : Field

Remarks

The STYLEREF is used to reference a fragment of text within the document that is formatted with the specified style.

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldStyleRef Members | Aspose.Words.Fields Namespace


FieldStyleRef Members

FieldStyleRef overview

Public Instance Constructors

FieldStyleRef Constructor Initializes a new instance of the FieldStyleRef class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertParagraphNumber | Gets or sets whether to insert the paragraph number of the referenced paragraph exactly as it appears in the document.
InsertParagraphNumberInFullContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in full context.
InsertParagraphNumberInRelativeContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in relative context.
InsertRelativePosition | Gets or sets whether to insert the relative position of the referenced paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
SearchFromBottom | Gets or sets whether to search from the bottom of the current page, rather from the top.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
StyleName | Gets or sets the name of the style by which the text to search for is formatted.
SuppressNonDelimiters | Gets or sets whether to suppress non-delimiter characters.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


FieldStyleRef Constructor

Initializes a new instance of the FieldStyleRef class.

[Visual Basic]
Public Sub New()
[C#]
public FieldStyleRef();

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


FieldStyleRef Properties

The properties of the FieldStyleRef class are listed below. For a complete list of FieldStyleRef class members, see the FieldStyleRef Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
InsertParagraphNumber | Gets or sets whether to insert the paragraph number of the referenced paragraph exactly as it appears in the document.
InsertParagraphNumberInFullContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in full context.
InsertParagraphNumberInRelativeContext | Gets or sets whether to insert the paragraph number of the referenced paragraph in relative context.
InsertRelativePosition | Gets or sets whether to insert the relative position of the referenced paragraph.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
SearchFromBottom | Gets or sets whether to search from the bottom of the current page, rather from the top.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
StyleName | Gets or sets the name of the style by which the text to search for is formatted.
SuppressNonDelimiters | Gets or sets whether to suppress non-delimiter characters.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


InsertParagraphNumber Property

Aspose.Words

FieldStyleRef.InsertParagraphNumber Property

Gets or sets whether to insert the paragraph number of the referenced paragraph exactly as it appears in the document.

[Visual Basic]
Public Property InsertParagraphNumber As Boolean
[C#]
public bool InsertParagraphNumber {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


InsertParagraphNumberInFullContext Property

Aspose.Words

FieldStyleRef.InsertParagraphNumberInFullContext Property

Gets or sets whether to insert the paragraph number of the referenced paragraph in full context.

[Visual Basic]
Public Property InsertParagraphNumberInFullContext As Boolean
[C#]
public bool InsertParagraphNumberInFullContext {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


InsertParagraphNumberInRelativeContext Property

Aspose.Words

FieldStyleRef.InsertParagraphNumberInRelativeContext Property

Gets or sets whether to insert the paragraph number of the referenced paragraph in relative context.

[Visual Basic]
Public Property InsertParagraphNumberInRelativeContext As Boolean
[C#]
public bool InsertParagraphNumberInRelativeContext {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


InsertRelativePosition Property

Aspose.Words

FieldStyleRef.InsertRelativePosition Property

Gets or sets whether to insert the relative position of the referenced paragraph.

[Visual Basic]
Public Property InsertRelativePosition As Boolean
[C#]
public bool InsertRelativePosition {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


SearchFromBottom Property

Aspose.Words

FieldStyleRef.SearchFromBottom Property

Gets or sets whether to search from the bottom of the current page, rather from the top.

[Visual Basic]
Public Property SearchFromBottom As Boolean
[C#]
public bool SearchFromBottom {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


StyleName Property

Aspose.Words

FieldStyleRef.StyleName Property

Gets or sets the name of the style by which the text to search for is formatted.

[Visual Basic]
Public Property StyleName As String
[C#]
public string StyleName {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


SuppressNonDelimiters Property

Aspose.Words

FieldStyleRef.SuppressNonDelimiters Property

Gets or sets whether to suppress non-delimiter characters.

[Visual Basic]
Public Property SuppressNonDelimiters As Boolean
[C#]
public bool SuppressNonDelimiters {get; set;}

Example

Shows how to use STYLEREF fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on one of the Microsoft Word list templates
Aspose.Words.Lists.List list = doc.Lists.Add(Aspose.Words.Lists.ListTemplate.NumberDefault);

// This generated list will look like "1.a )"
// The space before the bracket is a non-delimiter character that can be suppressed
list.ListLevels[0].NumberFormat = "\x0000.";
list.ListLevels[1].NumberFormat = "\x0001 )";

// Add text and apply paragraph styles that will be referenced by STYLEREF fields
builder.ListFormat.List = list;
builder.ListFormat.ListIndent();
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 1");
builder.ParagraphFormat.Style = doc.Styles["Quote"];
builder.Writeln("Item 2");
builder.ParagraphFormat.Style = doc.Styles["List Paragraph"];
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
builder.ParagraphFormat.Style = doc.Styles["Normal"];

// Place a STYLEREF field in the header and have it display the first "List Paragraph"-styled text in the document
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
FieldStyleRef fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";

// Place a STYLEREF field in the footer and have it display the last text
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "List Paragraph";
fieldStyleRef.SearchFromBottom = true;

builder.MoveToDocumentEnd();

// We can also use STYLEREF fields to reference the list numbers of lists
builder.Write("\nParagraph number: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumber = true;

builder.Write("\nParagraph number, relative context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInRelativeContext = true;

builder.Write("\nParagraph number, full context: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;

builder.Write("\nParagraph number, full context, non-delimiter chars suppressed: ");
fieldStyleRef = (FieldStyleRef)builder.InsertField(FieldType.FieldStyleRef, true);
fieldStyleRef.StyleName = "Quote";
fieldStyleRef.InsertParagraphNumberInFullContext = true;
fieldStyleRef.SuppressNonDelimiters = true;

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.FieldStyleRef.docx");

See Also

FieldStyleRef Class | Aspose.Words.Fields Namespace


FieldSubject Class

Implements the SUBJECT field.

For a list of all members of this type, see FieldSubject Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSubject

[Visual Basic]
Public Class FieldSubject
Inherits Field
[C#]
public class FieldSubject : Field

Remarks

Retrieves, and optionally sets, the document's subject, as recorded in the Subject property of the built-in document properties.

Example

Shows how to use the SUBJECT field.

[C#]

Document doc = new Document();

// Set a value for the document's subject property
doc.BuiltInDocumentProperties.Subject = "My subject";

// We can display this value with a SUBJECT field
DocumentBuilder builder = new DocumentBuilder(doc);
FieldSubject field = (FieldSubject)builder.InsertField(FieldType.FieldSubject, true);
field.Update();

Assert.AreEqual(" SUBJECT ", field.GetFieldCode());
Assert.AreEqual("My subject", field.Result);

// We can also set the field's Text attribute to override the current value of the Subject property
field.Text = "My new subject";
field.Update();

Assert.AreEqual(" SUBJECT  \"My new subject\"", field.GetFieldCode());
Assert.AreEqual("My new subject", field.Result);

// As well as displaying a new value in our field, we also changed the value of the document property
Assert.AreEqual("My new subject", doc.BuiltInDocumentProperties.Subject);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSubject Members | Aspose.Words.Fields Namespace


FieldSubject Members

FieldSubject overview

Public Instance Constructors

FieldSubject Constructor Initializes a new instance of the FieldSubject class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the subject.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSubject Class | Aspose.Words.Fields Namespace


FieldSubject Constructor

Initializes a new instance of the FieldSubject class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSubject();

See Also

FieldSubject Class | Aspose.Words.Fields Namespace


FieldSubject Properties

The properties of the FieldSubject class are listed below. For a complete list of FieldSubject class members, see the FieldSubject Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the subject.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldSubject Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldSubject.Text Property

Gets or sets the text of the subject.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to use the SUBJECT field.

[C#]

Document doc = new Document();

// Set a value for the document's subject property
doc.BuiltInDocumentProperties.Subject = "My subject";

// We can display this value with a SUBJECT field
DocumentBuilder builder = new DocumentBuilder(doc);
FieldSubject field = (FieldSubject)builder.InsertField(FieldType.FieldSubject, true);
field.Update();

Assert.AreEqual(" SUBJECT ", field.GetFieldCode());
Assert.AreEqual("My subject", field.Result);

// We can also set the field's Text attribute to override the current value of the Subject property
field.Text = "My new subject";
field.Update();

Assert.AreEqual(" SUBJECT  \"My new subject\"", field.GetFieldCode());
Assert.AreEqual("My new subject", field.Result);

// As well as displaying a new value in our field, we also changed the value of the document property
Assert.AreEqual("My new subject", doc.BuiltInDocumentProperties.Subject);

See Also

FieldSubject Class | Aspose.Words.Fields Namespace


FieldSymbol Class

Implements a SYMBOL field.

For a list of all members of this type, see FieldSymbol Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldSymbol

[Visual Basic]
Public Class FieldSymbol
Inherits Field
[C#]
public class FieldSymbol : Field

Remarks

Retrieves the character whose code point value is specified in decimal or hexadecimal.

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldSymbol Members | Aspose.Words.Fields Namespace


FieldSymbol Members

FieldSymbol overview

Public Instance Constructors

FieldSymbol Constructor Initializes a new instance of the FieldSymbol class.

Public Instance Properties

CharacterCode | Gets or sets the character's code point value in decimal or hexadecimal.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DontAffectsLineSpacing | Gets or sets whether the character retrieved by the field affects the line spacing of the paragraph.
End (inherited from Field) | Gets the node that represents the field end.
FontName | Gets or sets the name of the font of the character retrieved by the field.
FontSize | Gets or sets the size in points of the font of the character retrieved by the field.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsAnsi | Gets or sets whether the character code is interpreted as the value of an ANSI character.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsShiftJis | Gets or sets whether the character code is interpreted as the value of a SHIFT-JIS character.
IsUnicode | Gets or sets whether the character code is interpreted as the value of a Unicode character.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


FieldSymbol Constructor

Initializes a new instance of the FieldSymbol class.

[Visual Basic]
Public Sub New()
[C#]
public FieldSymbol();

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


FieldSymbol Properties

The properties of the FieldSymbol class are listed below. For a complete list of FieldSymbol class members, see the FieldSymbol Members topic.

Public Instance Properties

CharacterCode | Gets or sets the character's code point value in decimal or hexadecimal.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
DontAffectsLineSpacing | Gets or sets whether the character retrieved by the field affects the line spacing of the paragraph.
End (inherited from Field) | Gets the node that represents the field end.
FontName | Gets or sets the name of the font of the character retrieved by the field.
FontSize | Gets or sets the size in points of the font of the character retrieved by the field.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsAnsi | Gets or sets whether the character code is interpreted as the value of an ANSI character.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsShiftJis | Gets or sets whether the character code is interpreted as the value of a SHIFT-JIS character.
IsUnicode | Gets or sets whether the character code is interpreted as the value of a Unicode character.
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


CharacterCode Property

Aspose.Words

FieldSymbol.CharacterCode Property

Gets or sets the character's code point value in decimal or hexadecimal.

[Visual Basic]
Public Property CharacterCode As String
[C#]
public string CharacterCode {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


DontAffectsLineSpacing Property

Aspose.Words

FieldSymbol.DontAffectsLineSpacing Property

Gets or sets whether the character retrieved by the field affects the line spacing of the paragraph.

[Visual Basic]
Public Property DontAffectsLineSpacing As Boolean
[C#]
public bool DontAffectsLineSpacing {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


FontName Property

Aspose.Words

FieldSymbol.FontName Property

Gets or sets the name of the font of the character retrieved by the field.

[Visual Basic]
Public Property FontName As String
[C#]
public string FontName {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


FontSize Property

Aspose.Words

FieldSymbol.FontSize Property

Gets or sets the size in points of the font of the character retrieved by the field.

[Visual Basic]
Public Property FontSize As String
[C#]
public string FontSize {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


IsAnsi Property

Aspose.Words

FieldSymbol.IsAnsi Property

Gets or sets whether the character code is interpreted as the value of an ANSI character.

[Visual Basic]
Public Property IsAnsi As Boolean
[C#]
public bool IsAnsi {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


IsShiftJis Property

Aspose.Words

FieldSymbol.IsShiftJis Property

Gets or sets whether the character code is interpreted as the value of a SHIFT-JIS character.

[Visual Basic]
Public Property IsShiftJis As Boolean
[C#]
public bool IsShiftJis {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


IsUnicode Property

Aspose.Words

FieldSymbol.IsUnicode Property

Gets or sets whether the character code is interpreted as the value of a Unicode character.

[Visual Basic]
Public Property IsUnicode As Boolean
[C#]
public bool IsUnicode {get; set;}

Example

Shows how to use the SYMBOL field

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a SYMBOL field to display a symbol, designated by a character code
FieldSymbol field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);

// The ANSI character code "U+00A9", or "169" in integer form, is reserved for the copyright symbol
field.CharacterCode = 0x00a9.ToString();
field.IsAnsi = true;

Assert.AreEqual(" SYMBOL  169 \\a", field.GetFieldCode());

builder.Writeln(" Line 1");

// In Unicode, the "221E" code is reserved for ths infinity symbol
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.CharacterCode = 0x221E.ToString();
field.IsUnicode = true;

// Change the appearance of our symbol
// Note that some symbols can change from font to font
// The full list of symbols and their fonts can be looked up in the Windows Character Map
field.FontName = "Calibri";
field.FontSize = "24";

// A tall symbol like the one we placed can also be made to not push down the text on its line
field.DontAffectsLineSpacing = true;

Assert.AreEqual(" SYMBOL  8734 \\u \\f Calibri \\s 24 \\h", field.GetFieldCode());

builder.Writeln("Line 2");

// Display a symbol from the Shift-JIS, also known as the Windows-932 code page
// With a font that supports Shift-JIS, this symbol will display "あ", which is the large Hiragana letter "A"
field = (FieldSymbol)builder.InsertField(FieldType.FieldSymbol, true);
field.FontName = "MS Gothic";
field.CharacterCode = 0x82A0.ToString();
field.IsShiftJis = true;

Assert.AreEqual(" SYMBOL  33440 \\f \"MS Gothic\" \\j", field.GetFieldCode());

builder.Write("Line 3");

doc.Save(ArtifactsDir + "Field.SYMBOL.docx");

See Also

FieldSymbol Class | Aspose.Words.Fields Namespace


FieldTA Class

Implements the TA field.

For a list of all members of this type, see FieldTA Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldTA

[Visual Basic]
Public Class FieldTA
Inherits Field
[C#]
public class FieldTA : Field

Remarks

Defines the text and page number for a table of authorities entry, which is used by a TOA field.

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldTA Members | Aspose.Words.Fields Namespace


FieldTA Members

FieldTA overview

Public Instance Constructors

FieldTA Constructor Initializes a new instance of the FieldTA class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryCategory | Gets or sets the integral entry category, which is a number that corresponds to the order of categories.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsBold | Gets or sets whether to apply bold formatting to the page number for the entry.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsItalic | Gets or sets whether to apply italic formatting to the page number for the entry.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
LongCitation | Gets or sets the long citation for the entry.
PageRangeBookmarkName | Gets or sets the name of the bookmark that marks a range of pages that is inserted as the entry's page number.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
ShortCitation | Gets or sets the short citation for the entry.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldTA Class | Aspose.Words.Fields Namespace


FieldTA Constructor

Initializes a new instance of the FieldTA class.

[Visual Basic]
Public Sub New()
[C#]
public FieldTA();

See Also

FieldTA Class | Aspose.Words.Fields Namespace


FieldTA Properties

The properties of the FieldTA class are listed below. For a complete list of FieldTA class members, see the FieldTA Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryCategory | Gets or sets the integral entry category, which is a number that corresponds to the order of categories.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsBold | Gets or sets whether to apply bold formatting to the page number for the entry.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsItalic | Gets or sets whether to apply italic formatting to the page number for the entry.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
LongCitation | Gets or sets the long citation for the entry.
PageRangeBookmarkName | Gets or sets the name of the bookmark that marks a range of pages that is inserted as the entry's page number.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
ShortCitation | Gets or sets the short citation for the entry.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldTA Class | Aspose.Words.Fields Namespace


EntryCategory Property

Aspose.Words

FieldTA.EntryCategory Property

Gets or sets the integral entry category, which is a number that corresponds to the order of categories.

[Visual Basic]
Public Property EntryCategory As String
[C#]
public string EntryCategory {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldTA Class | Aspose.Words.Fields Namespace


IsBold Property

Aspose.Words

FieldTA.IsBold Property

Gets or sets whether to apply bold formatting to the page number for the entry.

[Visual Basic]
Public Property IsBold As Boolean
[C#]
public bool IsBold {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldTA Class | Aspose.Words.Fields Namespace


IsItalic Property

Aspose.Words

FieldTA.IsItalic Property

Gets or sets whether to apply italic formatting to the page number for the entry.

[Visual Basic]
Public Property IsItalic As Boolean
[C#]
public bool IsItalic {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldTA Class | Aspose.Words.Fields Namespace


LongCitation Property

Aspose.Words

FieldTA.LongCitation Property

Gets or sets the long citation for the entry.

[Visual Basic]
Public Property LongCitation As String
[C#]
public string LongCitation {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldTA Class | Aspose.Words.Fields Namespace


PageRangeBookmarkName Property

Aspose.Words

FieldTA.PageRangeBookmarkName Property

Gets or sets the name of the bookmark that marks a range of pages that is inserted as the entry's page number.

[Visual Basic]
Public Property PageRangeBookmarkName As String
[C#]
public string PageRangeBookmarkName {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldTA Class | Aspose.Words.Fields Namespace


ShortCitation Property

Aspose.Words

FieldTA.ShortCitation Property

Gets or sets the short citation for the entry.

[Visual Basic]
Public Property ShortCitation As String
[C#]
public string ShortCitation {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldTA Class | Aspose.Words.Fields Namespace


FieldTC Class

Implements the TC field.

For a list of all members of this type, see FieldTC Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldTC

[Visual Basic]
NotInheritable Public Class FieldTC
Inherits Field
[C#]
public sealed class FieldTC : Field

Remarks

Defines the text and page number for a table of contents (including a table of figures) entry, which is used by a TOC field.

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldTC Members | Aspose.Words.Fields Namespace


FieldTC Members

FieldTC overview

Public Instance Constructors

FieldTC Constructor Initializes a new instance of the FieldTC class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryLevel | Gets or sets the level of the entry.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
OmitPageNumber | Gets or sets whether page number in TOC should be omitted for this field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the entry.
Type (inherited from Field) | Gets the Microsoft Word field type.
TypeIdentifier | Gets or sets a type identifier for this field (which is typically a letter).

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldTC Class | Aspose.Words.Fields Namespace


FieldTC Constructor

Initializes a new instance of the FieldTC class.

[Visual Basic]
Public Sub New()
[C#]
public FieldTC();

See Also

FieldTC Class | Aspose.Words.Fields Namespace


FieldTC Properties

The properties of the FieldTC class are listed below. For a complete list of FieldTC class members, see the FieldTC Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryLevel | Gets or sets the level of the entry.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
OmitPageNumber | Gets or sets whether page number in TOC should be omitted for this field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the entry.
Type (inherited from Field) | Gets the Microsoft Word field type.
TypeIdentifier | Gets or sets a type identifier for this field (which is typically a letter).

See Also

FieldTC Class | Aspose.Words.Fields Namespace


EntryLevel Property

Aspose.Words

FieldTC.EntryLevel Property

Gets or sets the level of the entry.

[Visual Basic]
Public Property EntryLevel As String
[C#]
public string EntryLevel {get; set;}

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

See Also

FieldTC Class | Aspose.Words.Fields Namespace


OmitPageNumber Property

Aspose.Words

FieldTC.OmitPageNumber Property

Gets or sets whether page number in TOC should be omitted for this field.

[Visual Basic]
NotOverridable Public Property OmitPageNumber As Boolean
[C#]
public bool OmitPageNumber {get; set;}

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

See Also

FieldTC Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldTC.Text Property

Gets or sets the text of the entry.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

See Also

FieldTC Class | Aspose.Words.Fields Namespace


TypeIdentifier Property

Aspose.Words

FieldTC.TypeIdentifier Property

Gets or sets a type identifier for this field (which is typically a letter).

[Visual Basic]
Public Property TypeIdentifier As String
[C#]
public string TypeIdentifier {get; set;}

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

See Also

FieldTC Class | Aspose.Words.Fields Namespace


FieldTemplate Class

Implements the TEMPLATE field.

For a list of all members of this type, see FieldTemplate Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldTemplate

[Visual Basic]
Public Class FieldTemplate
Inherits Field
[C#]
public class FieldTemplate : Field

Remarks

Retrieves the file name of the template used by the current document.

Example

Shows how to display the location of the document's template with a TEMPLATE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldTemplate field = (FieldTemplate)builder.InsertField(FieldType.FieldTemplate, false);
Assert.AreEqual(" TEMPLATE ", field.GetFieldCode());

builder.Writeln();
field = (FieldTemplate)builder.InsertField(FieldType.FieldTemplate, false);
field.IncludeFullPath = true;

Assert.AreEqual(" TEMPLATE  \\p", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TEMPLATE.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldTemplate Members | Aspose.Words.Fields Namespace


FieldTemplate Members

FieldTemplate overview

Public Instance Constructors

FieldTemplate Constructor Initializes a new instance of the FieldTemplate class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IncludeFullPath | Gets or sets whether to include the full file path name.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldTemplate Class | Aspose.Words.Fields Namespace


FieldTemplate Constructor

Initializes a new instance of the FieldTemplate class.

[Visual Basic]
Public Sub New()
[C#]
public FieldTemplate();

See Also

FieldTemplate Class | Aspose.Words.Fields Namespace


FieldTemplate Properties

The properties of the FieldTemplate class are listed below. For a complete list of FieldTemplate class members, see the FieldTemplate Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IncludeFullPath | Gets or sets whether to include the full file path name.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldTemplate Class | Aspose.Words.Fields Namespace


IncludeFullPath Property

Aspose.Words

FieldTemplate.IncludeFullPath Property

Gets or sets whether to include the full file path name.

[Visual Basic]
Public Property IncludeFullPath As Boolean
[C#]
public bool IncludeFullPath {get; set;}

Example

Shows how to display the location of the document's template with a TEMPLATE field.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldTemplate field = (FieldTemplate)builder.InsertField(FieldType.FieldTemplate, false);
Assert.AreEqual(" TEMPLATE ", field.GetFieldCode());

builder.Writeln();
field = (FieldTemplate)builder.InsertField(FieldType.FieldTemplate, false);
field.IncludeFullPath = true;

Assert.AreEqual(" TEMPLATE  \\p", field.GetFieldCode());

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TEMPLATE.docx");

See Also

FieldTemplate Class | Aspose.Words.Fields Namespace


FieldTime Class

Implements the TIME field.

For a list of all members of this type, see FieldTime Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldTime

[Visual Basic]
Public Class FieldTime
Inherits Field
[C#]
public class FieldTime : Field

Remarks

Inserts the current date and time.

Example

Shows how to display the current time using the TIME field.

[C#]

public void FieldTime()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // By default, time is displayed in the "h:mm am/pm" format
    FieldTime field = InsertFieldTime(builder, "");
    Assert.AreEqual(" TIME ", field.GetFieldCode());

    // By using the \@ flag, we can change the appearance of our time
    field = InsertFieldTime(builder, "\\@ HHmm");
    Assert.AreEqual(" TIME \\@ HHmm", field.GetFieldCode());

    // We can even display the date, according to the gregorian calendar
    field = InsertFieldTime(builder, "\\@ \"M/d/yyyy h mm:ss am/pm\"");
    Assert.AreEqual(" TIME \\@ \"M/d/yyyy h mm:ss am/pm\"", field.GetFieldCode());

    doc.Save(ArtifactsDir + "Field.TIME.docx");
}

/// <summary>
/// Use a document builder to insert a TIME field, insert a new paragraph and return the field
/// </summary>
private FieldTime InsertFieldTime(DocumentBuilder builder, string format)
{
    FieldTime field = (FieldTime)builder.InsertField(FieldType.FieldTime, true);
    builder.MoveTo(field.Separator);
    builder.Write(format);
    builder.MoveTo(field.Start.ParentNode);

    builder.InsertParagraph();
    return field;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldTime Members | Aspose.Words.Fields Namespace


FieldTime Members

FieldTime overview

Public Instance Constructors

FieldTime Constructor Initializes a new instance of the FieldTime class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldTime Class | Aspose.Words.Fields Namespace


FieldTime Constructor

Initializes a new instance of the FieldTime class.

[Visual Basic]
Public Sub New()
[C#]
public FieldTime();

See Also

FieldTime Class | Aspose.Words.Fields Namespace


FieldTitle Class

Implements the TITLE field.

For a list of all members of this type, see FieldTitle Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldTitle

[Visual Basic]
Public Class FieldTitle
Inherits Field
[C#]
public class FieldTitle : Field

Remarks

Retrieves, and optionally sets, the document's title, as recorded in the Title property of the built-in document properties.

Example

Shows how to use the TITLE field.

[C#]

Document doc = new Document();

// A TITLE field will display the value assigned to this variable
doc.BuiltInDocumentProperties.Title = "My Title";

// Insert a TITLE field using a document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldTitle field = (FieldTitle)builder.InsertField(FieldType.FieldTitle, false);
field.Update();

Assert.AreEqual(" TITLE ", field.GetFieldCode());
Assert.AreEqual("My Title", field.Result);

builder.Writeln();

// Set the Text attribute to display a different value
field = (FieldTitle)builder.InsertField(FieldType.FieldTitle, false);
field.Text = "My New Title";
field.Update();

Assert.AreEqual(" TITLE  \"My New Title\"", field.GetFieldCode());
Assert.AreEqual("My New Title", field.Result);

// In doing that we've also changed the title in the document properties
Assert.AreEqual("My New Title", doc.BuiltInDocumentProperties.Title);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TITLE.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldTitle Members | Aspose.Words.Fields Namespace


FieldTitle Members

FieldTitle overview

Public Instance Constructors

FieldTitle Constructor Initializes a new instance of the FieldTitle class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the title.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldTitle Class | Aspose.Words.Fields Namespace


FieldTitle Constructor

Initializes a new instance of the FieldTitle class.

[Visual Basic]
Public Sub New()
[C#]
public FieldTitle();

See Also

FieldTitle Class | Aspose.Words.Fields Namespace


FieldTitle Properties

The properties of the FieldTitle class are listed below. For a complete list of FieldTitle class members, see the FieldTitle Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the title.
Type (inherited from Field) | Gets the Microsoft Word field type.

See Also

FieldTitle Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldTitle.Text Property

Gets or sets the text of the title.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to use the TITLE field.

[C#]

Document doc = new Document();

// A TITLE field will display the value assigned to this variable
doc.BuiltInDocumentProperties.Title = "My Title";

// Insert a TITLE field using a document builder
DocumentBuilder builder = new DocumentBuilder(doc);
FieldTitle field = (FieldTitle)builder.InsertField(FieldType.FieldTitle, false);
field.Update();

Assert.AreEqual(" TITLE ", field.GetFieldCode());
Assert.AreEqual("My Title", field.Result);

builder.Writeln();

// Set the Text attribute to display a different value
field = (FieldTitle)builder.InsertField(FieldType.FieldTitle, false);
field.Text = "My New Title";
field.Update();

Assert.AreEqual(" TITLE  \"My New Title\"", field.GetFieldCode());
Assert.AreEqual("My New Title", field.Result);

// In doing that we've also changed the title in the document properties
Assert.AreEqual("My New Title", doc.BuiltInDocumentProperties.Title);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TITLE.docx");

See Also

FieldTitle Class | Aspose.Words.Fields Namespace


FieldToa Class

Implements the TOA field.

For a list of all members of this type, see FieldToa Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldToa

[Visual Basic]
Public Class FieldToa
Inherits Field
[C#]
public class FieldToa : Field

Remarks

Builds a table of authorities (that is, a list of the references in a legal document, such as references to cases, statutes, and rules, along with the numbers of the pages on which the references appear) using the entries specified by TA fields.

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldToa Members | Aspose.Words.Fields Namespace


FieldToa Members

FieldToa overview

Public Instance Constructors

FieldToa Constructor Initializes a new instance of the FieldToa class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark that marks the portion of the document used to build the table.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryCategory | Gets or sets the integral category for entries included in the table.
EntrySeparator | Gets or sets the character sequence that is used to separate a table of authorities entry and its page number.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumberListSeparator | Gets or sets the character sequence that is used to separate two page numbers in a page number list.
PageRangeSeparator | Gets or sets the character sequence that is used to separate the start and end of a page range.
RemoveEntryFormatting | Gets or sets whether to remove the formatting of the entry text in the document from the entry in the table of authorities.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceName | Gets or sets the name of a sequence whose number is included with the page number.
SequenceSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseHeading | Gets or sets whether to include the category heading for the entries in a table of authorities.
UsePassim | Gets or sets whether to replace five or more different page references to the same authority with "passim", which is used to indicate that a word or passage occurs frequently in the work cited.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldToa Class | Aspose.Words.Fields Namespace


FieldToa Constructor

Initializes a new instance of the FieldToa class.

[Visual Basic]
Public Sub New()
[C#]
public FieldToa();

See Also

FieldToa Class | Aspose.Words.Fields Namespace


FieldToa Properties

The properties of the FieldToa class are listed below. For a complete list of FieldToa class members, see the FieldToa Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark that marks the portion of the document used to build the table.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryCategory | Gets or sets the integral category for entries included in the table.
EntrySeparator | Gets or sets the character sequence that is used to separate a table of authorities entry and its page number.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumberListSeparator | Gets or sets the character sequence that is used to separate two page numbers in a page number list.
PageRangeSeparator | Gets or sets the character sequence that is used to separate the start and end of a page range.
RemoveEntryFormatting | Gets or sets whether to remove the formatting of the entry text in the document from the entry in the table of authorities.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceName | Gets or sets the name of a sequence whose number is included with the page number.
SequenceSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseHeading | Gets or sets whether to include the category heading for the entries in a table of authorities.
UsePassim | Gets or sets whether to replace five or more different page references to the same authority with "passim", which is used to indicate that a word or passage occurs frequently in the work cited.

See Also

FieldToa Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldToa.BookmarkName Property

Gets or sets the name of the bookmark that marks the portion of the document used to build the table.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


EntryCategory Property

Aspose.Words

FieldToa.EntryCategory Property

Gets or sets the integral category for entries included in the table.

[Visual Basic]
Public Property EntryCategory As String
[C#]
public string EntryCategory {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


EntrySeparator Property

Aspose.Words

FieldToa.EntrySeparator Property

Gets or sets the character sequence that is used to separate a table of authorities entry and its page number.

[Visual Basic]
Public Property EntrySeparator As String
[C#]
public string EntrySeparator {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


PageNumberListSeparator Property

Aspose.Words

FieldToa.PageNumberListSeparator Property

Gets or sets the character sequence that is used to separate two page numbers in a page number list.

[Visual Basic]
Public Property PageNumberListSeparator As String
[C#]
public string PageNumberListSeparator {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


PageRangeSeparator Property

Aspose.Words

FieldToa.PageRangeSeparator Property

Gets or sets the character sequence that is used to separate the start and end of a page range.

[Visual Basic]
Public Property PageRangeSeparator As String
[C#]
public string PageRangeSeparator {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


RemoveEntryFormatting Property

Aspose.Words

FieldToa.RemoveEntryFormatting Property

Gets or sets whether to remove the formatting of the entry text in the document from the entry in the table of authorities.

[Visual Basic]
Public Property RemoveEntryFormatting As Boolean
[C#]
public bool RemoveEntryFormatting {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


SequenceName Property

Aspose.Words

FieldToa.SequenceName Property

Gets or sets the name of a sequence whose number is included with the page number.

[Visual Basic]
Public Property SequenceName As String
[C#]
public string SequenceName {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


SequenceSeparator Property

Aspose.Words

FieldToa.SequenceSeparator Property

Gets or sets the character sequence that is used to separate sequence numbers and page numbers.

[Visual Basic]
Public Property SequenceSeparator As String
[C#]
public string SequenceSeparator {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


UseHeading Property

Aspose.Words

FieldToa.UseHeading Property

Gets or sets whether to include the category heading for the entries in a table of authorities.

[Visual Basic]
Public Property UseHeading As Boolean
[C#]
public bool UseHeading {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


UsePassim Property

Aspose.Words

FieldToa.UsePassim Property

Gets or sets whether to replace five or more different page references to the same authority with "passim", which is used to indicate that a word or passage occurs frequently in the work cited.

[Visual Basic]
Public Property UsePassim As Boolean
[C#]
public bool UsePassim {get; set;}

Example

Shows how to build and customize a table of authorities using TOA and TA fields.

[C#]

public void FieldTOA()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert a TOA field, which will list all the TA entries in the document,
    // displaying long citations and page numbers for each
    FieldToa fieldToa = (FieldToa)builder.InsertField(FieldType.FieldTOA, false);

    // Set the entry category for our table
    // For a TA field to be included in this table, it will have to have a matching entry category
    fieldToa.EntryCategory = "1";

    // Moreover, the Table of Authorities category at index 1 is "Cases",
    // which will show up as the title of our table if we set this variable to true
    fieldToa.UseHeading = true;

    // We can further filter TA fields by designating a named bookmark that they have to be inside of
    fieldToa.BookmarkName = "MyBookmark";

    // By default, a dotted line page-wide tab appears between the TA field's citation and its page number
    // We can replace it with any text we put in this attribute, even preserving the tab if we use tab character
    fieldToa.EntrySeparator = " \t p.";

    // If we have multiple TA entries that share the same long citation,
    // all their respective page numbers will show up on one row,
    // and the page numbers separated by a string specified here
    fieldToa.PageNumberListSeparator = " & p. ";

    // To reduce clutter, we can set this to true to get our table to display the word "passim"
    // if there would be 5 or more page numbers in one row
    fieldToa.UsePassim = true;

    // One TA field can refer to a range of pages, and the sequence specified here will be between the start and end page numbers
    fieldToa.PageRangeSeparator = " to ";

    // The format from the TA fields will carry over into our table, and we can stop it from doing so by setting this variable
    fieldToa.RemoveEntryFormatting = true;
    builder.Font.Color = Color.Green;
    builder.Font.Name = "Arial Black";

    Assert.AreEqual(" TOA  \\c 1 \\h \\b MyBookmark \\e \" \t p.\" \\l \" & p. \" \\p \\g \" to \" \\f", fieldToa.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // We will insert a TA entry using a document builder
    // This entry is outside the bookmark specified by our table, so it won't be displayed
    FieldTA fieldTA = InsertToaEntry(builder, "1", "Source 1");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 1\"", fieldTA.GetFieldCode());

    // This entry is inside the bookmark,
    // but the entry category doesn't match that of the table, so it will also be omitted
    builder.StartBookmark("MyBookmark");
    fieldTA = InsertToaEntry(builder, "2", "Source 2");

    // This entry will appear in the table
    fieldTA = InsertToaEntry(builder, "1", "Source 3");

    // Short citations aren't displayed by a TOA table,
    // but they can be used as a shorthand to refer to bulky source names that multiple TA fields reference
    fieldTA.ShortCitation = "S.3";

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\s S.3", fieldTA.GetFieldCode());

    // The page number can be made to appear bold and/or italic
    // This will still be displayed if our table is set to ignore formatting
    fieldTA = InsertToaEntry(builder, "1", "Source 2");
    fieldTA.IsBold = true;
    fieldTA.IsItalic = true;

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 2\" \\b \\i", fieldTA.GetFieldCode());

    // We can get TA fields to refer to a range of pages that a bookmark spans across instead of the page that they are on
    // Note that this entry refers to the same source as the one above, so they will share one row in our table,
    // displaying the page number of the entry above as well as the page range of this entry,
    // with the table's page list and page number range separators between page numbers
    fieldTA = InsertToaEntry(builder, "1", "Source 3");
    fieldTA.PageRangeBookmarkName = "MyMultiPageBookmark";

    builder.StartBookmark("MyMultiPageBookmark");
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.InsertBreak(BreakType.PageBreak);
    builder.EndBookmark("MyMultiPageBookmark");

    Assert.AreEqual(" TA  \\c 1 \\l \"Source 3\" \\r MyMultiPageBookmark", fieldTA.GetFieldCode());

    // Having 5 or more TA entries with the same source invokes the "passim" feature of our table, if we enabled it
    for (int i = 0; i < 5; i++)
    {
        InsertToaEntry(builder, "1", "Source 4");
    }

    builder.EndBookmark("MyBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOA.TA.docx");
}

/// <summary>
/// Get a builder to insert a TA field, specifying its long citation and category,
/// then insert a page break and return the field we created
/// </summary>
private FieldTA InsertToaEntry(DocumentBuilder builder, string entryCategory, string longCitation)
{
    FieldTA field = (FieldTA)builder.InsertField(FieldType.FieldTOAEntry, false);
    field.EntryCategory = entryCategory;
    field.LongCitation = longCitation;

    builder.InsertBreak(BreakType.PageBreak);

    return field;
}

See Also

FieldToa Class | Aspose.Words.Fields Namespace


FieldToc Class

Implements the TOC field.

For a list of all members of this type, see FieldToc Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldToc

[Visual Basic]
Public Class FieldToc
Inherits Field
[C#]
public class FieldToc : Field

Remarks

Builds a table of contents (which can also be a table of figures) using the entries specified by TC fields, their heading levels, and specified styles, and inserts that table at this place in the document.

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldToc Members | Aspose.Words.Fields Namespace


FieldToc Members

FieldToc overview

Public Instance Constructors

FieldToc Constructor Initializes a new instance of the FieldToc class.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark that marks the portion of the document used to build the table.
CaptionlessTableOfFiguresLabel | Gets or sets the name of the sequence identifier used when building a table of figures that does not include caption's label and number.
CustomStyles | Gets or sets a list of styles other than the built-in heading styles to include in the table of contents.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryIdentifier | Gets or sets a string that should match type identifiers of TC fields being included.
EntryLevelRange | Gets or sets a range of levels of the table of contents entries to be included.
EntrySeparator | Gets or sets a sequence of characters that separate an entry and its page number.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HeadingLevelRange | Gets or sets a range of heading levels to include.
HideInWebLayout | Gets or sets whether to hide tab leader and page numbers in Web layout view.
InsertHyperlinks | Gets or sets whether to make the table of contents entries hyperlinks.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsPageNumberOmittingLevelRangeSpecified |
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumberOmittingLevelRange | Gets or sets a range of levels of the table of contents entries from which to omits page numbers.
PrefixedSequenceIdentifier | Gets or sets the identifier of a sequence for which a prefix should be added to the entry's page number.
PreserveLineBreaks | Gets or sets whether to preserve newline characters within table entries.
PreserveTabs | Gets or sets whether to preserve tab entries within table entries.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Start (inherited from Field) | Gets the node that represents the start of the field.
TableOfFiguresLabel | Gets or sets the name of the sequence identifier used when building a table of figures.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseParagraphOutlineLevel | Gets or sets whether to use the applied paragraph outline level.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.
UpdatePageNumbers | Updates the page numbers for items in this table of contents.

See Also

FieldToc Class | Aspose.Words.Fields Namespace


FieldToc Constructor

Initializes a new instance of the FieldToc class.

[Visual Basic]
Public Sub New()
[C#]
public FieldToc();

See Also

FieldToc Class | Aspose.Words.Fields Namespace


FieldToc Properties

The properties of the FieldToc class are listed below. For a complete list of FieldToc class members, see the FieldToc Members topic.

Public Instance Properties

BookmarkName | Gets or sets the name of the bookmark that marks the portion of the document used to build the table.
CaptionlessTableOfFiguresLabel | Gets or sets the name of the sequence identifier used when building a table of figures that does not include caption's label and number.
CustomStyles | Gets or sets a list of styles other than the built-in heading styles to include in the table of contents.
DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryIdentifier | Gets or sets a string that should match type identifiers of TC fields being included.
EntryLevelRange | Gets or sets a range of levels of the table of contents entries to be included.
EntrySeparator | Gets or sets a sequence of characters that separate an entry and its page number.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HeadingLevelRange | Gets or sets a range of heading levels to include.
HideInWebLayout | Gets or sets whether to hide tab leader and page numbers in Web layout view.
InsertHyperlinks | Gets or sets whether to make the table of contents entries hyperlinks.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
IsPageNumberOmittingLevelRangeSpecified |
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumberOmittingLevelRange | Gets or sets a range of levels of the table of contents entries from which to omits page numbers.
PrefixedSequenceIdentifier | Gets or sets the identifier of a sequence for which a prefix should be added to the entry's page number.
PreserveLineBreaks | Gets or sets whether to preserve newline characters within table entries.
PreserveTabs | Gets or sets whether to preserve tab entries within table entries.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
SequenceSeparator | Gets or sets the character sequence that is used to separate sequence numbers and page numbers.
Start (inherited from Field) | Gets the node that represents the start of the field.
TableOfFiguresLabel | Gets or sets the name of the sequence identifier used when building a table of figures.
Type (inherited from Field) | Gets the Microsoft Word field type.
UseParagraphOutlineLevel | Gets or sets whether to use the applied paragraph outline level.

See Also

FieldToc Class | Aspose.Words.Fields Namespace


BookmarkName Property

Aspose.Words

FieldToc.BookmarkName Property

Gets or sets the name of the bookmark that marks the portion of the document used to build the table.

[Visual Basic]
Public Property BookmarkName As String
[C#]
public string BookmarkName {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


CaptionlessTableOfFiguresLabel Property

Aspose.Words

FieldToc.CaptionlessTableOfFiguresLabel Property

Gets or sets the name of the sequence identifier used when building a table of figures that does not include caption's label and number.

[Visual Basic]
Public Property CaptionlessTableOfFiguresLabel As String
[C#]
public string CaptionlessTableOfFiguresLabel {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


CustomStyles Property

Aspose.Words

FieldToc.CustomStyles Property

Gets or sets a list of styles other than the built-in heading styles to include in the table of contents.

[Visual Basic]
Public Property CustomStyles As String
[C#]
public string CustomStyles {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


EntryIdentifier Property

Aspose.Words

FieldToc.EntryIdentifier Property

Gets or sets a string that should match type identifiers of TC fields being included.

[Visual Basic]
Public Property EntryIdentifier As String
[C#]
public string EntryIdentifier {get; set;}

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


EntryLevelRange Property

Aspose.Words

FieldToc.EntryLevelRange Property

Gets or sets a range of levels of the table of contents entries to be included.

[Visual Basic]
Public Property EntryLevelRange As String
[C#]
public string EntryLevelRange {get; set;}

Example

Shows how to insert a TOC field and filter which TC fields end up as entries.

[C#]

public void FieldTocEntryIdentifier()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.EntryIdentifier = "A";
    fieldToc.EntryLevelRange = "1-3";

    builder.InsertBreak(BreakType.PageBreak);

    // These two entries will appear in the table
    InsertTocEntry(builder, "TC field 1", "A", "1");
    InsertTocEntry(builder, "TC field 2", "A", "2");

    // These two entries will be omitted because of an incorrect type identifier
    InsertTocEntry(builder, "TC field 3", "B", "1");

    // ...and an out-of-range entry level
    InsertTocEntry(builder, "TC field 4", "A", "5");

    Assert.AreEqual(" TOC  \\f A \\l 1-3", fieldToc.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.TC.docx");
}

/// <summary>
/// Insert a table of contents entry via a document builder
/// </summary>
public void InsertTocEntry(DocumentBuilder builder, string text, string typeIdentifier, string entryLevel)
{
    FieldTC fieldTc = (FieldTC)builder.InsertField(FieldType.FieldTOCEntry, true);
    fieldTc.OmitPageNumber = true;
    fieldTc.Text = text;
    fieldTc.TypeIdentifier = typeIdentifier;
    fieldTc.EntryLevel = entryLevel;
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


EntrySeparator Property

Aspose.Words

FieldToc.EntrySeparator Property

Gets or sets a sequence of characters that separate an entry and its page number.

[Visual Basic]
Public Property EntrySeparator As String
[C#]
public string EntrySeparator {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


HeadingLevelRange Property

Aspose.Words

FieldToc.HeadingLevelRange Property

Gets or sets a range of heading levels to include.

[Visual Basic]
Public Property HeadingLevelRange As String
[C#]
public string HeadingLevelRange {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


HideInWebLayout Property

Aspose.Words

FieldToc.HideInWebLayout Property

Gets or sets whether to hide tab leader and page numbers in Web layout view.

[Visual Basic]
Public Property HideInWebLayout As Boolean
[C#]
public bool HideInWebLayout {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


InsertHyperlinks Property

Aspose.Words

FieldToc.InsertHyperlinks Property

Gets or sets whether to make the table of contents entries hyperlinks.

[Visual Basic]
Public Property InsertHyperlinks As Boolean
[C#]
public bool InsertHyperlinks {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


IsPageNumberOmittingLevelRangeSpecified Property

Aspose.Words

FieldToc.IsPageNumberOmittingLevelRangeSpecified Property

[Visual Basic]
Public ReadOnly Property IsPageNumberOmittingLevelRangeSpecified As Boolean
[C#]
public bool IsPageNumberOmittingLevelRangeSpecified {get;}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


PageNumberOmittingLevelRange Property

Aspose.Words

FieldToc.PageNumberOmittingLevelRange Property

Gets or sets a range of levels of the table of contents entries from which to omits page numbers.

[Visual Basic]
Public Property PageNumberOmittingLevelRange As String
[C#]
public string PageNumberOmittingLevelRange {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


PrefixedSequenceIdentifier Property

Aspose.Words

FieldToc.PrefixedSequenceIdentifier Property

Gets or sets the identifier of a sequence for which a prefix should be added to the entry's page number.

[Visual Basic]
Public Property PrefixedSequenceIdentifier As String
[C#]
public string PrefixedSequenceIdentifier {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


PreserveLineBreaks Property

Aspose.Words

FieldToc.PreserveLineBreaks Property

Gets or sets whether to preserve newline characters within table entries.

[Visual Basic]
Public Property PreserveLineBreaks As Boolean
[C#]
public bool PreserveLineBreaks {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


PreserveTabs Property

Aspose.Words

FieldToc.PreserveTabs Property

Gets or sets whether to preserve tab entries within table entries.

[Visual Basic]
Public Property PreserveTabs As Boolean
[C#]
public bool PreserveTabs {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


SequenceSeparator Property

Aspose.Words

FieldToc.SequenceSeparator Property

Gets or sets the character sequence that is used to separate sequence numbers and page numbers.

[Visual Basic]
Public Property SequenceSeparator As String
[C#]
public string SequenceSeparator {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


TableOfFiguresLabel Property

Aspose.Words

FieldToc.TableOfFiguresLabel Property

Gets or sets the name of the sequence identifier used when building a table of figures.

[Visual Basic]
Public Property TableOfFiguresLabel As String
[C#]
public string TableOfFiguresLabel {get; set;}

Example

Insert a TOC field and build the table with SEQ fields.

[C#]

public void TocSeqPrefix()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.PrefixedSequenceIdentifier = "PrefixSequence";
    fieldToc.SequenceSeparator = ">";

    Assert.AreEqual(" TOC  \\c MySequence \\s PrefixSequence \\d >", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Add two SEQ fields in one paragraph, setting the TOC's sequence and prefix sequence as their sequence identifiers
    FieldSeq fieldSeq = InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    Assert.AreEqual(" SEQ  PrefixSequence", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, ", MySequence ", "\n", "MySequence");
    Assert.AreEqual(" SEQ  MySequence", fieldSeq.GetFieldCode());

    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    InsertSeqField(builder, ", MySequence ", "\n", "MySequence");

    // If the sqeuence identifier doesn't match that of the TOC, the entry won't be included
    InsertSeqField(builder, "PrefixSequence ", "", "PrefixSequence");
    fieldSeq = InsertSeqField(builder, ", MySequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    Assert.AreEqual(" SEQ  OtherSequence", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Prefix.docx");
}

[Ignore("WORDSNET-18083")]
public void TocSeqNumbering()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Filter by sequence identifier and a prefix sequence identifier, and change sequence separator
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";

    Assert.AreEqual(" TOC  \\c MySequence", fieldToc.GetFieldCode());

    builder.InsertBreak(BreakType.PageBreak);

    // Set the current number of the sequence to 100
    FieldSeq fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetNumber = "100";
    Assert.AreEqual(" SEQ  MySequence \\r 100", fieldSeq.GetFieldCode());

    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");

    // Insert a heading
    builder.InsertBreak(BreakType.ParagraphBreak);
    builder.ParagraphFormat.Style = doc.Styles["Heading 1"];
    builder.Writeln("My heading");
    builder.ParagraphFormat.Style = doc.Styles["Normal"];

    // Reset sequence when we encounter a heading, resetting the sequence back to 1
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.ResetHeadingLevel = "1";
    Assert.AreEqual(" SEQ  MySequence \\s 1", fieldSeq.GetFieldCode());

    // Move to the next number
    fieldSeq = InsertSeqField(builder, "MySequence ", "\n", "MySequence");
    fieldSeq.InsertNextNumber = true;
    Assert.AreEqual(" SEQ  MySequence \\n", fieldSeq.GetFieldCode());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.ResetNumbering.docx");
}

[Ignore("WORDSNET-18084")]
public void TocSeqBookmark()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // This TOC takes in all SEQ fields with "MySequence" inside "TOCBookmark"
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);
    fieldToc.TableOfFiguresLabel = "MySequence";
    fieldToc.BookmarkName = "TOCBookmark";
    builder.InsertBreak(BreakType.PageBreak);

    Assert.AreEqual(" TOC  \\c MySequence \\b TOCBookmark", fieldToc.GetFieldCode());

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text won't show up in the TOC because it is outside of the bookmark.");

    builder.StartBookmark("TOCBookmark");

    InsertSeqField(builder, "MySequence ", "", "MySequence");
    builder.Writeln(" This text will show up in the TOC next to the entry for the above caption.");

    InsertSeqField(builder, "OtherSequence ", "", "OtherSequence");
    builder.Writeln(" This text, from a different sequence, won't be included in the same TOC as the one above.");

    // The contents of the bookmark we reference here will not appear at the SEQ field, but will appear in the corresponding TOC entry
    FieldSeq fieldSeq = InsertSeqField(builder, " MySequence ", "\n", "MySequence");
    fieldSeq.BookmarkName = "SEQBookmark";
    Assert.AreEqual(" SEQ  MySequence SEQBookmark", fieldSeq.GetFieldCode());

    // Add bookmark to reference
    builder.InsertBreak(BreakType.PageBreak);
    builder.StartBookmark("SEQBookmark");
    InsertSeqField(builder, " MySequence ", "", "MySequence");
    builder.Writeln(" Text inside SEQBookmark.");
    builder.EndBookmark("SEQBookmark");

    builder.EndBookmark("TOCBookmark");

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.TOC.SEQ.Bookmark.docx");
}

/// <summary>
/// Insert a sequence field with preceding text and a specified sequence identifier
/// </summary>
public FieldSeq InsertSeqField(DocumentBuilder builder, string textBefore, string textAfter, string sequenceIdentifier)
{
    builder.Write(textBefore);
    FieldSeq fieldSeq = (FieldSeq)builder.InsertField(FieldType.FieldSequence, true);
    fieldSeq.SequenceIdentifier = sequenceIdentifier;
    builder.Write(textAfter);

    return fieldSeq;
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


UseParagraphOutlineLevel Property

Aspose.Words

FieldToc.UseParagraphOutlineLevel Property

Gets or sets whether to use the applied paragraph outline level.

[Visual Basic]
Public Property UseParagraphOutlineLevel As Boolean
[C#]
public bool UseParagraphOutlineLevel {get; set;}

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


FieldToc Methods

The methods of the FieldToc class are listed below. For a complete list of FieldToc class members, see the FieldToc Members topic.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.
UpdatePageNumbers | Updates the page numbers for items in this table of contents.

See Also

FieldToc Class | Aspose.Words.Fields Namespace


FieldToc.UpdatePageNumbers Method

Updates the page numbers for items in this table of contents.

[Visual Basic]
Public Function UpdatePageNumbers() As Boolean
[C#]
public bool UpdatePageNumbers();

Return Value

True if the operation is successful. If any of the related TOC bookmarks was removed, false will be returned.

Example

Shows how to insert a TOC and populate it with entries based on heading styles.

[C#]

public void FieldToc()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // The table of contents we will insert will accept entries that are only within the scope of this bookmark
    builder.StartBookmark("MyBookmark");

    // Insert a list num field using a document builder
    FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true);

    // Limit possible TOC entries to only those within the bookmark we name here
    fieldToc.BookmarkName = "MyBookmark";

    // Normally paragraphs with a "Heading n" style will be the only ones that will be added to a TOC as entries
    // We can set this attribute to include other styles, such as "Quote" and "Intense Quote" in this case
    fieldToc.CustomStyles = "Quote; 6; Intense Quote; 7";

    // Styles are normally separated by a comma (",") but we can use this property to set a custom delimiter
    doc.FieldOptions.CustomTocStyleSeparator = ";";

    // Filter out any headings that are outside this range
    fieldToc.HeadingLevelRange = "1-3";

    // Headings in this range won't display their page number in their TOC entry
    fieldToc.PageNumberOmittingLevelRange = "2-5";

    fieldToc.EntrySeparator = "-";
    fieldToc.InsertHyperlinks = true;
    fieldToc.HideInWebLayout = false;
    fieldToc.PreserveLineBreaks = true;
    fieldToc.PreserveTabs = true;
    fieldToc.UseParagraphOutlineLevel = false;

    InsertHeading(builder, "First entry", "Heading 1");
    builder.Writeln("Paragraph text.");
    InsertHeading(builder, "Second entry", "Heading 1");
    InsertHeading(builder, "Third entry", "Quote");
    InsertHeading(builder, "Fourth entry", "Intense Quote");

    // These two headings will have the page numbers omitted because they are within the "2-5" range
    InsertHeading(builder, "Fifth entry", "Heading 2");
    InsertHeading(builder, "Sixth entry", "Heading 3");

    // This entry will be omitted because "Heading 4" is outside of the "1-3" range we set earlier
    InsertHeading(builder, "Seventh entry", "Heading 4");

    builder.EndBookmark("MyBookmark");
    builder.Writeln("Paragraph text.");

    // This entry will be omitted because it is outside the bookmark specified by the TOC
    InsertHeading(builder, "Eighth entry", "Heading 1");

    Assert.AreEqual(" TOC  \\b MyBookmark \\t \"Quote; 6; Intense Quote; 7\" \\o 1-3 \\n 2-5 \\p - \\h \\x \\w", fieldToc.GetFieldCode());

    fieldToc.UpdatePageNumbers();
    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FieldTOC.docx");
}

/// <summary>
/// Start a new page and insert a paragraph of a specified style
/// </summary>
public void InsertHeading(DocumentBuilder builder, string captionText, string styleName)
{
    builder.InsertBreak(BreakType.PageBreak);
    string originalStyle = builder.ParagraphFormat.StyleName;
    builder.ParagraphFormat.Style = builder.Document.Styles[styleName];
    builder.Writeln(captionText);
    builder.ParagraphFormat.Style = builder.Document.Styles[originalStyle];
}

See Also

FieldToc Class | Aspose.Words.Fields Namespace


FieldType Enumeration

Specifies Microsoft Word field types.

[Visual Basic]
Public Enum FieldType
[C#]
public enum FieldType

Example

Demonstrates how to retrieve the field class from an existing FieldStart node in the document.

[C#]

Document doc = new Document(MyDir + "Document.TableOfContents.doc");

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
Assert.AreEqual(FieldType.FieldTOC, fieldStart.FieldType);
Assert.AreEqual(true, fieldStart.IsDirty);
Assert.AreEqual(false, fieldStart.IsLocked);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Assert.AreEqual(false, field.IsLocked);
Assert.AreEqual(" TOC \\o \"1-3\" \\h \\z \\u ", field.GetFieldCode());

// This updates only this field in the document.
field.Update();
Inserts a field into a document using DocumentBuilder and FieldCode.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a simple Date field into the document.
// When we insert a field through the DocumentBuilder class we can get the
// special Field object which contains information about the field.
Field dateField = builder.InsertField(@"DATE \* MERGEFORMAT");

// Update this particular field in the document so we can get the FieldResult.
dateField.Update();

// Display some information from this field.
// The field result is where the last evaluated value is stored. This is what is displayed in the document
// When field codes are not showing.
Console.WriteLine("FieldResult: {0}", dateField.Result);

// Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9.
Console.WriteLine("FieldCode: {0}", dateField.GetFieldCode());

// The field type defines what type of field in the Document this is. In this case the type is "FieldDate"
Console.WriteLine("FieldType: {0}", dateField.Type);

// Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object.
dateField.Remove();

Members

Member Name | Description | Value
FieldNone | Field type is not specified or unknown. | 0
FieldCannotParse | Specifies that the field was unable to be parsed. | 1
FieldAddin | Specifies the ADDIN field. | 81
FieldAddressBlock | Specifies the ADDRESSBLOCK field. | 93
FieldAdvance | Specifies the ADVANCE field. | 84
FieldAsk | Specifies the ASK field. | 38
FieldAuthor | Specifies the AUTHOR field. | 17
FieldAutoNum | Specifies the AUTONUM field. | 54
FieldAutoNumLegal | Specifies the AUTONUMLGL field. | 53
FieldAutoNumOutline | Specifies the AUTONUMOUT field. | 52
FieldAutoText | Specifies the AUTOTEXT field. | 79
FieldAutoTextList | Specifies the AUTOTEXTLIST field. | 89
FieldBarcode | Specifies the BARCODE field. | 63
FieldBibliography | Specifies the BIBLIOGRAPHY field. | 100500
FieldBidiOutline | Specifies the BIDIOUTLINE field. | 92
FieldCitation | Specifies the CITATION field. | 1980
FieldComments | Specifies the COMMENTS field. | 19
FieldCompare | Specifies the COMPARE field. | 80
FieldCreateDate | Specifies the CREATEDATE field. | 21
FieldData | Specifies the DATA field. | 40
FieldDatabase | Specifies the DATABASE field. | 78
FieldDate | Specifies the DATE field. | 31
FieldDDE | Specifies the DDE field. | 45
FieldDisplayBarcode | Specifies the DISPLAYBARCODE field. | 6301
FieldMergeBarcode | Specifies the MERGEBARCODE field. | 6302
FieldDDEAuto | Specifies the DDEAUTO field. | 46
FieldDocProperty | Specifies the DOCPROPERTY field. | 85
FieldDocVariable | Specifies the DOCVARIABLE field. | 64
FieldEditTime | Specifies the EDITTIME field. | 25
FieldEmbed | Specifies the EMBED field. | 58
FieldEquation | Specifies the EQ field. | 49
FieldFileName | Specifies the FILENAME field. | 29
FieldFileSize | Specifies the FILESIZE field. | 69
FieldFillIn | Specifies the FILLIN field. | 39
FieldFootnoteRef | Specifies the FOOTNOTEREF field. | 5
FieldFormCheckBox | Specifies the FORMCHECKBOX field. | 71
FieldFormDropDown | Specifies the FORMDROPDOWN field. | 83
FieldFormTextInput | Specifies the FORMTEXT field. | 70
FieldFormula | Specifies the = (formula) field. | 34
FieldGreetingLine | Specifies the GREETINGLINE field. | 94
FieldGlossary | Specifies the GLOSSARY field. | 47
FieldGoToButton | Specifies the GOTOBUTTON field. | 50
FieldHtmlActiveX | Specifies the field that represents an HTML control. | 91
FieldHyperlink | Specifies the HYPERLINK field. | 88
FieldIf | Specifies the IF field. | 7
FieldInclude | Specifies the INCLUDE field. | 36
FieldIncludePicture | Specifies the INCLUDEPICTURE field. | 67
FieldIncludeText | Specifies the INCLUDETEXT field. | 68
FieldIndex | Specifies the INDEX field. | 8
FieldIndexEntry | Specifies the XE field. | 4
FieldInfo | Specifies the INFO field. | 14
FieldImport | Specifies the IMPORT field. | 55
FieldKeyword | Specifies the KEYWORDS field. | 18
FieldLastSavedBy | Specifies the LASTSAVEDBY field. | 20
FieldLink | Specifies the LINK field. | 56
FieldListNum | Specifies the LISTNUM field. | 90
FieldMacroButton | Specifies the MACROBUTTON field. | 51
FieldMergeField | Specifies the MERGEFIELD field. | 59
FieldMergeRec | Specifies the MERGEREC field. | 44
FieldMergeSeq | Specifies the MERGESEQ field. | 75
FieldNext | Specifies the NEXT field. | 41
FieldNextIf | Specifies the NEXTIF field. | 42
FieldNoteRef | Specifies the NOTEREF field. | 72
FieldNumChars | Specifies the NUMCHARS field. | 28
FieldNumPages | Specifies the NUMPAGES field. | 26
FieldNumWords | Specifies the NUMWORDS field. | 27
FieldOcx | Specifies the OCX field. Normally, Aspose.Words will represent an ActiveX control as a Shape object, but for some documents, where a control does not have data and/or seems to be invalid, it will be represented as a field. | 87
FieldPage | Specifies the PAGE field. | 33
FieldPageRef | Specifies the PAGEREF field. | 37
FieldPrint | Specifies the PRINT field. | 48
FieldPrintDate | Specifies the PRINTDATE field. | 23
FieldPrivate | Specifies the PRIVATE field. | 77
FieldQuote | Specifies the QUOTE field. | 35
FieldRef | Specifies the REF field. | 3
FieldRefNoKeyword | Specifies that the field represents a REF field where the keyword has been omitted. | 2
FieldRefDoc | Specifies the RD field. | 11
FieldRevisionNum | Specifies the REVNUM field. | 24
FieldSaveDate | Specifies the SAVEDATE field. | 22
FieldSection | Specifies the SECTION field. | 65
FieldSectionPages | Specifies the SECTIONPAGES field. | 66
FieldSequence | Specifies the SEQ field. | 12
FieldSet | Specifies the SET field. | 6
FieldShape | Specifies the SHAPE field. | 95
FieldSkipIf | Specifies the SKIPIF field. | 43
FieldStyleRef | Specifies the STYLEREF field. | 10
FieldSubject | Specifies the SUBJECT field. | 16
FieldSymbol | Specifies the SYMBOL field. | 57
FieldTemplate | Specifies the TEMPLATE field. | 30
FieldTime | Specifies the TIME field. | 32
FieldTitle | Specifies the TITLE field. | 15
FieldTOA | Specifies the TOA field. | 73
FieldTOAEntry | Specifies the TA field. | 74
FieldTOC | Specifies the TOC field. | 13
FieldTOCEntry | Specifies the TC field. | 9
FieldUserAddress | Specifies the USERADDRESS field. | 62
FieldUserInitials | Specifies the USERINITIALS field. | 61
FieldUserName | Specifies the USERNAME field. | 60

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fields Namespace


FieldUnknown Class

Implements an unknown or unrecognized field.

For a list of all members of this type, see FieldUnknown Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldUnknown

[Visual Basic]
Public Class FieldUnknown
Inherits Field
[C#]
public class FieldUnknown : Field

Example

Shows how to work with 'FieldNone' field in a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertField(FieldType.FieldNone, false);

MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Docx);

FieldUnknown fieldUnknown = (FieldUnknown)doc.Range.Fields.FirstOrDefault(p => p.Type == FieldType.FieldNone);
if (fieldUnknown != null)
    Assert.AreEqual(FieldType.FieldNone, fieldUnknown.Type);
else
    Assert.Fail("FieldUnknown doesn't exist");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldUnknown Members | Aspose.Words.Fields Namespace


FieldUnknown Members

FieldUnknown overview

Public Instance Constructors

FieldUnknown Constructor Initializes a new instance of the FieldUnknown class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldUnknown Class | Aspose.Words.Fields Namespace


FieldUnknown Constructor

Initializes a new instance of the FieldUnknown class.

[Visual Basic]
Public Sub New()
[C#]
public FieldUnknown();

See Also

FieldUnknown Class | Aspose.Words.Fields Namespace


FieldUpdateCultureSource Enumeration

Indicates what culture to use during field update.

[Visual Basic]
Public Enum FieldUpdateCultureSource
[C#]
public enum FieldUpdateCultureSource

Example

Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.

[C#]

// Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
doc.MailMerge.Execute(new[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });

Members

Member Name | Description | Value
CurrentThread | The culture of the current execution thread is used to update fields. | 0
FieldCode | The culture specified in the field formatting properties via language setting is used. | 1

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fields Namespace


FieldUserAddress Class

Implements the USERADDRESS field.

For a list of all members of this type, see FieldUserAddress Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldUserAddress

[Visual Basic]
Public Class FieldUserAddress
Inherits Field
[C#]
public class FieldUserAddress : Field

Remarks

Retrieves the current user's postal address.

Example

Shows how to use the USERADDRESS field.

[C#]

Document doc = new Document();

// Create a user information object and set it as the data source for our field
UserInformation userInformation = new UserInformation();
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Display the current user's address with a USERADDRESS field
DocumentBuilder builder = new DocumentBuilder(doc);
FieldUserAddress fieldUserAddress = (FieldUserAddress)builder.InsertField(FieldType.FieldUserAddress, true);
Assert.AreEqual(userInformation.Address, fieldUserAddress.Result);

Assert.AreEqual(" USERADDRESS ", fieldUserAddress.GetFieldCode());
Assert.AreEqual("123 Main Street", fieldUserAddress.Result);

// We can set this attribute to get our field to display a different value
fieldUserAddress.UserAddress = "456 North Road";
fieldUserAddress.Update();

Assert.AreEqual(" USERADDRESS  \"456 North Road\"", fieldUserAddress.GetFieldCode());
Assert.AreEqual("456 North Road", fieldUserAddress.Result);

// This does not change the value in the user information object
Assert.AreEqual("123 Main Street", doc.FieldOptions.CurrentUser.Address);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldUserAddress Members | Aspose.Words.Fields Namespace


FieldUserAddress Members

FieldUserAddress overview

Public Instance Constructors

FieldUserAddress Constructor Initializes a new instance of the FieldUserAddress class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UserAddress | Gets or sets the current user's postal address.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldUserAddress Class | Aspose.Words.Fields Namespace


FieldUserAddress Constructor

Initializes a new instance of the FieldUserAddress class.

[Visual Basic]
Public Sub New()
[C#]
public FieldUserAddress();

See Also

FieldUserAddress Class | Aspose.Words.Fields Namespace


FieldUserAddress Properties

The properties of the FieldUserAddress class are listed below. For a complete list of FieldUserAddress class members, see the FieldUserAddress Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UserAddress | Gets or sets the current user's postal address.

See Also

FieldUserAddress Class | Aspose.Words.Fields Namespace


UserAddress Property

Aspose.Words

FieldUserAddress.UserAddress Property

Gets or sets the current user's postal address.

[Visual Basic]
Public Property UserAddress As String
[C#]
public string UserAddress {get; set;}

Example

Shows how to use the USERADDRESS field.

[C#]

Document doc = new Document();

// Create a user information object and set it as the data source for our field
UserInformation userInformation = new UserInformation();
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Display the current user's address with a USERADDRESS field
DocumentBuilder builder = new DocumentBuilder(doc);
FieldUserAddress fieldUserAddress = (FieldUserAddress)builder.InsertField(FieldType.FieldUserAddress, true);
Assert.AreEqual(userInformation.Address, fieldUserAddress.Result);

Assert.AreEqual(" USERADDRESS ", fieldUserAddress.GetFieldCode());
Assert.AreEqual("123 Main Street", fieldUserAddress.Result);

// We can set this attribute to get our field to display a different value
fieldUserAddress.UserAddress = "456 North Road";
fieldUserAddress.Update();

Assert.AreEqual(" USERADDRESS  \"456 North Road\"", fieldUserAddress.GetFieldCode());
Assert.AreEqual("456 North Road", fieldUserAddress.Result);

// This does not change the value in the user information object
Assert.AreEqual("123 Main Street", doc.FieldOptions.CurrentUser.Address);

See Also

FieldUserAddress Class | Aspose.Words.Fields Namespace


FieldUserInitials Class

Implements the USERINITIALS field.

For a list of all members of this type, see FieldUserInitials Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldUserInitials

[Visual Basic]
Public Class FieldUserInitials
Inherits Field
[C#]
public class FieldUserInitials : Field

Remarks

Retrieves the current user's initials.

Example

Shows how to use the USERINITIALS field.

[C#]

Document doc = new Document();

// Create a user information object and set it as the data source for our field
UserInformation userInformation = new UserInformation();
userInformation.Initials = "J. D.";
doc.FieldOptions.CurrentUser = userInformation;

// Display the current user's Initials with a USERINITIALS field
DocumentBuilder builder = new DocumentBuilder(doc);
FieldUserInitials fieldUserInitials = (FieldUserInitials)builder.InsertField(FieldType.FieldUserInitials, true);
Assert.AreEqual(userInformation.Initials, fieldUserInitials.Result);

Assert.AreEqual(" USERINITIALS ", fieldUserInitials.GetFieldCode());
Assert.AreEqual("J. D.", fieldUserInitials.Result);

// We can set this attribute to get our field to display a different value
fieldUserInitials.UserInitials = "J. C.";
fieldUserInitials.Update();

Assert.AreEqual(" USERINITIALS  \"J. C.\"", fieldUserInitials.GetFieldCode());
Assert.AreEqual("J. C.", fieldUserInitials.Result);

// This does not change the value in the user information object
Assert.AreEqual("J. D.", doc.FieldOptions.CurrentUser.Initials);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldUserInitials Members | Aspose.Words.Fields Namespace


FieldUserInitials Members

FieldUserInitials overview

Public Instance Constructors

FieldUserInitials Constructor Initializes a new instance of the FieldUserInitials class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UserInitials | Gets or sets the current user's initials.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldUserInitials Class | Aspose.Words.Fields Namespace


FieldUserInitials Constructor

Initializes a new instance of the FieldUserInitials class.

[Visual Basic]
Public Sub New()
[C#]
public FieldUserInitials();

See Also

FieldUserInitials Class | Aspose.Words.Fields Namespace


FieldUserInitials Properties

The properties of the FieldUserInitials class are listed below. For a complete list of FieldUserInitials class members, see the FieldUserInitials Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UserInitials | Gets or sets the current user's initials.

See Also

FieldUserInitials Class | Aspose.Words.Fields Namespace


UserInitials Property

Aspose.Words

FieldUserInitials.UserInitials Property

Gets or sets the current user's initials.

[Visual Basic]
Public Property UserInitials As String
[C#]
public string UserInitials {get; set;}

Example

Shows how to use the USERINITIALS field.

[C#]

Document doc = new Document();

// Create a user information object and set it as the data source for our field
UserInformation userInformation = new UserInformation();
userInformation.Initials = "J. D.";
doc.FieldOptions.CurrentUser = userInformation;

// Display the current user's Initials with a USERINITIALS field
DocumentBuilder builder = new DocumentBuilder(doc);
FieldUserInitials fieldUserInitials = (FieldUserInitials)builder.InsertField(FieldType.FieldUserInitials, true);
Assert.AreEqual(userInformation.Initials, fieldUserInitials.Result);

Assert.AreEqual(" USERINITIALS ", fieldUserInitials.GetFieldCode());
Assert.AreEqual("J. D.", fieldUserInitials.Result);

// We can set this attribute to get our field to display a different value
fieldUserInitials.UserInitials = "J. C.";
fieldUserInitials.Update();

Assert.AreEqual(" USERINITIALS  \"J. C.\"", fieldUserInitials.GetFieldCode());
Assert.AreEqual("J. C.", fieldUserInitials.Result);

// This does not change the value in the user information object
Assert.AreEqual("J. D.", doc.FieldOptions.CurrentUser.Initials);

See Also

FieldUserInitials Class | Aspose.Words.Fields Namespace


FieldUserName Class

Implements the USERNAME field.

For a list of all members of this type, see FieldUserName Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldUserName

[Visual Basic]
Public Class FieldUserName
Inherits Field
[C#]
public class FieldUserName : Field

Remarks

Retrieves the current user's name.

Example

Shows how to use the USERNAME field.

[C#]

Document doc = new Document();

// Create a user information object and set it as the data source for our field
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
doc.FieldOptions.CurrentUser = userInformation;

DocumentBuilder builder = new DocumentBuilder(doc);

// Display the current user's Name with a USERNAME field
FieldUserName fieldUserName = (FieldUserName)builder.InsertField(FieldType.FieldUserName, true);
Assert.AreEqual(userInformation.Name, fieldUserName.Result);

Assert.AreEqual(" USERNAME ", fieldUserName.GetFieldCode());
Assert.AreEqual("John Doe", fieldUserName.Result);

// We can set this attribute to get our field to display a different value
fieldUserName.UserName = "Jane Doe";
fieldUserName.Update();

Assert.AreEqual(" USERNAME  \"Jane Doe\"", fieldUserName.GetFieldCode());
Assert.AreEqual("Jane Doe", fieldUserName.Result);

// This does not change the value in the user information object
Assert.AreEqual("John Doe", doc.FieldOptions.CurrentUser.Name);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldUserName Members | Aspose.Words.Fields Namespace


FieldUserName Members

FieldUserName overview

Public Instance Constructors

FieldUserName Constructor Initializes a new instance of the FieldUserName class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UserName | Gest or sets the current user's name.

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldUserName Class | Aspose.Words.Fields Namespace


FieldUserName Constructor

Initializes a new instance of the FieldUserName class.

[Visual Basic]
Public Sub New()
[C#]
public FieldUserName();

See Also

FieldUserName Class | Aspose.Words.Fields Namespace


FieldUserName Properties

The properties of the FieldUserName class are listed below. For a complete list of FieldUserName class members, see the FieldUserName Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Type (inherited from Field) | Gets the Microsoft Word field type.
UserName | Gest or sets the current user's name.

See Also

FieldUserName Class | Aspose.Words.Fields Namespace


UserName Property

Aspose.Words

FieldUserName.UserName Property

Gest or sets the current user's name.

[Visual Basic]
Public Property UserName As String
[C#]
public string UserName {get; set;}

Example

Shows how to use the USERNAME field.

[C#]

Document doc = new Document();

// Create a user information object and set it as the data source for our field
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
doc.FieldOptions.CurrentUser = userInformation;

DocumentBuilder builder = new DocumentBuilder(doc);

// Display the current user's Name with a USERNAME field
FieldUserName fieldUserName = (FieldUserName)builder.InsertField(FieldType.FieldUserName, true);
Assert.AreEqual(userInformation.Name, fieldUserName.Result);

Assert.AreEqual(" USERNAME ", fieldUserName.GetFieldCode());
Assert.AreEqual("John Doe", fieldUserName.Result);

// We can set this attribute to get our field to display a different value
fieldUserName.UserName = "Jane Doe";
fieldUserName.Update();

Assert.AreEqual(" USERNAME  \"Jane Doe\"", fieldUserName.GetFieldCode());
Assert.AreEqual("Jane Doe", fieldUserName.Result);

// This does not change the value in the user information object
Assert.AreEqual("John Doe", doc.FieldOptions.CurrentUser.Name);

See Also

FieldUserName Class | Aspose.Words.Fields Namespace


FieldXE Class

Implements the XE field.

For a list of all members of this type, see FieldXE Members.

System.Object
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldXE

[Visual Basic]
Public Class FieldXE
Inherits Field
[C#]
public class FieldXE : Field

Remarks

Defines the text and page number for an index entry, which is used by an INDEX field.

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldXE Members | Aspose.Words.Fields Namespace


FieldXE Members

FieldXE overview

Public Instance Constructors

FieldXE Constructor Initializes a new instance of the FieldXE class.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryType | Gets or sets an index entry type.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HasPageRangeBookmarkName | Gets a value indicating whether a page range bookmark name is provided through the field's code.
IsBold | Gets or sets whether to apply bold formatting to the entry's page number.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsItalic | Gets or sets whether to apply italic formatting to the entry's page number.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumberReplacement | Gets or sets text used in place of a page number.
PageRangeBookmarkName | Gets or sets the name of the bookmark that marks a range of pages that is inserted as the entry's page number.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the entry.
Type (inherited from Field) | Gets the Microsoft Word field type.
Yomi | Gets or sets the yomi (first phonetic character for sorting indexes) for the index entry

Public Instance Methods

GetFieldCode (inherited from Field) | Overloaded. Returns text between field start and field separator (or field end if there is no separator). Both field code and field result of child fields are included.
Remove (inherited from Field) | Removes the field from the document. Returns a node right after the field. If the field's end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null.
Unlink (inherited from Field) | Performs the field unlink.
Update (inherited from Field) | Overloaded. Performs the field update. Throws if the field is being updated already.

See Also

FieldXE Class | Aspose.Words.Fields Namespace


FieldXE Constructor

Initializes a new instance of the FieldXE class.

[Visual Basic]
Public Sub New()
[C#]
public FieldXE();

See Also

FieldXE Class | Aspose.Words.Fields Namespace


FieldXE Properties

The properties of the FieldXE class are listed below. For a complete list of FieldXE class members, see the FieldXE Members topic.

Public Instance Properties

DisplayResult (inherited from Field) | Gets the text that represents the displayed field result.
End (inherited from Field) | Gets the node that represents the field end.
EntryType | Gets or sets an index entry type.
Format (inherited from Field) | Gets a FieldFormat object that provides typed access to field's formatting.
HasPageRangeBookmarkName | Gets a value indicating whether a page range bookmark name is provided through the field's code.
IsBold | Gets or sets whether to apply bold formatting to the entry's page number.
IsDirty (inherited from Field) | Gets or sets whether the current result of the field is no longer correct (stale) due to other modifications made to the document.
IsItalic | Gets or sets whether to apply italic formatting to the entry's page number.
IsLocked (inherited from Field) | Gets or sets whether the field is locked (should not recalculate its result).
LocaleId (inherited from Field) | Gets or sets the LCID of the field.
PageNumberReplacement | Gets or sets text used in place of a page number.
PageRangeBookmarkName | Gets or sets the name of the bookmark that marks a range of pages that is inserted as the entry's page number.
Result (inherited from Field) | Gets or sets text that is between the field separator and field end.
Separator (inherited from Field) | Gets the node that represents the field separator. Can be null.
Start (inherited from Field) | Gets the node that represents the start of the field.
Text | Gets or sets the text of the entry.
Type (inherited from Field) | Gets the Microsoft Word field type.
Yomi | Gets or sets the yomi (first phonetic character for sorting indexes) for the index entry

See Also

FieldXE Class | Aspose.Words.Fields Namespace


EntryType Property

Aspose.Words

FieldXE.EntryType Property

Gets or sets an index entry type.

[Visual Basic]
Public Property EntryType As String
[C#]
public string EntryType {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


HasPageRangeBookmarkName Property

Aspose.Words

FieldXE.HasPageRangeBookmarkName Property

Gets a value indicating whether a page range bookmark name is provided through the field's code.

[Visual Basic]
Public ReadOnly Property HasPageRangeBookmarkName As Boolean
[C#]
public bool HasPageRangeBookmarkName {get;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


IsBold Property

Aspose.Words

FieldXE.IsBold Property

Gets or sets whether to apply bold formatting to the entry's page number.

[Visual Basic]
Public Property IsBold As Boolean
[C#]
public bool IsBold {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


IsItalic Property

Aspose.Words

FieldXE.IsItalic Property

Gets or sets whether to apply italic formatting to the entry's page number.

[Visual Basic]
Public Property IsItalic As Boolean
[C#]
public bool IsItalic {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


PageNumberReplacement Property

Aspose.Words

FieldXE.PageNumberReplacement Property

Gets or sets text used in place of a page number.

[Visual Basic]
Public Property PageNumberReplacement As String
[C#]
public string PageNumberReplacement {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


PageRangeBookmarkName Property

Aspose.Words

FieldXE.PageRangeBookmarkName Property

Gets or sets the name of the bookmark that marks a range of pages that is inserted as the entry's page number.

[Visual Basic]
Public Property PageRangeBookmarkName As String
[C#]
public string PageRangeBookmarkName {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


Text Property

Aspose.Words

FieldXE.Text Property

Gets or sets the text of the entry.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


Yomi Property

Aspose.Words

FieldXE.Yomi Property

Gets or sets the yomi (first phonetic character for sorting indexes) for the index entry

[Visual Basic]
Public Property Yomi As String
[C#]
public string Yomi {get; set;}

Example

Shows how to populate an index field with index entries.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create an index field which will contain all the index entries
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);

// Bookmark that will encompass a section that we want to index
string mainBookmarkName = "MainBookmark";
builder.StartBookmark(mainBookmarkName);
index.BookmarkName = mainBookmarkName;
index.CrossReferenceSeparator = ":";
index.Heading = ">";
index.LanguageId = "1033";
index.LetterRange = "a-j";
index.NumberOfColumns = "2";
index.PageNumberListSeparator = "|";
index.PageNumberSeparator = "|";
index.PageRangeSeparator = "/";
index.UseYomi = true;
index.RunSubentriesOnSameLine = false;
index.SequenceName = "Chapter";
index.SequenceSeparator = ":";
Assert.IsTrue(index.HasPageNumberSeparator);
Assert.IsTrue(index.HasSequenceName);

// Our index will take up page 1
builder.InsertBreak(BreakType.PageBreak);

// Use a document builder to insert an index entry
// Index entries are not added to the index manually, it will find them on its own
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 1";
indexEntry.EntryType = "Type1";
indexEntry.IsBold = true;
indexEntry.IsItalic = true;
Assert.AreEqual(false, indexEntry.HasPageRangeBookmarkName);

// We can insert a bookmark and have the index field point to it
string subBookmarkName = "MyBookmark";
builder.StartBookmark(subBookmarkName);
builder.Writeln("Bookmark text contents.");
builder.EndBookmark(subBookmarkName);

// Put the bookmark and index entry field on different pages
// Our index will use the page that the bookmark is on, not that of the index entry field, as the page number
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 2";
indexEntry.EntryType = "Type1";
indexEntry.PageRangeBookmarkName = subBookmarkName;
Assert.AreEqual(true, indexEntry.HasPageRangeBookmarkName);

// We can use the PageNumberReplacement property to point to any page we want, even one that may not exist
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Index entry 3";
indexEntry.EntryType = "Type1";
indexEntry.PageNumberReplacement = "999";

// If we are using an East Asian language, we can sort entries phonetically (using Furigana) instead of alphabetically
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "漢字";
indexEntry.EntryType = "Type1";

// The Yomi field will contain the character looked up for sorting
indexEntry.Yomi = "か";

// If we are sorting phonetically, we need to notify the index
index.UseYomi = true;

// For all our entry fields, we set the entry type to "Type1"
// Our field index will not list those entries unless we set its entry type to that of the entries
index.EntryType = "Type1";

builder.EndBookmark(mainBookmarkName);

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.XE.docx");

See Also

FieldXE Class | Aspose.Words.Fields Namespace


FormField Class

Represents a single form field.

For a list of all members of this type, see FormField Members.

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.Fields.FormField

[Visual Basic]
Public Class FormField
Inherits SpecialChar
[C#]
public class FormField : SpecialChar

Remarks

Microsoft Word provides the following form fields: checkbox, text input and dropdown (combobox).

FormField is an inline-node and can only be a child of Paragraph.

FormField is represented in a document by a special character and positioned as a character within a line of text.

A complete form field in a Word document is a complex structure represented by several nodes: field start, field code such as FORMTEXT, form field data, field separator, field result, field end and a bookmark. To programmatically create form fields in a Word document use DocumentBuilder.InsertCheckBox, DocumentBuilder.InsertTextInput and DocumentBuilder.InsertComboBox which make sure all of the form field nodes are created in a correct order and in a suitable state.

Example

Shows how to work with form field name, type, and result.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");

FormField formField = doc.Range.FormFields[3];

if (formField.Type.Equals(FieldType.FieldFormTextInput))
    formField.Result = "My name is " + formField.Name;
Shows how to access form fields.
[C#]

Document doc = new Document(MyDir + "FormFields.doc");
FormFieldCollection documentFormFields = doc.Range.FormFields;

FormField formField1 = documentFormFields[3];
FormField formField2 = documentFormFields["CustomerName"];

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FormField Members | Aspose.Words.Fields Namespace


FormField Members

FormField overview

Public Instance Properties

CalculateOnExit | True if references to the specified form field are automatically updated whenever the field is exited.
CheckBoxSize | Gets or sets the size of the checkbox in points. Has effect only when IsCheckBoxExactSize is true.
Checked | Gets or sets the checked status of the check box form field. Default value for this property is false.
Default | Gets or sets the default value of the check box form field. Default value for this property is false.
Document (inherited from Node) | Gets the document to which this node belongs.
DropDownItems | Provides access to the items of a dropdown form field.
DropDownSelectedIndex | Gets or sets the index specifying the currently selected item in a dropdown form field.
Enabled | True if a form field is enabled.
EntryMacro | Returns or sets an entry macro name for the form field.
ExitMacro | Returns or sets an exit macro name for the form field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
HelpText | Returns or sets the text that's displayed in a message box when the form field has the focus and the user presses F1.
IsCheckBoxExactSize | Gets or sets the boolean value that indicates whether the size of the textbox is automatic or specified explicitly.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
MaxLength | Maximum length for the text field. Zero when the length is not limited.
Name | Gets or sets the form field name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.FormField.
OwnHelp | Specifies the source of the text that's displayed in a message box when a form field has the focus and the user presses F1.
OwnStatus | Specifies the source of the text that's displayed in the status bar when a form field has the focus.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Result | Gets or sets a string that represents the result of this form field.
StatusText | Returns or sets the text that's displayed in the status bar when a form field has the focus.
TextInputDefault | Gets or sets the default string or a calculation expression of a text form field.
TextInputFormat | Returns or sets the text formatting for a text form field.
TextInputType | Gets or sets the type of a text form field.
Type | Returns the form field type.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveField | Removes the complete form field, not just the form field special character.
SetTextInputValue | Applies the text format specified in TextInputFormat and stores the value in Result.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FormField Class | Aspose.Words.Fields Namespace


FormField Properties

The properties of the FormField class are listed below. For a complete list of FormField class members, see the FormField Members topic.

Public Instance Properties

CalculateOnExit | True if references to the specified form field are automatically updated whenever the field is exited.
CheckBoxSize | Gets or sets the size of the checkbox in points. Has effect only when IsCheckBoxExactSize is true.
Checked | Gets or sets the checked status of the check box form field. Default value for this property is false.
Default | Gets or sets the default value of the check box form field. Default value for this property is false.
Document (inherited from Node) | Gets the document to which this node belongs.
DropDownItems | Provides access to the items of a dropdown form field.
DropDownSelectedIndex | Gets or sets the index specifying the currently selected item in a dropdown form field.
Enabled | True if a form field is enabled.
EntryMacro | Returns or sets an entry macro name for the form field.
ExitMacro | Returns or sets an exit macro name for the form field.
Font (inherited from Inline) | Provides access to the font formatting of this object.
HelpText | Returns or sets the text that's displayed in a message box when the form field has the focus and the user presses F1.
IsCheckBoxExactSize | Gets or sets the boolean value that indicates whether the size of the textbox is automatic or specified explicitly.
IsComposite (inherited from Node) | Returns true if this node can contain other nodes.
IsDeleteRevision (inherited from Inline) | Returns true if this object was deleted in Microsoft Word while change tracking was enabled.
IsFormatRevision (inherited from Inline) | Returns true if formatting of the object was changed in Microsoft Word while change tracking was enabled.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
IsMoveFromRevision (inherited from Inline) | Returns true if this object was moved (deleted) in Microsoft Word while change tracking was enabled.
IsMoveToRevision (inherited from Inline) | Returns true if this object was moved (inserted) in Microsoft Word while change tracking was enabled.
MaxLength | Maximum length for the text field. Zero when the length is not limited.
Name | Gets or sets the form field name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.FormField.
OwnHelp | Specifies the source of the text that's displayed in a message box when a form field has the focus and the user presses F1.
OwnStatus | Specifies the source of the text that's displayed in the status bar when a form field has the focus.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph (inherited from Inline) | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Result | Gets or sets a string that represents the result of this form field.
StatusText | Returns or sets the text that's displayed in the status bar when a form field has the focus.
TextInputDefault | Gets or sets the default string or a calculation expression of a text form field.
TextInputFormat | Returns or sets the text formatting for a text form field.
TextInputType | Gets or sets the type of a text form field.
Type | Returns the form field type.

See Also

FormField Class | Aspose.Words.Fields Namespace


CalculateOnExit Property

Aspose.Words

FormField.CalculateOnExit Property

True if references to the specified form field are automatically updated whenever the field is exited.

[Visual Basic]
Public Property CalculateOnExit As Boolean
[C#]
public bool CalculateOnExit {get; set;}

Remarks

Setting CalculateOnExit only affects the behavior of the form field when the document is opened in Microsoft Word. Aspose.Words never updates references to the form field.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


CheckBoxSize Property

Aspose.Words

FormField.CheckBoxSize Property

Gets or sets the size of the checkbox in points. Has effect only when IsCheckBoxExactSize is true.

[Visual Basic]
Public Property CheckBoxSize As Double
[C#]
public double CheckBoxSize {get; set;}

Remarks

Applicable for a check box form field only.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace | IsCheckBoxExactSize


Checked Property

Aspose.Words

FormField.Checked Property

Gets or sets the checked status of the check box form field. Default value for this property is false.

[Visual Basic]
Public Property Checked As Boolean
[C#]
public bool Checked {get; set;}

Remarks

Applicable for a check box form field only.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


Default Property

Aspose.Words

FormField.Default Property

Gets or sets the default value of the check box form field. Default value for this property is false.

[Visual Basic]
Public Property Default As Boolean
[C#]
public bool Default {get; set;}

Remarks

Applicable for a check box form field only.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


DropDownItems Property

Aspose.Words

FormField.DropDownItems Property

Provides access to the items of a dropdown form field.

[Visual Basic]
Public ReadOnly Property DropDownItems As DropDownItemCollection
[C#]
public DropDownItemCollection DropDownItems {get;}

Remarks

Microsoft Word allows maximum 25 items in a dropdown form field.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


DropDownSelectedIndex Property

Aspose.Words

FormField.DropDownSelectedIndex Property

Gets or sets the index specifying the currently selected item in a dropdown form field.

[Visual Basic]
Public Property DropDownSelectedIndex As Integer
[C#]
public int DropDownSelectedIndex {get; set;}

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


Enabled Property

Aspose.Words

FormField.Enabled Property

True if a form field is enabled.

[Visual Basic]
Public Property Enabled As Boolean
[C#]
public bool Enabled {get; set;}

Remarks

If a form field is enabled, its contents can be changed as the form is filled in.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


EntryMacro Property

Aspose.Words

FormField.EntryMacro Property

Returns or sets an entry macro name for the form field.

[Visual Basic]
Public Property EntryMacro As String
[C#]
public string EntryMacro {get; set;}

Remarks

The entry macro runs when the form field gets the focus in Microsoft Word.

Microsoft Word allows strings with at most 32 characters.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


ExitMacro Property

Aspose.Words

FormField.ExitMacro Property

Returns or sets an exit macro name for the form field.

[Visual Basic]
Public Property ExitMacro As String
[C#]
public string ExitMacro {get; set;}

Remarks

The exit macro runs when the form field loses the focus in Microsoft Word.

Microsoft Word allows strings with at most 32 characters.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


HelpText Property

Aspose.Words

FormField.HelpText Property

Returns or sets the text that's displayed in a message box when the form field has the focus and the user presses F1.

[Visual Basic]
Public Property HelpText As String
[C#]
public string HelpText {get; set;}

Remarks

If the OwnHelp property is set to True, HelpText specifies the text string value. If OwnHelp is set to False, HelpText specifies the name of an AutoText entry that contains help text for the form field.

Microsoft Word allows strings with at most 255 characters.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


IsCheckBoxExactSize Property

Aspose.Words

FormField.IsCheckBoxExactSize Property

Gets or sets the boolean value that indicates whether the size of the textbox is automatic or specified explicitly.

[Visual Basic]
Public Property IsCheckBoxExactSize As Boolean
[C#]
public bool IsCheckBoxExactSize {get; set;}

Remarks

Applicable for a check box form field only.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace | CheckBoxSize


MaxLength Property

Aspose.Words

FormField.MaxLength Property

Maximum length for the text field. Zero when the length is not limited.

[Visual Basic]
Public Property MaxLength As Integer
[C#]
public int MaxLength {get; set;}

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


Name Property

Aspose.Words

FormField.Name Property

Gets or sets the form field name.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

Microsoft Word allows strings with at most 20 characters.

Example

Shows how to work with form field name, type, and result.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");

FormField formField = doc.Range.FormFields[3];

if (formField.Type.Equals(FieldType.FieldFormTextInput))
    formField.Result = "My name is " + formField.Name;

See Also

FormField Class | Aspose.Words.Fields Namespace


NodeType Property

Aspose.Words

FormField.NodeType Property

Returns NodeType.FormField.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

FormField Class | Aspose.Words.Fields Namespace


OwnHelp Property

Aspose.Words

FormField.OwnHelp Property

Specifies the source of the text that's displayed in a message box when a form field has the focus and the user presses F1.

[Visual Basic]
Public Property OwnHelp As Boolean
[C#]
public bool OwnHelp {get; set;}

Remarks

If True, the text specified by the HelpText property is displayed. If False, the text in the AutoText entry specified by the HelpText property is displayed.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


OwnStatus Property

Aspose.Words

FormField.OwnStatus Property

Specifies the source of the text that's displayed in the status bar when a form field has the focus.

[Visual Basic]
Public Property OwnStatus As Boolean
[C#]
public bool OwnStatus {get; set;}

Remarks

If true, the text specified by the StatusText property is displayed. If false, the text of the AutoText entry specified by the StatusText property is displayed.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


Result Property

Aspose.Words

FormField.Result Property

Gets or sets a string that represents the result of this form field.

[Visual Basic]
Public Property Result As String
[C#]
public string Result {get; set;}

Remarks

For a text form field the result is the text that is in the field.

For a checkbox form field the result can be "1" or "0" to indicate checked or unchecked.

For a dropdown form field the result is the string selected in the dropdown.

Setting Result for a text form field does not apply the text format specified in TextInputFormat. If you want to set a value and apply the format, use the SetTextInputValue method.

Example

Shows how to work with form field name, type, and result.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");

FormField formField = doc.Range.FormFields[3];

if (formField.Type.Equals(FieldType.FieldFormTextInput))
    formField.Result = "My name is " + formField.Name;

See Also

FormField Class | Aspose.Words.Fields Namespace


StatusText Property

Aspose.Words

FormField.StatusText Property

Returns or sets the text that's displayed in the status bar when a form field has the focus.

[Visual Basic]
Public Property StatusText As String
[C#]
public string StatusText {get; set;}

Remarks

If the OwnStatus property is set to true, the StatusText property specifies the status bar text. If the OwnStatus property is set to false, the StatusText property specifies the name of an AutoText entry that contains status bar text for the form field.

Microsoft Word allows strings with at most 138 characters.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


TextInputDefault Property

Aspose.Words

FormField.TextInputDefault Property

Gets or sets the default string or a calculation expression of a text form field.

[Visual Basic]
Public Property TextInputDefault As String
[C#]
public string TextInputDefault {get; set;}

Remarks

The meaning of this property depends on the value of the TextInputType property.

When TextInputType is Regular or Number, this string specifies the default string for the text form field. This string is the content that Microsoft Word will display in the document when the form field is empty.

When TextInputType is Calculated, then this string holds the expression to be calculated. The expression needs to be a formula valid according to Microsoft Word formula field requirements. When you set a new expression using this property, Aspose.Words calculates the formula result automatically and inserts it into the form field.

Microsoft Word allows strings with at most 255 characters.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


TextInputFormat Property

Aspose.Words

FormField.TextInputFormat Property

Returns or sets the text formatting for a text form field.

[Visual Basic]
Public Property TextInputFormat As String
[C#]
public string TextInputFormat {get; set;}

Remarks

If the text form field contains regular text, then valid format strings are "", "UPPERCASE", "LOWERCASE", "FIRST CAPITAL" and "TITLE CASE". The strings are case-insensitive.

If the text form field contains a number or a date/time value, then valid format strings are number or date and time format strings.

Microsoft Word allows strings with at most 64 characters.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


TextInputType Property

Aspose.Words

FormField.TextInputType Property

Gets or sets the type of a text form field.

[Visual Basic]
Public Property TextInputType As TextFormFieldType
[C#]
public TextFormFieldType TextInputType {get; set;}

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


Type Property

Aspose.Words

FormField.Type Property

Returns the form field type.

[Visual Basic]
Public ReadOnly Property Type As FieldType
[C#]
public FieldType Type {get;}

Example

Shows how to work with form field name, type, and result.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");

FormField formField = doc.Range.FormFields[3];

if (formField.Type.Equals(FieldType.FieldFormTextInput))
    formField.Result = "My name is " + formField.Name;

See Also

FormField Class | Aspose.Words.Fields Namespace


FormField Methods

The methods of the FormField class are listed below. For a complete list of FormField class members, see the FormField Members topic.

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetText (inherited from SpecialChar) | Gets the special character that this node represents.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveField | Removes the complete form field, not just the form field special character.
SetTextInputValue | Applies the text format specified in TextInputFormat and stores the value in Result.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

FormField Class | Aspose.Words.Fields Namespace


FormField.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the node.

Return Value

False if the visitor requested the enumeration to stop.

Remarks

Calls DocumentVisitor.VisitFormField.

For more info see the Visitor design pattern.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


FormField.RemoveField Method

Removes the complete form field, not just the form field special character.

[Visual Basic]
Public Sub RemoveField()
[C#]
public void RemoveField();

Remarks

If there is a bookmark associated with the form field, the bookmark is not removed.

Example

Shows how to delete complete form field

[C#]

Document doc = new Document(MyDir + "FormFields.doc");

FormField formField = doc.Range.FormFields[3];
formField.RemoveField();

See Also

FormField Class | Aspose.Words.Fields Namespace


FormField.SetTextInputValue Method

Applies the text format specified in TextInputFormat and stores the value in Result.

[Visual Basic]
Public Sub SetTextInputValue( _
ByVal newValue As Object _
)
[C#]
public void SetTextInputValue(
object newValue
);

Parameters

newValue
Can be a string, number or a DateTime object.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormField Class | Aspose.Words.Fields Namespace


FormFieldCollection Class

A collection of FormField objects that represent all the form fields in a range.

For a list of all members of this type, see FormFieldCollection Members.

System.Object
Aspose.Words.Fields.FormFieldCollection

[Visual Basic]
Public Class FormFieldCollection
Implements IEnumerable`1([Aspose.Words.Fields.FormField, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class FormFieldCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to get a collection of form fields.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");
FormFieldCollection formFields = doc.Range.FormFields;

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FormFieldCollection Members | Aspose.Words.Fields Namespace


FormFieldCollection Members

FormFieldCollection overview

Public Instance Properties

Count | Returns the number of form fields in the collection.
Item | Overloaded. Returns a form field at the specified index.

Public Instance Methods

Clear | Removes all form fields from this collection and from the document.
GetEnumerator | Returns an enumerator object.
Remove | Removes a form field with the specified name.
RemoveAt | Removes a form field at the specified index.

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection Properties

The properties of the FormFieldCollection class are listed below. For a complete list of FormFieldCollection class members, see the FormFieldCollection Members topic.

Public Instance Properties

Count | Returns the number of form fields in the collection.
Item | Overloaded. Returns a form field at the specified index.

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


Count Property

Aspose.Words

FormFieldCollection.Count Property

Returns the number of form fields in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


Item Property

Aspose.Words

FormFieldCollection.Item Property

Returns a form field at the specified index.

Overload List

Returns a form field at the specified index.

public FormField this[int] {get;}

Returns a form field by bookmark name.

public FormField this[string] {get;}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


Item Property (Int32)

Aspose.Words

FormFieldCollection.Item Property (Int32)

Returns a form field at the specified index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As FormField
[C#]
public FormField this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace | FormFieldCollection.Item Overload List


Item Property (String)

Aspose.Words

FormFieldCollection.Item Property (String)

Returns a form field by bookmark name.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal bookmarkName As String _
) As FormField
[C#]
public FormField this[
string bookmarkName
] {get;}

Parameters

bookmarkName
Case-insensitive bookmark name.

Remarks

Returns null if the form field with the specified bookmark name cannot be found.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace | FormFieldCollection.Item Overload List


FormFieldCollection Methods

The methods of the FormFieldCollection class are listed below. For a complete list of FormFieldCollection class members, see the FormFieldCollection Members topic.

Public Instance Methods

Clear | Removes all form fields from this collection and from the document.
GetEnumerator | Returns an enumerator object.
Remove | Removes a form field with the specified name.
RemoveAt | Removes a form field at the specified index.

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection.Clear Method

Removes all form fields from this collection and from the document.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of FormField) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<FormField> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection.Remove Method

Removes a form field with the specified name.

[Visual Basic]
Public Sub Remove( _
ByVal formField As String _
)
[C#]
public void Remove(
string formField
);

Parameters

formField
The case-insensitive name of the form field to remove.

Remarks

If there is a bookmark associated with the form field, the bookmark is not removed.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection.RemoveAt Method

Removes a form field at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the form field to remove.

Remarks

If there is a bookmark associated with the form field, the bookmark is not removed.

Example

Shows how insert different kinds of form fields into a document and process them with a visitor implementation.

[C#]

public void FormField()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Use a document builder to insert a combo box
    FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);
    comboBox.CalculateOnExit = true;
    Assert.AreEqual(3, comboBox.DropDownItems.Count);
    Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
    Assert.AreEqual(true, comboBox.Enabled);

    builder.Writeln();

    // Use a document builder to insert a check box
    FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);
    checkBox.IsCheckBoxExactSize = true;
    checkBox.HelpText = "Right click to check this box";
    checkBox.OwnHelp = true;
    checkBox.StatusText = "Checkbox status text";
    checkBox.OwnStatus = true;
    Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
    Assert.AreEqual(false, checkBox.Checked);
    Assert.AreEqual(false, checkBox.Default);

    builder.Writeln();

    // Use a document builder to insert text input form field
    FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);
    Assert.AreEqual(3, doc.Range.Fields.Count);
    textInput.EntryMacro = "EntryMacro";
    textInput.ExitMacro = "ExitMacro";
    textInput.TextInputDefault = "Regular";
    textInput.TextInputFormat = "FIRST CAPITAL";
    textInput.SetTextInputValue("This value overrides the one we set during initialization");
    Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
    Assert.AreEqual(50, textInput.MaxLength);

    // Get the collection of form fields that has accumulated in our document
    FormFieldCollection formFields = doc.Range.FormFields;
    Assert.AreEqual(3, formFields.Count);

    // Iterate over the collection with an enumerator, accepting a visitor with each form field
    FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

    using (IEnumerator<FormField> fieldEnumerator = formFields.GetEnumerator())
    {
        while (fieldEnumerator.MoveNext())
        {
            fieldEnumerator.Current.Accept(formFieldVisitor);
        }
    }

    Console.WriteLine(formFieldVisitor.GetText());

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.FormField.docx");
}

/// <summary>
/// Visitor implementation that prints information about visited form fields.
/// </summary>
public class FormFieldVisitor : DocumentVisitor
{
    public FormFieldVisitor()
    {
        mBuilder = new StringBuilder();
    }

    /// <summary>
    /// Called when a FormField node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        AppendLine(formField.Type + ": \"" + formField.Name + "\"");
        AppendLine("\tStatus: " + (formField.Enabled ? "Enabled" : "Disabled"));
        AppendLine("\tHelp Text:  " + formField.HelpText);
        AppendLine("\tEntry macro name: " + formField.EntryMacro);
        AppendLine("\tExit macro name: " + formField.ExitMacro);

        switch (formField.Type)
        {
            case FieldType.FieldFormDropDown:
                AppendLine("\tDrop down items count: " + formField.DropDownItems.Count + ", default selected item index: " + formField.DropDownSelectedIndex);
                AppendLine("\tDrop down items: " + string.Join(", ", formField.DropDownItems.ToArray()));
                break;
            case FieldType.FieldFormCheckBox:
                AppendLine("\tCheckbox size: " + formField.CheckBoxSize);
                AppendLine("\t" + "Checkbox is currently: " + (formField.Checked ? "checked, " : "unchecked, ") + "by default: " + (formField.Default ? "checked" : "unchecked"));
                break;
            case FieldType.FieldFormTextInput:
                AppendLine("\tInput format: " + formField.TextInputFormat);
                AppendLine("\tCurrent contents: " + formField.Result);
                break;
        }

        // Let the visitor continue visiting other nodes.
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Adds newline char-terminated text to the current output.
    /// </summary>
    private void AppendLine(string text)
    {
        mBuilder.Append(text + '\n');
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public string GetText()
    {
        return mBuilder.ToString();
    }

    private readonly StringBuilder mBuilder;
}

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


GeneralFormat Enumeration

Specifies a general format that is applied to a numeric, text, or any field result. A field may have a combination of general formats.

[Visual Basic]
Public Enum GeneralFormat
[C#]
public enum GeneralFormat

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

Members

Member Name | Description | Value
None | Used to specify a missing general format. | 0
Aiueo | Numeric formatting. Formats a numeric result using hiragana characters in the traditional a-i-u-e-o order. | 1
UppercaseAlphabetic | Numeric formatting. Formats a numeric result as one or more occurrences of an uppercase alphabetic Latin character. | 2
LowercaseAlphabetic | Numeric formatting. Formats a numeric result as one or more occurrences of an lowercase alphabetic Latin character. | 3
Arabic | Numeric formatting. Formats a numeric result using Arabic cardinal numerals. | 4
ArabicAbjad | Numeric formatting. Formats a numeric result using ascending Abjad numerals. | 5
ArabicAlpha | Numeric formatting. Formats a numeric result using characters in the Arabic alphabet. | 6
ArabicDash | Numeric formatting. Formats a numeric result using Arabic cardinal numerals, with a prefix of "- " and a suffix of " -". | 7
BahtText | Numeric formatting. Formats a numeric result in the Thai counting system. | 8
CardText | Numeric formatting. Cardinal text (One, Two, Three, ...). | 9
ChineseNum1 | Numeric formatting. Formats a numeric result using ascending numbers from the appropriate counting system. | 10
ChineseNum2 | Numeric formatting. Formats a numeric result using sequential numbers from the appropriate legal format. | 11
ChineseNum3 | Numeric formatting. Formats a numeric result using sequential numbers from the appropriate counting thousand system. | 12
Chosung | Numeric formatting. Formats a numeric result using sequential numbers from the Korean Chosung format. | 13
CircleNum | Numeric formatting. Formats a numeric result using decimal numbering enclosed in a circle, using the enclosed alphanumeric glyph character for numbers in the range 1–20. | 14
DBChar | Numeric formatting. Formats a numeric result using double-byte Arabic numbering. | 15
DBNum1 | Numeric formatting. Formats a numeric result using sequential digital ideographs, using the appropriate character. | 16
DBNum2 | Numeric formatting. Formats a numeric result using sequential numbers from the appropriate counting system. | 17
DBNum3 | Numeric formatting. Formats a numeric result using sequential numbers from the appropriate legal counting system. | 18
DBNum4 | Numeric formatting. Formats a numeric result using sequential numbers from the appropriate digital counting system. | 19
DollarText | Numeric formatting. Dollar text (One, Two, Three, ... + AND 55/100). | 20
Ganada | Numeric formatting. Formats a numeric result using sequential numbers from the Korean Ganada format. | 21
GB1 | Numeric formatting. Formats a numeric result using decimal numbering followed by a period, using the enclosed alphanumeric glyph character. | 22
GB2 | Numeric formatting. Formats a numeric result using decimal numbering enclosed in parenthesis, using the enclosed alphanumeric glyph character. | 23
GB3 | Numeric formatting. Formats a numeric result using decimal numbering enclosed in a circle, using the enclosed alphanumeric glyph character. | 24
GB4 | Numeric formatting. Formats a numeric result using decimal numbering enclosed in a circle, using the enclosed alphanumeric glyph character. | 25
Hebrew1 | Numeric formatting. Formats a numeric result using Hebrew numerals. | 26
Hebrew2 | Numeric formatting. Formats a numeric result using the Hebrew alphabet. | 27
Hex | Numeric formatting. Formats the numeric result using uppercase hexadecimal digits. | 28
HindiArabic | Numeric formatting. Formats a numeric result using Hindi numbers. | 29
HindiCardText | Numeric formatting. Formats a numeric result using sequential numbers from the Hindi counting system. | 30
HindiLetter1 | Numeric formatting. Formats a numeric result using Hindi vowels. | 31
HindiLetter2 | Numeric formatting. Formats a numeric result using Hindi consonants. | 32
Iroha | Numeric formatting. Formats a numeric result using the Japanese iroha. | 33
KanjiNum1 | Numeric formatting. Formats a numeric result using a Japanese style using the appropriate counting system. | 34
KanjiNum2 | Numeric formatting. Formats a numeric result using the appropriate counting system. | 35
KanjiNum3 | Numeric formatting. Formats a numeric result using the appropriate counting system. | 36
Ordinal | Numeric formatting. Ordinal (1st, 2nd, 3rd, ...). | 37
OrdText | Numeric formatting. Ordinal text (First, Second, Third, ...). | 38
UppercaseRoman | Numeric formatting. Uppercase Roman (I, II, III, ...). | 39
LowercaseRoman | Numeric formatting. Lowercase Roman (i, ii, iii, ...). | 40
SBChar | Numeric formatting. Formats a numeric result using single-byte Arabic numbering. | 41
ThaiArabic | Numeric formatting. Formats a numeric result using Thai numbers. | 42
ThaiCardText | Numeric formatting. Formats a numeric result using sequential numbers from the Thai counting system. | 43
ThaiLetter | Numeric formatting. Formats a numeric result using Thai letters. | 44
VietCardText | Numeric formatting. Formats a numeric result using Vietnamese numerals. | 45
Zodiac1 | Numeric formatting. Formats a numeric result using sequential numerical traditional ideographs. | 46
Zodiac2 | Numeric formatting. Formats a numeric result using sequential zodiac ideographs. | 47
Zodiac3 | Numeric formatting. Formats a numeric result using sequential traditional zodiac ideographs. | 48
Caps | Text formatting. Capitalizes the first letter of each word. | 49
FirstCap | Text formatting. Capitalizes the first letter of the first word. | 50
Lower | Text formatting. All letters are lowercase. | 51
Upper | Text formatting. All letters are uppercase. | 52
CharFormat | Field result formatting. The CHARFORMAT instruction. | 53
MergeFormat | Field result formatting. The MERGEFORMAT instruction. | 54
MergeFormatInet | Field result formatting. The MERGEFORMATINET instruction. | 55

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fields Namespace


GeneralFormatCollection Class

Represents a typed collection of general formats.

For a list of all members of this type, see GeneralFormatCollection Members.

System.Object
Aspose.Words.Fields.GeneralFormatCollection

[Visual Basic]
Public Class GeneralFormatCollection
Implements IEnumerable`1([Aspose.Words.Fields.GeneralFormat, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class GeneralFormatCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

GeneralFormatCollection Members | Aspose.Words.Fields Namespace


GeneralFormatCollection Members

GeneralFormatCollection overview

Public Instance Properties

Count | Gets the total number of the items in the collection.
Item | Gets a general format at the specified index.

Public Instance Methods

Add | Adds a general format to the collection.
GetEnumerator | Returns an enumerator object.
Remove | Removes all occurrences of the specified general format from the collection.
RemoveAt | Removes a general format occurrence at the specified index.

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


GeneralFormatCollection Properties

The properties of the GeneralFormatCollection class are listed below. For a complete list of GeneralFormatCollection class members, see the GeneralFormatCollection Members topic.

Public Instance Properties

Count | Gets the total number of the items in the collection.
Item | Gets a general format at the specified index.

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


Count Property

Aspose.Words

GeneralFormatCollection.Count Property

Gets the total number of the items in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


Item Property

Aspose.Words

GeneralFormatCollection.Item Property

Gets a general format at the specified index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As GeneralFormat
[C#]
public GeneralFormat this[
int index
] {get;}

Parameters

index
The index of a general format.

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


GeneralFormatCollection Methods

The methods of the GeneralFormatCollection class are listed below. For a complete list of GeneralFormatCollection class members, see the GeneralFormatCollection Members topic.

Public Instance Methods

Add | Adds a general format to the collection.
GetEnumerator | Returns an enumerator object.
Remove | Removes all occurrences of the specified general format from the collection.
RemoveAt | Removes a general format occurrence at the specified index.

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


GeneralFormatCollection.Add Method

Adds a general format to the collection.

[Visual Basic]
Public Sub Add( _
ByVal item As GeneralFormat _
)
[C#]
public void Add(
GeneralFormat item
);

Parameters

item
A general format.

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


GeneralFormatCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of GeneralFormat) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<GeneralFormat> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


GeneralFormatCollection.Remove Method

Removes all occurrences of the specified general format from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal item As GeneralFormat _
)
[C#]
public void Remove(
GeneralFormat item
);

Parameters

item
A general format.

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


GeneralFormatCollection.RemoveAt Method

Removes a general format occurrence at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index

Example

Shows how to format fields

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Use a document builder to insert field with no format
Field field = builder.InsertField("= 2 + 3");

// We can format our field here instead of in the field code
FieldFormat format = field.Format;
format.NumericFormat = "$###.00";
field.Update();

// Apply a date/time format
field = builder.InsertField("DATE");
format = field.Format;
format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();

// Apply 2 general formats at the same time
field = builder.InsertField("= 25 + 33");
format = field.Format;
format.GeneralFormats.Add(GeneralFormat.LowercaseRoman);
format.GeneralFormats.Add(GeneralFormat.Upper);
field.Update();

int index = 0;
using (IEnumerator<GeneralFormat> generalFormatEnumerator = format.GeneralFormats.GetEnumerator())
{
    while (generalFormatEnumerator.MoveNext())
    {
        Console.WriteLine($"General format index {index++}: {generalFormatEnumerator.Current}");
    }
}

Assert.AreEqual("LVIII", field.Result);
Assert.AreEqual(2, format.GeneralFormats.Count);
Assert.AreEqual(GeneralFormat.LowercaseRoman, format.GeneralFormats[0]);

// Removing field formats
format.GeneralFormats.Remove(GeneralFormat.LowercaseRoman);
format.GeneralFormats.RemoveAt(0);
Assert.AreEqual(0, format.GeneralFormats.Count);
field.Update();

// Our field has no general formats left and is back to default form
Assert.AreEqual("58", field.Result);

See Also

GeneralFormatCollection Class | Aspose.Words.Fields Namespace


IBarcodeGenerator Interface

Public interface for barcode custom generator. Implementation should be provided by user.

For a list of all members of this type, see IBarcodeGenerator Members.

[Visual Basic]
Public Interface IBarcodeGenerator
[C#]
public interface IBarcodeGenerator

Remarks

Generator instance should be passed through the BarcodeGenerator property.

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IBarcodeGenerator Members | Aspose.Words.Fields Namespace


IBarcodeGenerator Members

IBarcodeGenerator overview

Public Instance Methods

GetBarcodeImage | Generate barcode image using the set of parameters (for DisplayBarcode field).
GetOldBarcodeImage | Generate barcode image using the set of parameters (for old-fashioned Barcode field).

See Also

IBarcodeGenerator Interface | Aspose.Words.Fields Namespace


IBarcodeGenerator Methods

The methods of the IBarcodeGenerator interface are listed below. For a complete list of IBarcodeGenerator interface members, see the IBarcodeGenerator Members topic.

Public Instance Methods

GetBarcodeImage | Generate barcode image using the set of parameters (for DisplayBarcode field).
GetOldBarcodeImage | Generate barcode image using the set of parameters (for old-fashioned Barcode field).

See Also

IBarcodeGenerator Interface | Aspose.Words.Fields Namespace


IBarcodeGenerator.GetBarcodeImage Method

Generate barcode image using the set of parameters (for DisplayBarcode field).

[Visual Basic]
Function GetBarcodeImage( _
ByVal parameters As BarcodeParameters _
) As Image
[C#]
Image GetBarcodeImage(
BarcodeParameters parameters
);

Parameters

parameters
The set of parameters

Return Value

Image representing generated barcode.

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

IBarcodeGenerator Interface | Aspose.Words.Fields Namespace


IBarcodeGenerator.GetOldBarcodeImage Method

Generate barcode image using the set of parameters (for old-fashioned Barcode field).

[Visual Basic]
Function GetOldBarcodeImage( _
ByVal parameters As BarcodeParameters _
) As Image
[C#]
Image GetOldBarcodeImage(
BarcodeParameters parameters
);

Parameters

parameters
The set of parameters

Return Value

Image representing generated barcode.

Example

Shows how to create barcode images using a barcode generator.

[C#]

public void BarcodeGenerator()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    Assert.IsNull(doc.FieldOptions.BarcodeGenerator);

    // Barcodes generated in this way will be images, and we can use a custom IBarcodeGenerator implementation to generate them
    doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();

    // Configure barcode parameters for a QR barcode
    BarcodeParameters barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "QR";
    barcodeParameters.BarcodeValue = "ABC123";
    barcodeParameters.BackgroundColor = "0xF8BD69";
    barcodeParameters.ForegroundColor = "0xB5413B";
    barcodeParameters.ErrorCorrectionLevel = "3";
    barcodeParameters.ScalingFactor = "250";
    barcodeParameters.SymbolHeight = "1000";
    barcodeParameters.SymbolRotation = "0";

    // Save the generated barcode image to the file system
    System.Drawing.Image img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.QR.jpg");

    // Insert the image into the document
    builder.InsertImage(img);

    // Configure barcode parameters for a EAN13 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "EAN13";
    barcodeParameters.BarcodeValue = "501234567890";
    barcodeParameters.DisplayText = true;
    barcodeParameters.PosCodeStyle = "CASE";
    barcodeParameters.FixCheckDigit = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.EAN13.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for a CODE39 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "CODE39";
    barcodeParameters.BarcodeValue = "12345ABCDE";
    barcodeParameters.AddStartStopChar = true;

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.CODE39.jpg");
    builder.InsertImage(img);

    // Configure barcode parameters for an ITF14 barcode
    barcodeParameters = new BarcodeParameters();
    barcodeParameters.BarcodeType = "ITF14";
    barcodeParameters.BarcodeValue = "09312345678907";
    barcodeParameters.CaseCodeStyle = "STD";

    img = doc.FieldOptions.BarcodeGenerator.GetBarcodeImage(barcodeParameters);
    img.Save(ArtifactsDir + "Field.BarcodeGenerator.ITF14.jpg");
    builder.InsertImage(img);

    doc.Save(ArtifactsDir + "Field.BarcodeGenerator.docx");
}

See Also

IBarcodeGenerator Interface | Aspose.Words.Fields Namespace


IFieldResultFormatter Interface

Implement this interface if you want to control how the field result is formatted.

For a list of all members of this type, see IFieldResultFormatter Members.

[Visual Basic]
Public Interface IFieldResultFormatter
[C#]
public interface IFieldResultFormatter

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IFieldResultFormatter Members | Aspose.Words.Fields Namespace


IFieldResultFormatter Members

IFieldResultFormatter overview

Public Instance Methods

Format | Overloaded. Called when Aspose.Words applies a capitalization format switch, i.e. \* Upper.
FormatDateTime | Called when Aspose.Words applies a date/time format switch, i.e. \@ "dd.MM.yyyy".
FormatNumeric | Called when Aspose.Words applies a numeric format switch, i.e. \# "#.##".

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace


IFieldResultFormatter Methods

The methods of the IFieldResultFormatter interface are listed below. For a complete list of IFieldResultFormatter interface members, see the IFieldResultFormatter Members topic.

Public Instance Methods

Format | Overloaded. Called when Aspose.Words applies a capitalization format switch, i.e. \* Upper.
FormatDateTime | Called when Aspose.Words applies a date/time format switch, i.e. \@ "dd.MM.yyyy".
FormatNumeric | Called when Aspose.Words applies a numeric format switch, i.e. \# "#.##".

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace


Format Method

Aspose.Words

IFieldResultFormatter.Format Method

Called when Aspose.Words applies a number format switch, i.e. \* Ordinal.

Overload List

Called when Aspose.Words applies a number format switch, i.e. \* Ordinal.

string Format(double,GeneralFormat);

Called when Aspose.Words applies a capitalization format switch, i.e. \* Upper.

string Format(string,GeneralFormat);

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace


IFieldResultFormatter.Format Method (Double, GeneralFormat)

Called when Aspose.Words applies a number format switch, i.e. \* Ordinal.

[Visual Basic]
Function Format( _
ByVal value As Double, _
ByVal format As GeneralFormat _
) As String
[C#]
string Format(
double value,
GeneralFormat format
);

Remarks

The implementation should return null to indicate that the default formatting should be applied.

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace | IFieldResultFormatter.Format Overload List


IFieldResultFormatter.Format Method (String, GeneralFormat)

Called when Aspose.Words applies a capitalization format switch, i.e. \* Upper.

[Visual Basic]
Function Format( _
ByVal value As String, _
ByVal format As GeneralFormat _
) As String
[C#]
string Format(
string value,
GeneralFormat format
);

Remarks

The implementation should return null to indicate that the default formatting should be applied.

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace | IFieldResultFormatter.Format Overload List


IFieldResultFormatter.FormatDateTime Method

Called when Aspose.Words applies a date/time format switch, i.e. \@ "dd.MM.yyyy".

[Visual Basic]
Function FormatDateTime( _
ByVal value As Date, _
ByVal format As String, _
ByVal calendarType As CalendarType _
) As String
[C#]
string FormatDateTime(
DateTime value,
string format,
CalendarType calendarType
);

Remarks

The implementation should return null to indicate that the default formatting should be applied.

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace


IFieldResultFormatter.FormatNumeric Method

Called when Aspose.Words applies a numeric format switch, i.e. \# "#.##".

[Visual Basic]
Function FormatNumeric( _
ByVal value As Double, _
ByVal format As String _
) As String
[C#]
string FormatNumeric(
double value,
string format
);

Remarks

The implementation should return null to indicate that the default formatting should be applied.

Example

Shows how to control how the field result is formatted.

[C#]

public void FieldResultFormatting()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    doc.FieldOptions.ResultFormatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:");

    // Insert a field with a numeric format
    builder.InsertField(" = 2 + 3 \\# $###", null);

    // Insert a field with a date/time format
    builder.InsertField("DATE \\@ \"d MMMM yyyy\"", null);

    // Insert a field with a general format
    builder.InsertField("QUOTE \"2\" \\* Ordinal", null);

    // Formats will be applied and recorded by the formatter during the field update
    doc.UpdateFields();
    ((FieldResultFormatter)doc.FieldOptions.ResultFormatter).PrintInvocations();

    // Our formatter has also overridden the formats that were originally applied in the fields
    Assert.AreEqual("$5", doc.Range.Fields[0].Result);
    Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: "));
    Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result);
}

/// <summary>
/// Custom IFieldResult implementation that applies formats and tracks format invocations
/// </summary>
private class FieldResultFormatter : IFieldResultFormatter
{
    public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat)
    {
        mNumberFormat = numberFormat;
        mDateFormat = dateFormat;
        mGeneralFormat = generalFormat;
    }

    public string FormatNumeric(double value, string format)
    {
        mNumberFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mNumberFormat) ? null : string.Format(mNumberFormat, value);
    }

    public string FormatDateTime(DateTime value, string format, CalendarType calendarType)
    {
        mDateFormatInvocations.Add(new object[] { value, format, calendarType });

        return string.IsNullOrEmpty(mDateFormat) ? null : string.Format(mDateFormat, value);
    }

    public string Format(string value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    public string Format(double value, GeneralFormat format)
    {
        return Format((object)value, format);
    }

    private string Format(object value, GeneralFormat format)
    {
        mGeneralFormatInvocations.Add(new object[] { value, format });

        return string.IsNullOrEmpty(mGeneralFormat) ? null : string.Format(mGeneralFormat, value);
    }

    public void PrintInvocations()
    {
        Console.WriteLine("Number format invocations ({0}):", mNumberFormatInvocations.Count);
        foreach (object[] s in mNumberFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }

        Console.WriteLine("Date format invocations ({0}):", mDateFormatInvocations.Count);
        foreach (object[] s in mDateFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1] + ", calendar type: " + s[2]);
        }

        Console.WriteLine("General format invocations ({0}):", mGeneralFormatInvocations.Count);
        foreach (object[] s in mGeneralFormatInvocations)
        {
            Console.WriteLine("\tValue: " + s[0] + ", original format: " + s[1]);
        }
    }

    private readonly string mNumberFormat;
    private readonly string mDateFormat;
    private readonly string mGeneralFormat;

    private readonly ArrayList mNumberFormatInvocations = new ArrayList();
    private readonly ArrayList mDateFormatInvocations = new ArrayList();
    private readonly ArrayList mGeneralFormatInvocations = new ArrayList();

}

See Also

IFieldResultFormatter Interface | Aspose.Words.Fields Namespace


IFieldUpdateCultureProvider Interface

When implemented, provides a CultureInfo object that should be used during the update of a particular field.

For a list of all members of this type, see IFieldUpdateCultureProvider Members.

[Visual Basic]
Public Interface IFieldUpdateCultureProvider
[C#]
public interface IFieldUpdateCultureProvider

Example

Shows how to specifying a culture defining date/time formatting on per field basis

[C#]

[Test]
public void DefineDateTimeFormatting()
{
    Document doc = new Document(MyDir + "Field.UpdateDateTimeFormatting.docx");

    doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
    // Set a provider that return a culture object specific for each particular field
    doc.FieldOptions.FieldUpdateCultureProvider = new FieldUpdateCultureProvider();

    FieldTime fieldDate = (FieldTime) doc.Range.Fields[0];
    if (fieldDate.LocaleId != (int) EditingLanguage.Russian)
        fieldDate.LocaleId = (int) EditingLanguage.Russian;

    doc.Save(ArtifactsDir + "Field.UpdateDateTimeFormatting.pdf");
}

/// <summary>
/// Provides a CultureInfo object that should be used during the update of a particular field.
/// </summary>
private class FieldUpdateCultureProvider : IFieldUpdateCultureProvider
{
    /// <summary>
    /// Returns a CultureInfo object to be used during the field's update.
    /// </summary>
    public CultureInfo GetCulture(string name, Field field)
    {
        switch (name)
        {
            case "ru-RU":
                CultureInfo culture = new CultureInfo(name, false);
                DateTimeFormatInfo format = culture.DateTimeFormat;

                format.MonthNames = new []{"месяц 1", "месяц 2", "месяц 3", "месяц 4", "месяц 5", "месяц 6", "месяц 7", "месяц 8", "месяц 9", "месяц 10", "месяц 11", "месяц 12", ""};
                format.MonthGenitiveNames = format.MonthNames;
                format.AbbreviatedMonthNames = new []{"мес 1", "мес 2", "мес 3", "мес 4", "мес 5", "мес 6", "мес 7", "мес 8", "мес 9", "мес 10", "мес 11", "мес 12", ""};
                format.AbbreviatedMonthGenitiveNames = format.AbbreviatedMonthNames;

                format.DayNames = new []{"день недели 7", "день недели 1", "день недели 2", "день недели 3", "день недели 4", "день недели 5", "день недели 6"};
                format.AbbreviatedDayNames = new []{"день 7", "день 1", "день 2", "день 3", "день 4", "день 5", "день 6"};
                format.ShortestDayNames = new []{"д7", "д1", "д2", "д3", "д4", "д5", "д6"};

                format.AMDesignator = "До полудня";
                format.PMDesignator = "После полудня";

                const string pattern = "yyyy MM (MMMM) dd (dddd) hh:mm:ss tt";
                format.LongDatePattern = pattern;
                format.LongTimePattern = pattern;
                format.ShortDatePattern = pattern;
                format.ShortTimePattern = pattern;

                return culture;
            case "en-US":
                return new CultureInfo(name, false);
            default:
                return null;
        }
    }
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IFieldUpdateCultureProvider Members | Aspose.Words.Fields Namespace


IFieldUpdateCultureProvider Members

IFieldUpdateCultureProvider overview

Public Instance Methods

GetCulture Returns a CultureInfo object to be used during the field's update.

See Also

IFieldUpdateCultureProvider Interface | Aspose.Words.Fields Namespace


IFieldUpdateCultureProvider Methods

The methods of the IFieldUpdateCultureProvider interface are listed below. For a complete list of IFieldUpdateCultureProvider interface members, see the IFieldUpdateCultureProvider Members topic.

Public Instance Methods

GetCulture Returns a CultureInfo object to be used during the field's update.

See Also

IFieldUpdateCultureProvider Interface | Aspose.Words.Fields Namespace


IFieldUpdateCultureProvider.GetCulture Method

Returns a CultureInfo object to be used during the field's update.

[Visual Basic]
Function GetCulture( _
ByVal culture As String, _
ByVal field As Field _
) As CultureInfo
[C#]
CultureInfo GetCulture(
string culture,
Field field
);

Parameters

culture
The name of the culture requested for the field being updated.
field
The field being updated.

Return Value

The culture object that should be used for the field's update.

See Also

IFieldUpdateCultureProvider Interface | Aspose.Words.Fields Namespace


IFieldUserPromptRespondent Interface

Represents the respondent to user prompts during field update.

For a list of all members of this type, see IFieldUserPromptRespondent Members.

[Visual Basic]
Public Interface IFieldUserPromptRespondent
[C#]
public interface IFieldUserPromptRespondent

Remarks

The ASK and FILLIN fields are the examples of fields that prompt the user for some response. Implement this interface and assign it to the UserPromptRespondent property to establish interaction between field update and the user.

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IFieldUserPromptRespondent Members | Aspose.Words.Fields Namespace


IFieldUserPromptRespondent Members

IFieldUserPromptRespondent overview

Public Instance Methods

Respond When implemented, returns a response from the user on prompting. Your implementation should return null to indicate that the user has not responded to the prompt (i.e. the user has pressed the Cancel button in the prompt window).

See Also

IFieldUserPromptRespondent Interface | Aspose.Words.Fields Namespace


IFieldUserPromptRespondent Methods

The methods of the IFieldUserPromptRespondent interface are listed below. For a complete list of IFieldUserPromptRespondent interface members, see the IFieldUserPromptRespondent Members topic.

Public Instance Methods

Respond When implemented, returns a response from the user on prompting. Your implementation should return null to indicate that the user has not responded to the prompt (i.e. the user has pressed the Cancel button in the prompt window).

See Also

IFieldUserPromptRespondent Interface | Aspose.Words.Fields Namespace


IFieldUserPromptRespondent.Respond Method

When implemented, returns a response from the user on prompting. Your implementation should return null to indicate that the user has not responded to the prompt (i.e. the user has pressed the Cancel button in the prompt window).

[Visual Basic]
Function Respond( _
ByVal promptText As String, _
ByVal defaultResponse As String _
) As String
[C#]
string Respond(
string promptText,
string defaultResponse
);

Parameters

promptText
Prompt text (i.e. title of the prompt window).
defaultResponse
Default user response (i.e. initial value contained in the prompt window).

Return Value

User response (i.e. confirmed value contained in the prompt window).

Example

Shows how to create an ASK field and set its properties.

[C#]

[Test]
public void FieldAsk()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Place a field where the response to our ASK field will be placed
    FieldRef fieldRef = (FieldRef)builder.InsertField(FieldType.FieldRef, true);
    fieldRef.BookmarkName = "MyAskField";
    builder.Writeln();

    // Insert the ASK field and edit its properties, making sure to reference our REF field
    FieldAsk fieldAsk = (FieldAsk)builder.InsertField(FieldType.FieldAsk, true);
    fieldAsk.BookmarkName = "MyAskField";
    fieldAsk.PromptText = "Please provide a response for this ASK field";
    fieldAsk.DefaultResponse = "Response from within the field.";
    fieldAsk.PromptOnceOnMailMerge = true;
    builder.Writeln();

    // ASK fields apply the default response to their respective REF fields during a mail merge
    System.Data.DataTable table = new System.Data.DataTable("My Table");
    table.Columns.Add("Column 1");
    table.Rows.Add("Row 1");
    table.Rows.Add("Row 2");

    FieldMergeField fieldMergeField = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, true);
    fieldMergeField.FieldName = "Column 1";

    // We can modify or override the default response in our ASK fields with a custom prompt responder, which will take place during a mail merge
    doc.FieldOptions.UserPromptRespondent = new MyPromptRespondent();
    doc.MailMerge.Execute(table);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Fields.AskField.docx");

    Assert.AreEqual(
        " ASK  MyAskField \"Please provide a response for this ASK field\" \\d \"Response from within the field.\" \\o",
        fieldAsk.GetFieldCode());

    Assert.AreEqual("Please provide a response for this ASK field", fieldAsk.PromptText); // ExSkip
}

/// <summary>
/// IFieldUserPromptRespondent implementation that appends a line to the default response of an ASK field during a mail merge
/// </summary>
private class MyPromptRespondent : IFieldUserPromptRespondent
{
    public string Respond(string promptText, string defaultResponse)
    {
        return "Response from MyPromptRespondent. " + defaultResponse;
    }
}

See Also

IFieldUserPromptRespondent Interface | Aspose.Words.Fields Namespace


MergeFieldImageDimension Class

Represents an image dimension (i.e. the width or the height) used across a mail merge process.

For a list of all members of this type, see MergeFieldImageDimension Members.

System.Object
Aspose.Words.Fields.MergeFieldImageDimension

[Visual Basic]
Public Class MergeFieldImageDimension
[C#]
public class MergeFieldImageDimension

Remarks

To indicate that the image should be inserted with its original dimension during a mail merge, you should assign a negative value to the Value property.

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MergeFieldImageDimension Members | Aspose.Words.Fields Namespace | MergeFieldImageDimensionUnit


MergeFieldImageDimension Members

MergeFieldImageDimension overview

Public Instance Constructors

MergeFieldImageDimension Overloaded. Initializes a new instance of the MergeFieldImageDimension class.

Public Instance Properties

Unit | The unit.
Value | The value.

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace | MergeFieldImageDimensionUnit


MergeFieldImageDimension Constructor

Creates an image dimension instance with the given value in points.

Overload List

Creates an image dimension instance with the given value in points.

public MergeFieldImageDimension(double);

Creates an image dimension instance with the given value and the given unit.

public MergeFieldImageDimension(double,MergeFieldImageDimensionUnit);

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace


MergeFieldImageDimension Constructor (Double)

Creates an image dimension instance with the given value in points.

[Visual Basic]
Overloads Public Sub New( _
ByVal value As Double _
)
[C#]
public MergeFieldImageDimension(
double value
);

Parameters

value
The value.

Remarks

You should use a negative value to indicate that the original value of the corresponding image dimension should be applied.

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace | MergeFieldImageDimension Constructor Overload List


MergeFieldImageDimension Constructor (Double, MergeFieldImageDimensionUnit)

Creates an image dimension instance with the given value and the given unit.

[Visual Basic]
Overloads Public Sub New( _
ByVal value As Double, _
ByVal unit As MergeFieldImageDimensionUnit _
)
[C#]
public MergeFieldImageDimension(
double value,
MergeFieldImageDimensionUnit unit
);

Parameters

value
The value.
unit
The unit.

Remarks

You should use a negative value to indicate that the original value of the corresponding image dimension should be applied.

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace | MergeFieldImageDimension Constructor Overload List


MergeFieldImageDimension Properties

The properties of the MergeFieldImageDimension class are listed below. For a complete list of MergeFieldImageDimension class members, see the MergeFieldImageDimension Members topic.

Public Instance Properties

Unit | The unit.
Value | The value.

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace | MergeFieldImageDimensionUnit


Unit Property

Aspose.Words

MergeFieldImageDimension.Unit Property

The unit.

[Visual Basic]
Public Property Unit As MergeFieldImageDimensionUnit
[C#]
public MergeFieldImageDimensionUnit Unit {get; set;}

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace


Value Property

Aspose.Words

MergeFieldImageDimension.Value Property

The value.

[Visual Basic]
Public Property Value As Double
[C#]
public double Value {get; set;}

Remarks

You should use a negative value to indicate that the original value of the corresponding image dimension should be applied.

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

MergeFieldImageDimension Class | Aspose.Words.Fields Namespace


MergeFieldImageDimensionUnit Enumeration

Specifies an unit of an image dimension (i.e. the width or the height) used across a mail merge process.

[Visual Basic]
Public Enum MergeFieldImageDimensionUnit
[C#]
public enum MergeFieldImageDimensionUnit

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

Members

Member Name | Description | Value
Point | The point (i.e. 1/72 inch). | 0
Percent | The percent of the original image dimension value. | 1

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fields Namespace


TextFormFieldType Enumeration

Specifies the type of a text form field.

[Visual Basic]
Public Enum TextFormFieldType
[C#]
public enum TextFormFieldType

Example

Builds a sample form to fill.

[C#]

DocumentBuilder builder = new DocumentBuilder();

// Insert a text form field for input a name.
builder.InsertTextInput("", TextFormFieldType.Regular, "", "Enter your name here", 30);

// Insert two blank lines.
builder.Writeln("");
builder.Writeln("");

string[] items =
{
    "-- Select your favorite footwear --", "Sneakers", "Oxfords", "Flip-flops", "Other",
    "I prefer to be barefoot"
};

// Insert a combo box to select a footwear type.
builder.InsertComboBox("", items, 0);

// Insert 2 blank lines.
builder.Writeln("");
builder.Writeln("");

builder.Document.Save(ArtifactsDir + "DocumentBuilder.CreateForm.doc");

Members

Member Name | Description | Value
Regular | The text form field can contain any text. | 0
Number | The text form field can contain only numbers. | 1
Date | The text form field can contain only a valid date value. | 2
CurrentDate | The text form field value is the current date when the field is updated. | 3
CurrentTime | The text form field value is the current time when the field is updated. | 4
Calculated | The text form field value is calculated from the expression specified in the TextInputDefault property. | 5

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fields Namespace


ToaCategories Class

Represents a table of authorities categories.

For a list of all members of this type, see ToaCategories Members.

System.Object
Aspose.Words.Fields.ToaCategories

[Visual Basic]
Public Class ToaCategories
[C#]
public class ToaCategories

Example

Shows how to specify a table of authorities categories for a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// There are default category values we can use, or we can make our own like this
ToaCategories toaCategories = new ToaCategories();
doc.FieldOptions.ToaCategories = toaCategories;

toaCategories[1] = "My Category 1"; // Replaces default value "Cases"
toaCategories[2] = "My Category 2"; // Replaces default value "Statutes"

// Even if we changed the categories in the FieldOptions object, the default categories are still available here
Assert.AreEqual("Cases", ToaCategories.DefaultCategories[1]);
Assert.AreEqual("Statutes", ToaCategories.DefaultCategories[2]);

// Insert 2 tables of authorities, one per category
builder.InsertField("TOA \\c 1 \\h", null);
builder.InsertField("TOA \\c 2 \\h", null);
builder.InsertBreak(BreakType.PageBreak);

// Insert table of authorities entries across 2 categories
builder.InsertField("TA \\c 2 \\l \"entry 1\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 1 \\l \"entry 2\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 2 \\l \"entry 3\"");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TableOfAuthorities.Categories.docx");

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ToaCategories Members | Aspose.Words.Fields Namespace


ToaCategories Members

ToaCategories overview

Public Static (Shared) Properties

DefaultCategories Gets the default table of authorities categories.

Public Instance Constructors

ToaCategories Constructor Initializes a new instance of the ToaCategories class.

Public Instance Properties

Item Gets or sets the category heading by category number.

See Also

ToaCategories Class | Aspose.Words.Fields Namespace


ToaCategories Constructor

Initializes a new instance of the ToaCategories class.

[Visual Basic]
Public Sub New()
[C#]
public ToaCategories();

See Also

ToaCategories Class | Aspose.Words.Fields Namespace


ToaCategories Properties

The properties of the ToaCategories class are listed below. For a complete list of ToaCategories class members, see the ToaCategories Members topic.

Public Static (Shared) Properties

DefaultCategories Gets the default table of authorities categories.

Public Instance Properties

Item Gets or sets the category heading by category number.

See Also

ToaCategories Class | Aspose.Words.Fields Namespace


DefaultCategories Property

Aspose.Words

ToaCategories.DefaultCategories Property

Gets the default table of authorities categories.

[Visual Basic]
Public Shared ReadOnly Property DefaultCategories As ToaCategories
[C#]
public static ToaCategories DefaultCategories {get;}

Remarks

Use the ToaCategories property to specify table of authorities categories for a single document.

Example

Shows how to specify a table of authorities categories for a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// There are default category values we can use, or we can make our own like this
ToaCategories toaCategories = new ToaCategories();
doc.FieldOptions.ToaCategories = toaCategories;

toaCategories[1] = "My Category 1"; // Replaces default value "Cases"
toaCategories[2] = "My Category 2"; // Replaces default value "Statutes"

// Even if we changed the categories in the FieldOptions object, the default categories are still available here
Assert.AreEqual("Cases", ToaCategories.DefaultCategories[1]);
Assert.AreEqual("Statutes", ToaCategories.DefaultCategories[2]);

// Insert 2 tables of authorities, one per category
builder.InsertField("TOA \\c 1 \\h", null);
builder.InsertField("TOA \\c 2 \\h", null);
builder.InsertBreak(BreakType.PageBreak);

// Insert table of authorities entries across 2 categories
builder.InsertField("TA \\c 2 \\l \"entry 1\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 1 \\l \"entry 2\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 2 \\l \"entry 3\"");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TableOfAuthorities.Categories.docx");

See Also

ToaCategories Class | Aspose.Words.Fields Namespace


Item Property

Aspose.Words

ToaCategories.Item Property

Gets or sets the category heading by category number.

[Visual Basic]
Public Default Property Item( _
ByVal number As Integer _
) As String
[C#]
public string this[
int number
] {get; set;}

Example

Shows how to specify a table of authorities categories for a document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// There are default category values we can use, or we can make our own like this
ToaCategories toaCategories = new ToaCategories();
doc.FieldOptions.ToaCategories = toaCategories;

toaCategories[1] = "My Category 1"; // Replaces default value "Cases"
toaCategories[2] = "My Category 2"; // Replaces default value "Statutes"

// Even if we changed the categories in the FieldOptions object, the default categories are still available here
Assert.AreEqual("Cases", ToaCategories.DefaultCategories[1]);
Assert.AreEqual("Statutes", ToaCategories.DefaultCategories[2]);

// Insert 2 tables of authorities, one per category
builder.InsertField("TOA \\c 1 \\h", null);
builder.InsertField("TOA \\c 2 \\h", null);
builder.InsertBreak(BreakType.PageBreak);

// Insert table of authorities entries across 2 categories
builder.InsertField("TA \\c 2 \\l \"entry 1\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 1 \\l \"entry 2\"");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertField("TA \\c 2 \\l \"entry 3\"");

doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.TableOfAuthorities.Categories.docx");

See Also

ToaCategories Class | Aspose.Words.Fields Namespace


UserInformation Class

Specifies information about the user.

For a list of all members of this type, see UserInformation Members.

System.Object
Aspose.Words.Fields.UserInformation

[Visual Basic]
Public Class UserInformation
[C#]
public class UserInformation

Example

Shows how to set user details and display them with fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set user information
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
userInformation.Initials = "J. D.";
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Insert fields that reference our user information
Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result);
Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result);

// The field options object also has a static default user value that fields from many documents can refer to
UserInformation.DefaultUser.Name = "Default User";
UserInformation.DefaultUser.Initials = "D. U.";
UserInformation.DefaultUser.Address = "One Microsoft Way";
doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result);
Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result);

Requirements

Namespace: Aspose.Words.Fields

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

UserInformation Members | Aspose.Words.Fields Namespace


UserInformation Members

UserInformation overview

Public Static (Shared) Properties

DefaultUser Default user information.

Public Instance Constructors

UserInformation Constructor Initializes a new instance of the UserInformation class.

Public Instance Properties

Address | Gets or sets the user's postal address.
Initials | Gets or sets the user's initials.
Name | Gets or sets the user's name.

See Also

UserInformation Class | Aspose.Words.Fields Namespace


UserInformation Constructor

Initializes a new instance of the UserInformation class.

[Visual Basic]
Public Sub New()
[C#]
public UserInformation();

See Also

UserInformation Class | Aspose.Words.Fields Namespace


UserInformation Properties

The properties of the UserInformation class are listed below. For a complete list of UserInformation class members, see the UserInformation Members topic.

Public Static (Shared) Properties

DefaultUser Default user information.

Public Instance Properties

Address | Gets or sets the user's postal address.
Initials | Gets or sets the user's initials.
Name | Gets or sets the user's name.

See Also

UserInformation Class | Aspose.Words.Fields Namespace


Address Property

Aspose.Words

UserInformation.Address Property

Gets or sets the user's postal address.

[Visual Basic]
Public Property Address As String
[C#]
public string Address {get; set;}

Example

Shows how to set user details and display them with fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set user information
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
userInformation.Initials = "J. D.";
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Insert fields that reference our user information
Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result);
Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result);

// The field options object also has a static default user value that fields from many documents can refer to
UserInformation.DefaultUser.Name = "Default User";
UserInformation.DefaultUser.Initials = "D. U.";
UserInformation.DefaultUser.Address = "One Microsoft Way";
doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result);
Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result);

See Also

UserInformation Class | Aspose.Words.Fields Namespace


DefaultUser Property

Aspose.Words

UserInformation.DefaultUser Property

Default user information.

[Visual Basic]
Public Shared ReadOnly Property DefaultUser As UserInformation
[C#]
public static UserInformation DefaultUser {get;}

Remarks

Use the CurrentUser property to specify user information for single document.

Example

Shows how to set user details and display them with fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set user information
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
userInformation.Initials = "J. D.";
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Insert fields that reference our user information
Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result);
Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result);

// The field options object also has a static default user value that fields from many documents can refer to
UserInformation.DefaultUser.Name = "Default User";
UserInformation.DefaultUser.Initials = "D. U.";
UserInformation.DefaultUser.Address = "One Microsoft Way";
doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result);
Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result);

See Also

UserInformation Class | Aspose.Words.Fields Namespace


Initials Property

Aspose.Words

UserInformation.Initials Property

Gets or sets the user's initials.

[Visual Basic]
Public Property Initials As String
[C#]
public string Initials {get; set;}

Example

Shows how to set user details and display them with fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set user information
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
userInformation.Initials = "J. D.";
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Insert fields that reference our user information
Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result);
Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result);

// The field options object also has a static default user value that fields from many documents can refer to
UserInformation.DefaultUser.Name = "Default User";
UserInformation.DefaultUser.Initials = "D. U.";
UserInformation.DefaultUser.Address = "One Microsoft Way";
doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result);
Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result);

See Also

UserInformation Class | Aspose.Words.Fields Namespace


Name Property

Aspose.Words

UserInformation.Name Property

Gets or sets the user's name.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Example

Shows how to set user details and display them with fields.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set user information
UserInformation userInformation = new UserInformation();
userInformation.Name = "John Doe";
userInformation.Initials = "J. D.";
userInformation.Address = "123 Main Street";
doc.FieldOptions.CurrentUser = userInformation;

// Insert fields that reference our user information
Assert.AreEqual(userInformation.Name, builder.InsertField(" USERNAME ").Result);
Assert.AreEqual(userInformation.Initials, builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual(userInformation.Address, builder.InsertField(" USERADDRESS ").Result);

// The field options object also has a static default user value that fields from many documents can refer to
UserInformation.DefaultUser.Name = "Default User";
UserInformation.DefaultUser.Initials = "D. U.";
UserInformation.DefaultUser.Address = "One Microsoft Way";
doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

Assert.AreEqual("Default User", builder.InsertField(" USERNAME ").Result);
Assert.AreEqual("D. U.", builder.InsertField(" USERINITIALS ").Result);
Assert.AreEqual("One Microsoft Way", builder.InsertField(" USERADDRESS ").Result);

See Also

UserInformation Class | Aspose.Words.Fields Namespace


Aspose.Words.Fonts

Aspose.Words

Aspose.Words.Fonts Namespace

The Aspose.Words.Fonts namespace provides classes and enumerations to access information about fonts used in a document.

Namespace hierarchy

Classes

Class | Description
DefaultFontSubstitutionRule | Default font substitution rule.
FileFontSource | Represents the single TrueType font file stored in the file system.
FolderFontSource | Represents the folder that contains TrueType font files.
FontConfigSubstitutionRule | Font config substitution rule.
FontFallbackSettings | Specifies font fallback mechanism settings.
FontInfo | Specifies information about a font used in the document.
FontInfoCollection | Represents a collection of fonts used in a document.
FontInfoSubstitutionRule | Font info substitution rule.
FontSettings | Specifies font settings for a document.
FontSourceBase | This is an abstract base class for the classes that allow the user to specify various font sources.
FontSubstitutionRule | This is an abstract base class for the font substitution rule.
FontSubstitutionSettings | Specifies font substitution mechanism settings.
MemoryFontSource | Represents the single TrueType font file stored in memory.
PhysicalFontInfo | Specifies information about physical font available to Aspose.Words font engine.
StreamFontSource | Base class for user-defined stream font source.
SystemFontSource | Represents all TrueType fonts installed to the system.
TableSubstitutionRule | Table font substitution rule.

Enumerations

Enumeration | Description
EmbeddedFontFormat | Specifies format of particular embedded font inside FontInfo object. When saving a document to a file, only embedded fonts of corresponding format are written down.
EmbeddedFontStyle | Specifies the style of an embedded font inside a FontInfo object.
FontFamily | Represents the font family.
FontPitch | Represents the font pitch.
FontSourceType | Specifies the type of a font source.


DefaultFontSubstitutionRule Class

Default font substitution rule.

For a list of all members of this type, see DefaultFontSubstitutionRule Members.

System.Object
Aspose.Words.Fonts.FontSubstitutionRule
Aspose.Words.Fonts.DefaultFontSubstitutionRule

[Visual Basic]
Public Class DefaultFontSubstitutionRule
Inherits FontSubstitutionRule
[C#]
public class DefaultFontSubstitutionRule : FontSubstitutionRule

Remarks

This rule defines single default font name to be used for substitution if the original font is not available.

Example

Shows how to set the default font substitution rule.

[C#]

// Create a blank document and a new FontSettings property
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Get the default substitution rule within FontSettings, which will be enabled by default and will substitute all missing fonts with "Times New Roman"
DefaultFontSubstitutionRule defaultFontSubstitutionRule = fontSettings.SubstitutionSettings.DefaultFontSubstitution;
Assert.True(defaultFontSubstitutionRule.Enabled);
Assert.AreEqual("Times New Roman", defaultFontSubstitutionRule.DefaultFontName);

// Set the default font substitute to "Courier New"
defaultFontSubstitutionRule.DefaultFontName = "Courier New";

// Using a document builder, add some text in a font that we don't have to see the substitution take place,
// and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Font.Name = "Missing Font";
builder.Writeln("Line written in a missing font, which will be substituted with Courier New.");

doc.Save(ArtifactsDir + "Font.DefaultFontSubstitutionRule.pdf");

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DefaultFontSubstitutionRule Members | Aspose.Words.Fonts Namespace


DefaultFontSubstitutionRule Members

DefaultFontSubstitutionRule overview

Public Instance Properties

DefaultFontName | Gets or sets the default font name.
Enabled (inherited from FontSubstitutionRule) | Specifies whether the rule is enabled or not.

See Also

DefaultFontSubstitutionRule Class | Aspose.Words.Fonts Namespace


DefaultFontSubstitutionRule Properties

The properties of the DefaultFontSubstitutionRule class are listed below. For a complete list of DefaultFontSubstitutionRule class members, see the DefaultFontSubstitutionRule Members topic.

Public Instance Properties

DefaultFontName | Gets or sets the default font name.
Enabled (inherited from FontSubstitutionRule) | Specifies whether the rule is enabled or not.

See Also

DefaultFontSubstitutionRule Class | Aspose.Words.Fonts Namespace


DefaultFontName Property

Aspose.Words

DefaultFontSubstitutionRule.DefaultFontName Property

Gets or sets the default font name.

[Visual Basic]
Public Property DefaultFontName As String
[C#]
public string DefaultFontName {get; set;}

Remarks

The default value is 'Times New Roman'.

Example

Demonstrates how to specify what font to substitute for a missing font during rendering.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// If the default font defined here cannot be found during rendering then the closest font on the machine is used instead.
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial Unicode MS";

// Now the set default font is used in place of any missing fonts during any rendering calls.
doc.Save(ArtifactsDir + "Rendering.SetDefaultFont.pdf");
doc.Save(ArtifactsDir + "Rendering.SetDefaultFont.xps");
Shows how to set the default font substitution rule.
[C#]

// Create a blank document and a new FontSettings property
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Get the default substitution rule within FontSettings, which will be enabled by default and will substitute all missing fonts with "Times New Roman"
DefaultFontSubstitutionRule defaultFontSubstitutionRule = fontSettings.SubstitutionSettings.DefaultFontSubstitution;
Assert.True(defaultFontSubstitutionRule.Enabled);
Assert.AreEqual("Times New Roman", defaultFontSubstitutionRule.DefaultFontName);

// Set the default font substitute to "Courier New"
defaultFontSubstitutionRule.DefaultFontName = "Courier New";

// Using a document builder, add some text in a font that we don't have to see the substitution take place,
// and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Font.Name = "Missing Font";
builder.Writeln("Line written in a missing font, which will be substituted with Courier New.");

doc.Save(ArtifactsDir + "Font.DefaultFontSubstitutionRule.pdf");

See Also

DefaultFontSubstitutionRule Class | Aspose.Words.Fonts Namespace


EmbeddedFontFormat Enumeration

Specifies format of particular embedded font inside FontInfo object.

When saving a document to a file, only embedded fonts of corresponding format are written down.

[Visual Basic]
Public Enum EmbeddedFontFormat
[C#]
public enum EmbeddedFontFormat

Example

Shows how to extract embedded font from a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");
// Let's get the font we are interested in
FontInfo mittelschriftInfo = doc.FontInfos[2];
// We can now extract this embedded font
byte[] embeddedFontBytes = mittelschriftInfo.GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular);
Assert.IsNotNull(embeddedFontBytes);
// Then we can save the font to our directory
File.WriteAllBytes(ArtifactsDir + "Alte DIN 1451 Mittelschrift.ttf", embeddedFontBytes);

// If we want to extract a font from a .doc as opposed to a .docx, we need to make sure to set the appropriate embedded font format
doc = new Document(MyDir + "Font.Embedded.doc");

Assert.IsNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular));
Assert.IsNotNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.EmbeddedOpenType, EmbeddedFontStyle.Regular));

Members

Member Name | Description | Value
EmbeddedOpenType | Specifies Embedded OpenType (EOT) File Format. This format of embedded fonts used in DOC files. | 0
OpenType | Specifies font, embedded as plain copy of OpenType (TrueType) font file. This format of embedded fonts used in Open Office XML format, including DOCX files. | 1

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fonts Namespace


EmbeddedFontStyle Enumeration

Specifies the style of an embedded font inside a FontInfo object.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum EmbeddedFontStyle
[C#]
public enum EmbeddedFontStyle

Example

Shows how to extract embedded font from a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");
// Let's get the font we are interested in
FontInfo mittelschriftInfo = doc.FontInfos[2];
// We can now extract this embedded font
byte[] embeddedFontBytes = mittelschriftInfo.GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular);
Assert.IsNotNull(embeddedFontBytes);
// Then we can save the font to our directory
File.WriteAllBytes(ArtifactsDir + "Alte DIN 1451 Mittelschrift.ttf", embeddedFontBytes);

// If we want to extract a font from a .doc as opposed to a .docx, we need to make sure to set the appropriate embedded font format
doc = new Document(MyDir + "Font.Embedded.doc");

Assert.IsNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular));
Assert.IsNotNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.EmbeddedOpenType, EmbeddedFontStyle.Regular));

Members

Member Name | Description | Value
Regular | Specifies the Regular embedded font. | 0
Bold | Specifies the Bold embedded font. | 1
Italic | Specifies the Italic embedded font. | 2
BoldItalic | Specifies the Bold-Italic embedded font. | 3

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fonts Namespace


FileFontSource Class

Represents the single TrueType font file stored in the file system.

For a list of all members of this type, see FileFontSource Members.

System.Object
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.FileFontSource

[Visual Basic]
Public Class FileFontSource
Inherits FontSourceBase
[C#]
public class FileFontSource : FontSourceBase

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FileFontSource Members | Aspose.Words.Fonts Namespace


FileFontSource Members

FileFontSource overview

Public Instance Constructors

FileFontSource Overloaded. Initializes a new instance of the FileFontSource class.

Public Instance Properties

FilePath | Path to the font file.
Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) Returns list of fonts available via this source.

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


FileFontSource Constructor

Ctor.

Overload List

Ctor.

public FileFontSource(string);

Ctor.

public FileFontSource(string,int);

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


FileFontSource Constructor (String)

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal filePath As String _
)
[C#]
public FileFontSource(
string filePath
);

Parameters

filePath
Path to font file.

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace | FileFontSource Constructor Overload List


FileFontSource Constructor (String, Int32)

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal filePath As String, _
ByVal priority As Integer _
)
[C#]
public FileFontSource(
string filePath,
int priority
);

Parameters

filePath
Path to font file.
priority
Font source priority. See the Priority property description for more information.

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace | FileFontSource Constructor Overload List


FileFontSource Properties

The properties of the FileFontSource class are listed below. For a complete list of FileFontSource class members, see the FileFontSource Members topic.

Public Instance Properties

FilePath | Path to the font file.
Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


FilePath Property

Aspose.Words

FileFontSource.FilePath Property

Path to the font file.

[Visual Basic]
Public ReadOnly Property FilePath As String
[C#]
public string FilePath {get;}

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


Type Property

Aspose.Words

FileFontSource.Type Property

Returns the type of the font source.

[Visual Basic]
Overrides Public ReadOnly Property Type As FontSourceType
[C#]
public override FontSourceType Type {get;}

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


FolderFontSource Class

Represents the folder that contains TrueType font files.

For a list of all members of this type, see FolderFontSource Members.

System.Object
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.FolderFontSource

[Visual Basic]
Public Class FolderFontSource
Inherits FontSourceBase
[C#]
public class FolderFontSource : FontSourceBase

Example

Shows how to create a folder font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a folder that contains font files
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false, 1);

// Add that source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

Assert.AreEqual(MyDir + "MyFonts", folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FolderFontSource Members | Aspose.Words.Fonts Namespace


FolderFontSource Members

FolderFontSource overview

Public Instance Constructors

FolderFontSource Overloaded. Initializes a new instance of the FolderFontSource class.

Public Instance Properties

FolderPath | Path to the folder.
Priority (inherited from FontSourceBase) | Returns the font source priority.
ScanSubfolders | Determines whether or not to scan the subfolders.
Type | Returns the type of the font source.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) Returns list of fonts available via this source.

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


FolderFontSource Constructor

Ctor.

Overload List

Ctor.

public FolderFontSource(string,bool);

Ctor.

public FolderFontSource(string,bool,int);

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


FolderFontSource Constructor (String, Boolean)

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal folderPath As String, _
ByVal scanSubfolders As Boolean _
)
[C#]
public FolderFontSource(
string folderPath,
bool scanSubfolders
);

Parameters

folderPath
Path to folder.
scanSubfolders
Determines whether or not to scan subfolders.

Example

Shows how to create a folder font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a folder that contains font files
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false, 1);

// Add that source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

Assert.AreEqual(MyDir + "MyFonts", folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace | FolderFontSource Constructor Overload List


FolderFontSource Constructor (String, Boolean, Int32)

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal folderPath As String, _
ByVal scanSubfolders As Boolean, _
ByVal priority As Integer _
)
[C#]
public FolderFontSource(
string folderPath,
bool scanSubfolders,
int priority
);

Parameters

folderPath
Path to folder.
scanSubfolders
Determines whether or not to scan subfolders.
priority
Font source priority. See the Priority property description for more information.

Example

Shows how to create a folder font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a folder that contains font files
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false, 1);

// Add that source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

Assert.AreEqual(MyDir + "MyFonts", folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace | FolderFontSource Constructor Overload List


FolderFontSource Properties

The properties of the FolderFontSource class are listed below. For a complete list of FolderFontSource class members, see the FolderFontSource Members topic.

Public Instance Properties

FolderPath | Path to the folder.
Priority (inherited from FontSourceBase) | Returns the font source priority.
ScanSubfolders | Determines whether or not to scan the subfolders.
Type | Returns the type of the font source.

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


FolderPath Property

Aspose.Words

FolderFontSource.FolderPath Property

Path to the folder.

[Visual Basic]
Public ReadOnly Property FolderPath As String
[C#]
public string FolderPath {get;}

Example

Shows how to create a folder font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a folder that contains font files
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false, 1);

// Add that source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

Assert.AreEqual(MyDir + "MyFonts", folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


ScanSubfolders Property

Aspose.Words

FolderFontSource.ScanSubfolders Property

Determines whether or not to scan the subfolders.

[Visual Basic]
Public ReadOnly Property ScanSubfolders As Boolean
[C#]
public bool ScanSubfolders {get;}

Example

Shows how to create a folder font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a folder that contains font files
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false, 1);

// Add that source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

Assert.AreEqual(MyDir + "MyFonts", folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


Type Property

Aspose.Words

FolderFontSource.Type Property

Returns the type of the font source.

[Visual Basic]
Overrides Public ReadOnly Property Type As FontSourceType
[C#]
public override FontSourceType Type {get;}

Example

Shows how to create a folder font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a folder that contains font files
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false, 1);

// Add that source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

Assert.AreEqual(MyDir + "MyFonts", folderFontSource.FolderPath);
Assert.AreEqual(false, folderFontSource.ScanSubfolders);
Assert.AreEqual(FontSourceType.FontsFolder, folderFontSource.Type);
Assert.AreEqual(1, folderFontSource.Priority);

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


FontConfigSubstitutionRule Class

Font config substitution rule.

For a list of all members of this type, see FontConfigSubstitutionRule Members.

System.Object
Aspose.Words.Fonts.FontSubstitutionRule
Aspose.Words.Fonts.FontConfigSubstitutionRule

[Visual Basic]
Public Class FontConfigSubstitutionRule
Inherits FontSubstitutionRule
[C#]
public class FontConfigSubstitutionRule : FontSubstitutionRule

Remarks

This rule uses fontconfig utility on Linux (and other Unix-like) platforms to get the substitution if the original font is not available.

If fontconfig utility is not available then this rule will be ignored.

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontConfigSubstitutionRule Members | Aspose.Words.Fonts Namespace


FontConfigSubstitutionRule Members

FontConfigSubstitutionRule overview

Public Instance Properties

Enabled Specifies whether the rule is enabled or not.

Public Instance Methods

IsFontConfigAvailable | Check if fontconfig utility is available or not.
ResetCache | Resets the cache of fontconfig calling results.

See Also

FontConfigSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontConfigSubstitutionRule Properties

The properties of the FontConfigSubstitutionRule class are listed below. For a complete list of FontConfigSubstitutionRule class members, see the FontConfigSubstitutionRule Members topic.

Public Instance Properties

Enabled Specifies whether the rule is enabled or not.

See Also

FontConfigSubstitutionRule Class | Aspose.Words.Fonts Namespace


Enabled Property

Aspose.Words

FontConfigSubstitutionRule.Enabled Property

Specifies whether the rule is enabled or not.

[Visual Basic]
Overrides Public Property Enabled As Boolean
[C#]
public override bool Enabled {set;}

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}

See Also

FontConfigSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontConfigSubstitutionRule Methods

The methods of the FontConfigSubstitutionRule class are listed below. For a complete list of FontConfigSubstitutionRule class members, see the FontConfigSubstitutionRule Members topic.

Public Instance Methods

IsFontConfigAvailable | Check if fontconfig utility is available or not.
ResetCache | Resets the cache of fontconfig calling results.

See Also

FontConfigSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontConfigSubstitutionRule.IsFontConfigAvailable Method

Check if fontconfig utility is available or not.

[Visual Basic]
Public Function IsFontConfigAvailable() As Boolean
[C#]
public bool IsFontConfigAvailable();

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}

See Also

FontConfigSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontConfigSubstitutionRule.ResetCache Method

Resets the cache of fontconfig calling results.

[Visual Basic]
Public Sub ResetCache()
[C#]
public void ResetCache();

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}

See Also

FontConfigSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontFallbackSettings Class

Specifies font fallback mechanism settings.

For a list of all members of this type, see FontFallbackSettings Members.

System.Object
Aspose.Words.Fonts.FontFallbackSettings

[Visual Basic]
Public Class FontFallbackSettings
[C#]
public class FontFallbackSettings

Remarks

By default fallback settings are initialized with predefined settings which mimics the Microsoft Word fallback.

Example

Shows how to distribute fallback fonts across unicode character code ranges.

[C#]

Document doc = new Document();

// Create a FontSettings object for our document and get its FallbackSettings attribute
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;

// Set our fonts to be sourced exclusively from the "MyFonts" folder
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// Calling BuildAutomatic() will generate a fallback scheme that distributes accessible fonts across as many unicode character codes as possible
// In our case, it only has access to the handful of fonts inside the "MyFonts" folder
fontFallbackSettings.BuildAutomatic();
fontFallbackSettings.Save(ArtifactsDir + "Font.FontFallbackSettings.BuildAutomatic.xml");

// We can also load a custom substitution scheme from a file like this
// This scheme applies the "Arvo" font across the "0000-00ff" unicode blocks, the "Squarish Sans CT" font across "0100-024f",
// and the "M+ 2m" font in every place that none of the other fonts cover
fontFallbackSettings.Load(MyDir + "Font.FallbackSettings.Custom.xml");

// Create a document builder and set its font to one that doesn't exist in any of our sources
// In doing that we will rely completely on our font fallback scheme to render text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Missing Font";

// Type out every unicode character from 0x0021 to 0x052F, with descriptive lines dividing unicode blocks we defined in our custom font fallback scheme
for (int i = 0x0021; i < 0x0530; i++)
{
    switch (i)
    {
        case 0x0021:
            builder.Writeln("\n\n0x0021 - 0x00FF: \nBasic Latin/Latin-1 Supplement unicode blocks in \"Arvo\" font:");
            break;
        case 0x0100:
            builder.Writeln("\n\n0x0100 - 0x024F: \nLatin Extended A/B blocks, mostly in \"Squarish Sans CT\" font:");
            break;
        case 0x0250:
            builder.Writeln("\n\n0x0250 - 0x052F: \nIPA/Greek/Cyrillic blocks in \"M+ 2m\" font:");
            break;
    }

    builder.Write(Convert.ToChar(i).ToString());
}

doc.Save(ArtifactsDir + "Font.FallbackSettings.Custom.pdf");

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontFallbackSettings Members | Aspose.Words.Fonts Namespace


FontFallbackSettings Members

FontFallbackSettings overview

Public Instance Methods

BuildAutomatic | Automatically builds the fallback settings by scanning available fonts.
Load | Overloaded. Loads font fallback settings from XML file.
LoadMsOfficeFallbackSettings | Loads predefined fallback settings which mimics the Microsoft Word fallback and uses Microsoft office fonts.
LoadNotoFallbackSettings | Loads predefined fallback settings which uses Google Noto fonts.
Save | Overloaded. Saves the current fallback settings to stream.

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


FontFallbackSettings Methods

The methods of the FontFallbackSettings class are listed below. For a complete list of FontFallbackSettings class members, see the FontFallbackSettings Members topic.

Public Instance Methods

BuildAutomatic | Automatically builds the fallback settings by scanning available fonts.
Load | Overloaded. Loads font fallback settings from XML file.
LoadMsOfficeFallbackSettings | Loads predefined fallback settings which mimics the Microsoft Word fallback and uses Microsoft office fonts.
LoadNotoFallbackSettings | Loads predefined fallback settings which uses Google Noto fonts.
Save | Overloaded. Saves the current fallback settings to stream.

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


FontFallbackSettings.BuildAutomatic Method

Automatically builds the fallback settings by scanning available fonts.

[Visual Basic]
Public Sub BuildAutomatic()
[C#]
public void BuildAutomatic();

Remarks

This method may produce non-optimal fallback settings. Fonts are checked by Unicode Character Range fields and not by the actual glyphs presence. Also Unicode ranges are checked individually and several ranges related to single language/script may use different fallback fonts.

Example

Shows how to distribute fallback fonts across unicode character code ranges.

[C#]

Document doc = new Document();

// Create a FontSettings object for our document and get its FallbackSettings attribute
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;

// Set our fonts to be sourced exclusively from the "MyFonts" folder
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// Calling BuildAutomatic() will generate a fallback scheme that distributes accessible fonts across as many unicode character codes as possible
// In our case, it only has access to the handful of fonts inside the "MyFonts" folder
fontFallbackSettings.BuildAutomatic();
fontFallbackSettings.Save(ArtifactsDir + "Font.FontFallbackSettings.BuildAutomatic.xml");

// We can also load a custom substitution scheme from a file like this
// This scheme applies the "Arvo" font across the "0000-00ff" unicode blocks, the "Squarish Sans CT" font across "0100-024f",
// and the "M+ 2m" font in every place that none of the other fonts cover
fontFallbackSettings.Load(MyDir + "Font.FallbackSettings.Custom.xml");

// Create a document builder and set its font to one that doesn't exist in any of our sources
// In doing that we will rely completely on our font fallback scheme to render text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Missing Font";

// Type out every unicode character from 0x0021 to 0x052F, with descriptive lines dividing unicode blocks we defined in our custom font fallback scheme
for (int i = 0x0021; i < 0x0530; i++)
{
    switch (i)
    {
        case 0x0021:
            builder.Writeln("\n\n0x0021 - 0x00FF: \nBasic Latin/Latin-1 Supplement unicode blocks in \"Arvo\" font:");
            break;
        case 0x0100:
            builder.Writeln("\n\n0x0100 - 0x024F: \nLatin Extended A/B blocks, mostly in \"Squarish Sans CT\" font:");
            break;
        case 0x0250:
            builder.Writeln("\n\n0x0250 - 0x052F: \nIPA/Greek/Cyrillic blocks in \"M+ 2m\" font:");
            break;
    }

    builder.Write(Convert.ToChar(i).ToString());
}

doc.Save(ArtifactsDir + "Font.FallbackSettings.Custom.pdf");

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


Load Method

Aspose.Words

FontFallbackSettings.Load Method

Loads fallback settings from XML stream.

Overload List

Loads fallback settings from XML stream.

public void Load(Stream);

Loads font fallback settings from XML file.

public void Load(string);

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


FontFallbackSettings.Load Method (Stream)

Loads fallback settings from XML stream.

[Visual Basic]
Overloads Public Sub Load( _
ByVal stream As Stream _
)
[C#]
public void Load(
Stream stream
);

Parameters

stream
Input stream.

Example

Shows how to load and save font fallback settings from stream.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// By default fallback settings are initialized with predefined settings which mimics the Microsoft Word fallback.
using (FileStream fontFallbackStream = new FileStream(MyDir + "Fallback.xml", FileMode.Open))
{
    FontSettings fontSettings = new FontSettings();
    fontSettings.FallbackSettings.Load(fontFallbackStream);

    doc.FontSettings = fontSettings;
}

doc.Save(ArtifactsDir + "LoadFontFallbackSettingsFromStream.pdf");

// Saves font fallback setting by stream
using (FileStream fontFallbackStream =
    new FileStream(ArtifactsDir + "FallbackSettings.xml", FileMode.Create))
{
    doc.FontSettings.FallbackSettings.Save(fontFallbackStream);
}

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace | FontFallbackSettings.Load Overload List


FontFallbackSettings.Load Method (String)

Loads font fallback settings from XML file.

[Visual Basic]
Overloads Public Sub Load( _
ByVal fileName As String _
)
[C#]
public void Load(
string fileName
);

Parameters

fileName
Input file name.

Example

Shows how to load and save font fallback settings from file.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// By default fallback settings are initialized with predefined settings which mimics the Microsoft Word fallback.
FontSettings fontSettings = new FontSettings();
fontSettings.FallbackSettings.Load(MyDir + "Fallback.xml");

doc.FontSettings = fontSettings;
doc.Save(ArtifactsDir + "LoadFontFallbackSettingsFromFile.pdf");

// Saves font fallback setting by string
doc.FontSettings.FallbackSettings.Save(ArtifactsDir + "FallbackSettings.xml");

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace | FontFallbackSettings.Load Overload List


FontFallbackSettings.LoadMsOfficeFallbackSettings Method

Loads predefined fallback settings which mimics the Microsoft Word fallback and uses Microsoft office fonts.

[Visual Basic]
Public Sub LoadMsOfficeFallbackSettings()
[C#]
public void LoadMsOfficeFallbackSettings();

Example

Shows how to load pre-defined fallback font settings.

[C#]

Document doc = new Document();

// Create a FontSettings object for our document and get its FallbackSettings attribute
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;

// Save the default fallback font scheme in an XML document
// For example, one of the elements has a value of "0C00-0C7F" for Range and a corresponding "Vani" value for FallbackFonts
// This means that if the font we are using does not have symbols for the 0x0C00-0x0C7F unicode block,
// the symbols from the "Vani" font will be used as a substitute
fontFallbackSettings.Save(ArtifactsDir + "Font.FallbackSettings.Default.xml");

// There are two pre-defined font fallback schemes we can choose from
// 1: Use the default Microsoft Office scheme, which is the same one as the default
fontFallbackSettings.LoadMsOfficeFallbackSettings();
fontFallbackSettings.Save(ArtifactsDir + "Font.FallbackSettings.LoadMsOfficeFallbackSettings.xml");

// 2: Use the scheme built from Google Noto fonts
fontFallbackSettings.LoadNotoFallbackSettings();
fontFallbackSettings.Save(ArtifactsDir + "Font.FallbackSettings.LoadNotoFallbackSettings.xml");

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


FontFallbackSettings.LoadNotoFallbackSettings Method

Loads predefined fallback settings which uses Google Noto fonts.

[Visual Basic]
Public Sub LoadNotoFallbackSettings()
[C#]
public void LoadNotoFallbackSettings();

Example

Shows how to add predefined font fallback settings for Google Noto fonts.

[C#]

FontSettings fontSettings = new FontSettings();
// These are free fonts licensed under SIL OFL
// They can be downloaded from https://www.google.com/get/noto/#sans-lgc
fontSettings.SetFontsFolder(FontsDir + "Noto", false);
// Note that only Sans style Noto fonts with regular weight are used in the predefined settings
// Some of the Noto fonts uses advanced typography features
// Advanced typography is currently not supported by AW and these fonts may be rendered inaccurately
fontSettings.FallbackSettings.LoadNotoFallbackSettings();
fontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = false;
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Noto Sans";

Document doc = new Document();
doc.FontSettings = fontSettings;
Shows how to load pre-defined fallback font settings.
[C#]

Document doc = new Document();

// Create a FontSettings object for our document and get its FallbackSettings attribute
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;

// Save the default fallback font scheme in an XML document
// For example, one of the elements has a value of "0C00-0C7F" for Range and a corresponding "Vani" value for FallbackFonts
// This means that if the font we are using does not have symbols for the 0x0C00-0x0C7F unicode block,
// the symbols from the "Vani" font will be used as a substitute
fontFallbackSettings.Save(ArtifactsDir + "Font.FallbackSettings.Default.xml");

// There are two pre-defined font fallback schemes we can choose from
// 1: Use the default Microsoft Office scheme, which is the same one as the default
fontFallbackSettings.LoadMsOfficeFallbackSettings();
fontFallbackSettings.Save(ArtifactsDir + "Font.FallbackSettings.LoadMsOfficeFallbackSettings.xml");

// 2: Use the scheme built from Google Noto fonts
fontFallbackSettings.LoadNotoFallbackSettings();
fontFallbackSettings.Save(ArtifactsDir + "Font.FallbackSettings.LoadNotoFallbackSettings.xml");

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


Save Method

Aspose.Words

FontFallbackSettings.Save Method

Saves the current fallback settings to stream.

Overload List

Saves the current fallback settings to stream.

public void Save(Stream);

Saves the current fallback settings to file.

public void Save(string);

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace


FontFallbackSettings.Save Method (Stream)

Saves the current fallback settings to stream.

[Visual Basic]
Overloads Public Sub Save( _
ByVal outputStream As Stream _
)
[C#]
public void Save(
Stream outputStream
);

Parameters

outputStream
Output stream.

Example

Shows how to load and save font fallback settings from stream.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// By default fallback settings are initialized with predefined settings which mimics the Microsoft Word fallback.
using (FileStream fontFallbackStream = new FileStream(MyDir + "Fallback.xml", FileMode.Open))
{
    FontSettings fontSettings = new FontSettings();
    fontSettings.FallbackSettings.Load(fontFallbackStream);

    doc.FontSettings = fontSettings;
}

doc.Save(ArtifactsDir + "LoadFontFallbackSettingsFromStream.pdf");

// Saves font fallback setting by stream
using (FileStream fontFallbackStream =
    new FileStream(ArtifactsDir + "FallbackSettings.xml", FileMode.Create))
{
    doc.FontSettings.FallbackSettings.Save(fontFallbackStream);
}

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace | FontFallbackSettings.Save Overload List


FontFallbackSettings.Save Method (String)

Saves the current fallback settings to file.

[Visual Basic]
Overloads Public Sub Save( _
ByVal fileName As String _
)
[C#]
public void Save(
string fileName
);

Parameters

fileName
Output file name.

Example

Shows how to load and save font fallback settings from file.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// By default fallback settings are initialized with predefined settings which mimics the Microsoft Word fallback.
FontSettings fontSettings = new FontSettings();
fontSettings.FallbackSettings.Load(MyDir + "Fallback.xml");

doc.FontSettings = fontSettings;
doc.Save(ArtifactsDir + "LoadFontFallbackSettingsFromFile.pdf");

// Saves font fallback setting by string
doc.FontSettings.FallbackSettings.Save(ArtifactsDir + "FallbackSettings.xml");

See Also

FontFallbackSettings Class | Aspose.Words.Fonts Namespace | FontFallbackSettings.Save Overload List


FontFamily Enumeration

Represents the font family.

[Visual Basic]
Public Enum FontFamily
[C#]
public enum FontFamily

Remarks

A font family is a set of fonts having common stroke width and serif characteristics.

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

Members

Member Name | Description | Value
Auto | Specifies a generic family name. This name is used when information about a font does not exist or does not matter. The default font is used. | 0
Roman | Specifies a proportional font with serifs. An example is Times New Roman. | 1
Swiss | Specifies a proportional font without serifs. An example is Arial. | 2
Modern | Specifies a monospace font with or without serifs. Monospace fonts are usually modern; examples include Pica, Elite, and Courier New. | 3
Script | Specifies a font that is designed to look like handwriting; examples include Script and Cursive. | 4
Decorative | Specifies a novelty font. An example is Old English. | 5

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fonts Namespace


FontInfo Class

Specifies information about a font used in the document.

For a list of all members of this type, see FontInfo Members.

System.Object
Aspose.Words.Fonts.FontInfo

[Visual Basic]
Public Class FontInfo
[C#]
public class FontInfo

Remarks

You do not create instances of this class directly. Use the FontInfos property to access the collection of fonts defined in a document.

Example

Shows how to gather the details of what fonts are present in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

FontInfoCollection fonts = doc.FontInfos;
int fontIndex = 1;

// The fonts info extracted from this document does not necessarily mean that the fonts themselves are
// used in the document. If a font is present but not used then most likely they were referenced at some time
// and then removed from the Document.
foreach (FontInfo info in fonts)
{
    // Print out some important details about the font.
    Console.WriteLine("Font #{0}", fontIndex);
    Console.WriteLine("Name: {0}", info.Name);
    Console.WriteLine("IsTrueType: {0}", info.IsTrueType);
    fontIndex++;
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontInfo Members | Aspose.Words.Fonts Namespace | FontInfoCollection | FontInfos


FontInfo Members

FontInfo overview

Public Instance Properties

AltName | Gets or sets the alternate name for the font.
Charset | Gets or sets the character set for the font.
Family | Gets or sets the font family this font belongs to.
IsTrueType | Indicates that this font is a TrueType or OpenType font as opposed to a raster or vector font. Default is true.
Name | Gets the name of the font.
Panose | Gets or sets the PANOSE typeface classification number.
Pitch | The pitch indicates if the font is fixed pitch, proportionally spaced, or relies on a default setting.

Public Instance Methods

GetEmbeddedFont Gets a specific embedded font file.

See Also

FontInfo Class | Aspose.Words.Fonts Namespace | FontInfoCollection | FontInfos


FontInfo Properties

The properties of the FontInfo class are listed below. For a complete list of FontInfo class members, see the FontInfo Members topic.

Public Instance Properties

AltName | Gets or sets the alternate name for the font.
Charset | Gets or sets the character set for the font.
Family | Gets or sets the font family this font belongs to.
IsTrueType | Indicates that this font is a TrueType or OpenType font as opposed to a raster or vector font. Default is true.
Name | Gets the name of the font.
Panose | Gets or sets the PANOSE typeface classification number.
Pitch | The pitch indicates if the font is fixed pitch, proportionally spaced, or relies on a default setting.

See Also

FontInfo Class | Aspose.Words.Fonts Namespace | FontInfoCollection | FontInfos


AltName Property

Aspose.Words

FontInfo.AltName Property

Gets or sets the alternate name for the font.

[Visual Basic]
Public Property AltName As String
[C#]
public string AltName {get; set;}

Remarks

Cannot be null. Can be an empty string.

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


Charset Property

Aspose.Words

FontInfo.Charset Property

Gets or sets the character set for the font.

[Visual Basic]
Public Property Charset As Integer
[C#]
public int Charset {get; set;}

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


Family Property

Aspose.Words

FontInfo.Family Property

Gets or sets the font family this font belongs to.

[Visual Basic]
Public Property Family As FontFamily
[C#]
public FontFamily Family {get; set;}

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


IsTrueType Property

Aspose.Words

FontInfo.IsTrueType Property

Indicates that this font is a TrueType or OpenType font as opposed to a raster or vector font. Default is true.

[Visual Basic]
Public Property IsTrueType As Boolean
[C#]
public bool IsTrueType {get; set;}

Example

Shows how to gather the details of what fonts are present in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

FontInfoCollection fonts = doc.FontInfos;
int fontIndex = 1;

// The fonts info extracted from this document does not necessarily mean that the fonts themselves are
// used in the document. If a font is present but not used then most likely they were referenced at some time
// and then removed from the Document.
foreach (FontInfo info in fonts)
{
    // Print out some important details about the font.
    Console.WriteLine("Font #{0}", fontIndex);
    Console.WriteLine("Name: {0}", info.Name);
    Console.WriteLine("IsTrueType: {0}", info.IsTrueType);
    fontIndex++;
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


Name Property

Aspose.Words

FontInfo.Name Property

Gets the name of the font.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Remarks

Cannot be null. Can be an empty string.

Example

Shows how to gather the details of what fonts are present in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

FontInfoCollection fonts = doc.FontInfos;
int fontIndex = 1;

// The fonts info extracted from this document does not necessarily mean that the fonts themselves are
// used in the document. If a font is present but not used then most likely they were referenced at some time
// and then removed from the Document.
foreach (FontInfo info in fonts)
{
    // Print out some important details about the font.
    Console.WriteLine("Font #{0}", fontIndex);
    Console.WriteLine("Name: {0}", info.Name);
    Console.WriteLine("IsTrueType: {0}", info.IsTrueType);
    fontIndex++;
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


Panose Property

Aspose.Words

FontInfo.Panose Property

Gets or sets the PANOSE typeface classification number.

[Visual Basic]
Public Property Panose As Byte()
[C#]
public byte[] Panose {get; set;}

Remarks

PANOSE is a compact 10-byte description of a fonts critical visual characteristics, such as contrast, weight, and serif style. The digits represent Family Kind, Serif Style, Weight, Proportion, Contrast, Stroke Variation, Arm Style, Letterform, Midline, and X-Height.

Can be null.

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


Pitch Property

Aspose.Words

FontInfo.Pitch Property

The pitch indicates if the font is fixed pitch, proportionally spaced, or relies on a default setting.

[Visual Basic]
Public Property Pitch As FontPitch
[C#]
public FontPitch Pitch {get; set;}

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


FontInfo Methods

The methods of the FontInfo class are listed below. For a complete list of FontInfo class members, see the FontInfo Members topic.

Public Instance Methods

GetEmbeddedFont Gets a specific embedded font file.

See Also

FontInfo Class | Aspose.Words.Fonts Namespace | FontInfoCollection | FontInfos


FontInfo.GetEmbeddedFont Method

Gets a specific embedded font file.

[Visual Basic]
Public Function GetEmbeddedFont( _
ByVal format As EmbeddedFontFormat, _
ByVal style As EmbeddedFontStyle _
) As Byte()
[C#]
public byte[] GetEmbeddedFont(
EmbeddedFontFormat format,
EmbeddedFontStyle style
);

Parameters

format
Specifies the font format to retrieve.
style
Specifies the font style to retrieve.

Return Value

Returns null if the specified font is not embedded.

Example

Shows how to extract embedded font from a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");
// Let's get the font we are interested in
FontInfo mittelschriftInfo = doc.FontInfos[2];
// We can now extract this embedded font
byte[] embeddedFontBytes = mittelschriftInfo.GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular);
Assert.IsNotNull(embeddedFontBytes);
// Then we can save the font to our directory
File.WriteAllBytes(ArtifactsDir + "Alte DIN 1451 Mittelschrift.ttf", embeddedFontBytes);

// If we want to extract a font from a .doc as opposed to a .docx, we need to make sure to set the appropriate embedded font format
doc = new Document(MyDir + "Font.Embedded.doc");

Assert.IsNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular));
Assert.IsNotNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.EmbeddedOpenType, EmbeddedFontStyle.Regular));

See Also

FontInfo Class | Aspose.Words.Fonts Namespace


FontInfoCollection Class

Represents a collection of fonts used in a document.

For a list of all members of this type, see FontInfoCollection Members.

System.Object
Aspose.Words.Fonts.FontInfoCollection

[Visual Basic]
Public Class FontInfoCollection
Implements IEnumerable`1([Aspose.Words.Fonts.FontInfo, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class FontInfoCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

Items are FontInfo objects.

You do not create instances of this class directly. Use the FontInfos property to access the collection of fonts defined in the document.

Example

Shows how to save a document with embedded TrueType fonts

[C#]

Document doc = new Document(MyDir + "Document.docx");

FontInfoCollection fontInfos = doc.FontInfos;
fontInfos.EmbedTrueTypeFonts = true;
fontInfos.EmbedSystemFonts = false;
fontInfos.SaveSubsetFonts = false;

doc.Save(ArtifactsDir + "Document.docx");
Shows how to gather the details of what fonts are present in a document.
[C#]

Document doc = new Document(MyDir + "Document.doc");

FontInfoCollection fonts = doc.FontInfos;
int fontIndex = 1;

// The fonts info extracted from this document does not necessarily mean that the fonts themselves are
// used in the document. If a font is present but not used then most likely they were referenced at some time
// and then removed from the Document.
foreach (FontInfo info in fonts)
{
    // Print out some important details about the font.
    Console.WriteLine("Font #{0}", fontIndex);
    Console.WriteLine("Name: {0}", info.Name);
    Console.WriteLine("IsTrueType: {0}", info.IsTrueType);
    fontIndex++;
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontInfoCollection Members | Aspose.Words.Fonts Namespace | FontInfo | FontInfos


FontInfoCollection Members

FontInfoCollection overview

Public Instance Properties

Count | Gets the number of elements contained in the collection.
EmbedSystemFonts | Specifies whether or not to embed System fonts into the document. Default value for this property is false. This option works only when EmbedTrueTypeFonts option is set to true.
EmbedTrueTypeFonts | Specifies whether or not to embed TrueType fonts in a document when it is saved. Default value for this property is false.
Item | Overloaded. Provides access to the collection items.
SaveSubsetFonts | Specifies whether or not to save a subset of the embedded TrueType fonts with the document. Default value for this property is false. This option works only when EmbedTrueTypeFonts property is set to true.

Public Instance Methods

Contains | Determines whether the collection contains a font with the given name.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace | FontInfo | FontInfos


FontInfoCollection Properties

The properties of the FontInfoCollection class are listed below. For a complete list of FontInfoCollection class members, see the FontInfoCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
EmbedSystemFonts | Specifies whether or not to embed System fonts into the document. Default value for this property is false. This option works only when EmbedTrueTypeFonts option is set to true.
EmbedTrueTypeFonts | Specifies whether or not to embed TrueType fonts in a document when it is saved. Default value for this property is false.
Item | Overloaded. Provides access to the collection items.
SaveSubsetFonts | Specifies whether or not to save a subset of the embedded TrueType fonts with the document. Default value for this property is false. This option works only when EmbedTrueTypeFonts property is set to true.

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace | FontInfo | FontInfos


Count Property

Aspose.Words

FontInfoCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows info about the fonts that are present in the blank document.

[C#]

// Create a new document
Document doc = new Document();
// A blank document comes with 3 fonts
Assert.AreEqual(3, doc.FontInfos.Count);
Assert.AreEqual(true, doc.FontInfos.Contains("Times New Roman"));
Assert.AreEqual(true, doc.FontInfos.Contains("Symbol"));
Assert.AreEqual(true, doc.FontInfos.Contains("Arial"));

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


EmbedSystemFonts Property

Aspose.Words

FontInfoCollection.EmbedSystemFonts Property

Specifies whether or not to embed System fonts into the document. Default value for this property is false.

This option works only when EmbedTrueTypeFonts option is set to true.

[Visual Basic]
Public Property EmbedSystemFonts As Boolean
[C#]
public bool EmbedSystemFonts {get; set;}

Remarks

Setting this property to True is useful if the user is on an East Asian system and wants to create a document that is readable by others who do not have fonts for that language on their system. For example, a user on a Japanese system could choose to embed the fonts in a document so that the Japanese document would be readable on all systems.

This option works for DOC, DOCX and RTF formats only.

Example

Shows how to save a document with embedded TrueType fonts

[C#]

Document doc = new Document(MyDir + "Document.docx");

FontInfoCollection fontInfos = doc.FontInfos;
fontInfos.EmbedTrueTypeFonts = true;
fontInfos.EmbedSystemFonts = false;
fontInfos.SaveSubsetFonts = false;

doc.Save(ArtifactsDir + "Document.docx");

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


EmbedTrueTypeFonts Property

Aspose.Words

FontInfoCollection.EmbedTrueTypeFonts Property

Specifies whether or not to embed TrueType fonts in a document when it is saved. Default value for this property is false.

[Visual Basic]
Public Property EmbedTrueTypeFonts As Boolean
[C#]
public bool EmbedTrueTypeFonts {get; set;}

Remarks

Embedding TrueType fonts allows others to view the document with the same fonts that were used to create it, but may substantially increase the document size.

This option works for DOC, DOCX and RTF formats only.

Example

Shows how to save a document with embedded TrueType fonts

[C#]

Document doc = new Document(MyDir + "Document.docx");

FontInfoCollection fontInfos = doc.FontInfos;
fontInfos.EmbedTrueTypeFonts = true;
fontInfos.EmbedSystemFonts = false;
fontInfos.SaveSubsetFonts = false;

doc.Save(ArtifactsDir + "Document.docx");

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


Item Property

Aspose.Words

FontInfoCollection.Item Property

Provides access to the collection items.

Overload List

Gets a font at the specified index.

public FontInfo this[int] {get;}

Gets a font with the specified name.

public FontInfo this[string] {get;}

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


Item Property (Int32)

Aspose.Words

FontInfoCollection.Item Property (Int32)

Gets a font at the specified index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As FontInfo
[C#]
public FontInfo this[
int index
] {get;}

Parameters

index
Zero-based index of the font.

Example

Shows how to extract embedded font from a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");
// Let's get the font we are interested in
FontInfo mittelschriftInfo = doc.FontInfos[2];
// We can now extract this embedded font
byte[] embeddedFontBytes = mittelschriftInfo.GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular);
Assert.IsNotNull(embeddedFontBytes);
// Then we can save the font to our directory
File.WriteAllBytes(ArtifactsDir + "Alte DIN 1451 Mittelschrift.ttf", embeddedFontBytes);

// If we want to extract a font from a .doc as opposed to a .docx, we need to make sure to set the appropriate embedded font format
doc = new Document(MyDir + "Font.Embedded.doc");

Assert.IsNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular));
Assert.IsNotNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.EmbeddedOpenType, EmbeddedFontStyle.Regular));

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace | FontInfoCollection.Item Overload List


Item Property (String)

Aspose.Words

FontInfoCollection.Item Property (String)

Gets a font with the specified name.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal name As String _
) As FontInfo
[C#]
public FontInfo this[
string name
] {get;}

Parameters

name
Case-insensitive name of the font to locate.

Example

Shows how to extract embedded font from a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");
// Let's get the font we are interested in
FontInfo mittelschriftInfo = doc.FontInfos[2];
// We can now extract this embedded font
byte[] embeddedFontBytes = mittelschriftInfo.GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular);
Assert.IsNotNull(embeddedFontBytes);
// Then we can save the font to our directory
File.WriteAllBytes(ArtifactsDir + "Alte DIN 1451 Mittelschrift.ttf", embeddedFontBytes);

// If we want to extract a font from a .doc as opposed to a .docx, we need to make sure to set the appropriate embedded font format
doc = new Document(MyDir + "Font.Embedded.doc");

Assert.IsNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.OpenType, EmbeddedFontStyle.Regular));
Assert.IsNotNull(doc.FontInfos["Alte DIN 1451 Mittelschrift"].GetEmbeddedFont(EmbeddedFontFormat.EmbeddedOpenType, EmbeddedFontStyle.Regular));

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace | FontInfoCollection.Item Overload List


SaveSubsetFonts Property

Aspose.Words

FontInfoCollection.SaveSubsetFonts Property

Specifies whether or not to save a subset of the embedded TrueType fonts with the document. Default value for this property is false.

This option works only when EmbedTrueTypeFonts property is set to true.

[Visual Basic]
Public Property SaveSubsetFonts As Boolean
[C#]
public bool SaveSubsetFonts {get; set;}

Remarks

This option works for DOC, DOCX and RTF formats only.

Example

Shows how to save a document with embedded TrueType fonts

[C#]

Document doc = new Document(MyDir + "Document.docx");

FontInfoCollection fontInfos = doc.FontInfos;
fontInfos.EmbedTrueTypeFonts = true;
fontInfos.EmbedSystemFonts = false;
fontInfos.SaveSubsetFonts = false;

doc.Save(ArtifactsDir + "Document.docx");

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


FontInfoCollection Methods

The methods of the FontInfoCollection class are listed below. For a complete list of FontInfoCollection class members, see the FontInfoCollection Members topic.

Public Instance Methods

Contains | Determines whether the collection contains a font with the given name.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace | FontInfo | FontInfos


FontInfoCollection.Contains Method

Determines whether the collection contains a font with the given name.

[Visual Basic]
Public Function Contains( _
ByVal name As String _
) As Boolean
[C#]
public bool Contains(
string name
);

Parameters

name
Case-insensitive name of the font to locate.

Return Value

True if the item is found in the collection; otherwise, false.

Example

Shows info about the fonts that are present in the blank document.

[C#]

// Create a new document
Document doc = new Document();
// A blank document comes with 3 fonts
Assert.AreEqual(3, doc.FontInfos.Count);
Assert.AreEqual(true, doc.FontInfos.Contains("Times New Roman"));
Assert.AreEqual(true, doc.FontInfos.Contains("Symbol"));
Assert.AreEqual(true, doc.FontInfos.Contains("Arial"));

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


FontInfoCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of FontInfo) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<FontInfo> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace


FontInfoSubstitutionRule Class

Font info substitution rule.

For a list of all members of this type, see FontInfoSubstitutionRule Members.

System.Object
Aspose.Words.Fonts.FontSubstitutionRule
Aspose.Words.Fonts.FontInfoSubstitutionRule

[Visual Basic]
Public Class FontInfoSubstitutionRule
Inherits FontSubstitutionRule
[C#]
public class FontInfoSubstitutionRule : FontSubstitutionRule

Remarks

According to this rule Aspose.Words evaluates all the related fields in FontInfo (Panose, Sig etc) for the missing font and finds the closest match among the available font sources. If FontInfo is not available for the missing font then nothing will be done.

Example

Shows how to set the property for finding the closest match font among the available font sources instead missing font.

[C#]

Document doc = new Document(MyDir + "Font.EnableFontSubstitution.docx");

// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;

FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial"; ;
fontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontInfoSubstitutionRule Members | Aspose.Words.Fonts Namespace


FontInfoSubstitutionRule Members

FontInfoSubstitutionRule overview

Public Instance Properties

Enabled (inherited from FontSubstitutionRule) Specifies whether the rule is enabled or not.

See Also

FontInfoSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontPitch Enumeration

Represents the font pitch.

[Visual Basic]
Public Enum FontPitch
[C#]
public enum FontPitch

Remarks

The pitch indicates if the font is fixed pitch, proportionally spaced, or relies on a default setting.

Example

Shows how to get information about each font in a document.

[C#]

Document doc = new Document(MyDir + "Font.Embedded.docx");

// We can iterate over all the fonts with an enumerator
IEnumerator fontCollectionEnumerator = doc.FontInfos.GetEnumerator();
// Print detailed information about each font to the console
while (fontCollectionEnumerator.MoveNext())
{
    FontInfo fontInfo = (FontInfo)fontCollectionEnumerator.Current;
    if (fontInfo != null)
    {
        Console.WriteLine("Font name: " + fontInfo.Name);
        Console.WriteLine("Alt name: " + fontInfo.AltName); // Alt names are usually blank
        Console.WriteLine("\t- Family: " + fontInfo.Family);
        Console.WriteLine("\t- " + (fontInfo.IsTrueType ? "Is TrueType" : "Is not TrueType"));
        Console.WriteLine("\t- Pitch: " + fontInfo.Pitch);
        Console.WriteLine("\t- Charset: " + fontInfo.Charset);
        Console.WriteLine("\t- Panose:");
        Console.WriteLine("\t\tFamily Kind: " + fontInfo.Panose[0]);
        Console.WriteLine("\t\tSerif Style: " + fontInfo.Panose[1]);
        Console.WriteLine("\t\tWeight: " + fontInfo.Panose[2]);
        Console.WriteLine("\t\tProportion: " + fontInfo.Panose[3]);
        Console.WriteLine("\t\tContrast: " + fontInfo.Panose[4]);
        Console.WriteLine("\t\tStroke Variation: " + fontInfo.Panose[5]);
        Console.WriteLine("\t\tArm Style: " + fontInfo.Panose[6]);
        Console.WriteLine("\t\tLetterform: " + fontInfo.Panose[7]);
        Console.WriteLine("\t\tMidline: " + fontInfo.Panose[8]);
        Console.WriteLine("\t\tX-Height: " + fontInfo.Panose[9]);
    }
}

Members

Member Name | Description | Value
Default | Specifies that no information is available about the pitch of a font. | 0
Fixed | Specifies that this is a fixed width font. | 1
Variable | Specifies that this is a proportional width font. | 2

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fonts Namespace


FontSettings Class

Specifies font settings for a document.

For a list of all members of this type, see FontSettings Members.

System.Object
Aspose.Words.Fonts.FontSettings

[Visual Basic]
Public Class FontSettings
[C#]
public class FontSettings

Remarks

Aspose.Words uses font settings to resolve the fonts in the document. Fonts are resolved mostly when building document layout or rendering to fixed page formats. But when loading some formats, Aspose.Words also may require to resolve the fonts. For example, when loading HTML documents Aspose.Words may resolve the fonts to perform font fallback. So it is recommended that you set the font settings in LoadOptions when loading the document. Or at least before building the layout or rendering the document to the fixed-page format.

By default all documents uses single static font settings instance. It could be accessed by DefaultInstance property.

Changing font settings is safe at any time from any thread. But it is recommended that you do not change the font settings while processing some documents which uses this settings. This can lead to the fact that the same font will be resolved differently in different parts of the document.

Example

Demonstrates how to set the folder Aspose.Words uses to look for TrueType fonts during rendering or embedding of fonts.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for
// fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and
// FontSettings.SetFontSources instead.
FontSettings.DefaultInstance.SetFontsFolder(@"C:\MyFonts\", false);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolder.pdf");
Demonstrates how to set Aspose.Words to look in multiple folders for TrueType fonts when rendering or embedding fonts.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for
// fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and
// FontSettings.SetFontSources instead.
FontSettings.DefaultInstance.SetFontsFolders(new String[] { @"C:\MyFonts\", @"D:\Misc\Fonts\" }, true);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolders.pdf");
Demonstrates how to set Aspose.Words to look for TrueType fonts in system folders as well as a custom defined folder when scanning for fonts.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Retrieve the array of environment-dependent font sources that are searched by default. For example this will contain a "Windows\Fonts\" source on a Windows machines.
// We add this array to a new ArrayList to make adding or removing font entries much easier.
ArrayList fontSources = new ArrayList(FontSettings.DefaultInstance.GetFontsSources());

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FolderFontSource folderFontSource = new FolderFontSource("C:\\MyFonts\\", true);

// Add the custom folder which contains our fonts to the list of existing font sources.
fontSources.Add(folderFontSource);

// Convert the ArrayList of source back into a primitive array of FontSource objects.
FontSourceBase[] updatedFontSources = (FontSourceBase[]) fontSources.ToArray(typeof(FontSourceBase));

// Apply the new set of font sources to use.
FontSettings.DefaultInstance.SetFontsSources(updatedFontSources);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolders.pdf");

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontSettings Members | Aspose.Words.Fonts Namespace


FontSettings Members

FontSettings overview

Public Static (Shared) Properties

DefaultInstance Static default font settings.

Public Instance Constructors

FontSettings Constructor Initializes a new instance of the FontSettings class.

Public Instance Properties

FallbackSettings | Settings related to font fallback mechanism.
SubstitutionSettings | Settings related to font substitution mechanism.

Public Instance Methods

GetFontsSources | Gets a copy of the array that contains the list of sources where Aspose.Words looks for TrueType fonts.
ResetFontSources | Resets the fonts sources to the system default.
SetFontsFolder | Sets the folder where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts. This is a shortcut to SetFontsFolders for setting only one font directory.
SetFontsFolders | Sets the folders where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts.
SetFontsSources | Sets the sources where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts.

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings Constructor

Initializes a new instance of the FontSettings class.

[Visual Basic]
Public Sub New()
[C#]
public FontSettings();

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings Properties

The properties of the FontSettings class are listed below. For a complete list of FontSettings class members, see the FontSettings Members topic.

Public Static (Shared) Properties

DefaultInstance Static default font settings.

Public Instance Properties

FallbackSettings | Settings related to font fallback mechanism.
SubstitutionSettings | Settings related to font substitution mechanism.

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


DefaultInstance Property

Aspose.Words

FontSettings.DefaultInstance Property

Static default font settings.

[Visual Basic]
Public Shared ReadOnly Property DefaultInstance As FontSettings
[C#]
public static FontSettings DefaultInstance {get;}

Remarks

This instance is used by default in a document unless FontSettings is specified.

Example

Demonstrates how to receive notifications of font substitutions by using IWarningCallback.

[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Document.doc");

// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;

// We can choose the default font to use in the case of any missing fonts.
FontSettings.DefaultInstance.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial";

// For testing we will set Aspose.Words to look for fonts only in a folder which doesn't exist. Since Aspose.Words won't
// find any fonts in the specified directory, then during rendering the fonts in the document will be substituted with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this substitution using our callback.
FontSettings.DefaultInstance.SetFontsFolder(String.Empty, false);

// Pass the save options along with the save path to the save method.
doc.Save(ArtifactsDir + "Rendering.MissingFontNotification.pdf");

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FallbackSettings Property

Aspose.Words

FontSettings.FallbackSettings Property

Settings related to font fallback mechanism.

[Visual Basic]
Public ReadOnly Property FallbackSettings As FontFallbackSettings
[C#]
public FontFallbackSettings FallbackSettings {get;}

Example

Shows how to distribute fallback fonts across unicode character code ranges.

[C#]

Document doc = new Document();

// Create a FontSettings object for our document and get its FallbackSettings attribute
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;
FontFallbackSettings fontFallbackSettings = fontSettings.FallbackSettings;

// Set our fonts to be sourced exclusively from the "MyFonts" folder
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// Calling BuildAutomatic() will generate a fallback scheme that distributes accessible fonts across as many unicode character codes as possible
// In our case, it only has access to the handful of fonts inside the "MyFonts" folder
fontFallbackSettings.BuildAutomatic();
fontFallbackSettings.Save(ArtifactsDir + "Font.FontFallbackSettings.BuildAutomatic.xml");

// We can also load a custom substitution scheme from a file like this
// This scheme applies the "Arvo" font across the "0000-00ff" unicode blocks, the "Squarish Sans CT" font across "0100-024f",
// and the "M+ 2m" font in every place that none of the other fonts cover
fontFallbackSettings.Load(MyDir + "Font.FallbackSettings.Custom.xml");

// Create a document builder and set its font to one that doesn't exist in any of our sources
// In doing that we will rely completely on our font fallback scheme to render text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Missing Font";

// Type out every unicode character from 0x0021 to 0x052F, with descriptive lines dividing unicode blocks we defined in our custom font fallback scheme
for (int i = 0x0021; i < 0x0530; i++)
{
    switch (i)
    {
        case 0x0021:
            builder.Writeln("\n\n0x0021 - 0x00FF: \nBasic Latin/Latin-1 Supplement unicode blocks in \"Arvo\" font:");
            break;
        case 0x0100:
            builder.Writeln("\n\n0x0100 - 0x024F: \nLatin Extended A/B blocks, mostly in \"Squarish Sans CT\" font:");
            break;
        case 0x0250:
            builder.Writeln("\n\n0x0250 - 0x052F: \nIPA/Greek/Cyrillic blocks in \"M+ 2m\" font:");
            break;
    }

    builder.Write(Convert.ToChar(i).ToString());
}

doc.Save(ArtifactsDir + "Font.FallbackSettings.Custom.pdf");

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


SubstitutionSettings Property

Aspose.Words

FontSettings.SubstitutionSettings Property

Settings related to font substitution mechanism.

[Visual Basic]
Public ReadOnly Property SubstitutionSettings As FontSubstitutionSettings
[C#]
public FontSubstitutionSettings SubstitutionSettings {get;}

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings Methods

The methods of the FontSettings class are listed below. For a complete list of FontSettings class members, see the FontSettings Members topic.

Public Instance Methods

GetFontsSources | Gets a copy of the array that contains the list of sources where Aspose.Words looks for TrueType fonts.
ResetFontSources | Resets the fonts sources to the system default.
SetFontsFolder | Sets the folder where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts. This is a shortcut to SetFontsFolders for setting only one font directory.
SetFontsFolders | Sets the folders where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts.
SetFontsSources | Sets the sources where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts.

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings.GetFontsSources Method

Gets a copy of the array that contains the list of sources where Aspose.Words looks for TrueType fonts.

[Visual Basic]
Public Function GetFontsSources() As FontSourceBase()
[C#]
public FontSourceBase[] GetFontsSources();

Return Value

A copy of the current font sources.

Remarks

The returned value is a copy of the data that Aspose.Words uses. If you change the entries in the returned array, it will have no effect on document rendering. To specify new font sources use the SetFontsSources method.

Example

Demonstrates how to set Aspose.Words to look for TrueType fonts in system folders as well as a custom defined folder when scanning for fonts.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Retrieve the array of environment-dependent font sources that are searched by default. For example this will contain a "Windows\Fonts\" source on a Windows machines.
// We add this array to a new ArrayList to make adding or removing font entries much easier.
ArrayList fontSources = new ArrayList(FontSettings.DefaultInstance.GetFontsSources());

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FolderFontSource folderFontSource = new FolderFontSource("C:\\MyFonts\\", true);

// Add the custom folder which contains our fonts to the list of existing font sources.
fontSources.Add(folderFontSource);

// Convert the ArrayList of source back into a primitive array of FontSource objects.
FontSourceBase[] updatedFontSources = (FontSourceBase[]) fontSources.ToArray(typeof(FontSourceBase));

// Apply the new set of font sources to use.
FontSettings.DefaultInstance.SetFontsSources(updatedFontSources);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolders.pdf");

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings.ResetFontSources Method

Resets the fonts sources to the system default.

[Visual Basic]
Public Sub ResetFontSources()
[C#]
public void ResetFontSources();

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings.SetFontsFolder Method

Sets the folder where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts. This is a shortcut to SetFontsFolders for setting only one font directory.

[Visual Basic]
Public Sub SetFontsFolder( _
ByVal fontFolder As String, _
ByVal recursive As Boolean _
)
[C#]
public void SetFontsFolder(
string fontFolder,
bool recursive
);

Parameters

fontFolder
The folder that contains TrueType fonts.
recursive
True to scan the specified folders for fonts recursively.

Example

Demonstrates how to set the folder Aspose.Words uses to look for TrueType fonts during rendering or embedding of fonts.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for
// fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and
// FontSettings.SetFontSources instead.
FontSettings.DefaultInstance.SetFontsFolder(@"C:\MyFonts\", false);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolder.pdf");

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings.SetFontsFolders Method

Sets the folders where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts.

[Visual Basic]
Public Sub SetFontsFolders( _
ByVal fontsFolders As String(), _
ByVal recursive As Boolean _
)
[C#]
public void SetFontsFolders(
string[] fontsFolders,
bool recursive
);

Parameters

fontsFolders
An array of folders that contain TrueType fonts.
recursive
True to scan the specified folders for fonts recursively.

Remarks

By default, Aspose.Words looks for fonts installed to the system.

Setting this property resets the cache of all previously loaded fonts.

Example

Demonstrates how to set Aspose.Words to look in multiple folders for TrueType fonts when rendering or embedding fonts.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for
// fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and
// FontSettings.SetFontSources instead.
FontSettings.DefaultInstance.SetFontsFolders(new String[] { @"C:\MyFonts\", @"D:\Misc\Fonts\" }, true);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolders.pdf");

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings.SetFontsSources Method

Sets the sources where Aspose.Words looks for TrueType fonts when rendering documents or embedding fonts.

[Visual Basic]
Public Sub SetFontsSources( _
ByVal sources As FontSourceBase() _
)
[C#]
public void SetFontsSources(
FontSourceBase[] sources
);

Parameters

sources
An array of sources that contain TrueType fonts.

Remarks

By default, Aspose.Words looks for fonts installed to the system.

Setting this property resets the cache of all previously loaded fonts.

Example

Demonstrates how to set Aspose.Words to look for TrueType fonts in system folders as well as a custom defined folder when scanning for fonts.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// Retrieve the array of environment-dependent font sources that are searched by default. For example this will contain a "Windows\Fonts\" source on a Windows machines.
// We add this array to a new ArrayList to make adding or removing font entries much easier.
ArrayList fontSources = new ArrayList(FontSettings.DefaultInstance.GetFontsSources());

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FolderFontSource folderFontSource = new FolderFontSource("C:\\MyFonts\\", true);

// Add the custom folder which contains our fonts to the list of existing font sources.
fontSources.Add(folderFontSource);

// Convert the ArrayList of source back into a primitive array of FontSource objects.
FontSourceBase[] updatedFontSources = (FontSourceBase[]) fontSources.ToArray(typeof(FontSourceBase));

// Apply the new set of font sources to use.
FontSettings.DefaultInstance.SetFontsSources(updatedFontSources);

doc.Save(ArtifactsDir + "Rendering.SetFontsFolders.pdf");

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSourceBase Class

This is an abstract base class for the classes that allow the user to specify various font sources.

For a list of all members of this type, see FontSourceBase Members.

System.Object
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.FileFontSource
Aspose.Words.Fonts.FolderFontSource
Aspose.Words.Fonts.MemoryFontSource
Aspose.Words.Fonts.StreamFontSource
Aspose.Words.Fonts.SystemFontSource

[Visual Basic]
MustInherit Public Class FontSourceBase
[C#]
public abstract class FontSourceBase

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontSourceBase Members | Aspose.Words.Fonts Namespace


FontSourceBase Members

FontSourceBase overview

Public Instance Properties

Priority | Returns the font source priority.
Type | Returns the type of the font source.

Public Instance Methods

GetAvailableFonts Returns list of fonts available via this source.

See Also

FontSourceBase Class | Aspose.Words.Fonts Namespace


FontSourceBase Properties

The properties of the FontSourceBase class are listed below. For a complete list of FontSourceBase class members, see the FontSourceBase Members topic.

Public Instance Properties

Priority | Returns the font source priority.
Type | Returns the type of the font source.

See Also

FontSourceBase Class | Aspose.Words.Fonts Namespace


Priority Property

Aspose.Words

FontSourceBase.Priority Property

Returns the font source priority.

[Visual Basic]
Public ReadOnly Property Priority As Integer
[C#]
public int Priority {get;}

Remarks

This value is used when there are fonts with the same family name and style in different font sources. In this case Aspose.Words selects the font from the source with the higher priority value.

The default value is 0.

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

See Also

FontSourceBase Class | Aspose.Words.Fonts Namespace


Type Property

Aspose.Words

FontSourceBase.Type Property

Returns the type of the font source.

[Visual Basic]
MustOverride Public ReadOnly Property Type As FontSourceType
[C#]
public abstract FontSourceType Type {get;}

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

See Also

FontSourceBase Class | Aspose.Words.Fonts Namespace


FontSourceBase Methods

The methods of the FontSourceBase class are listed below. For a complete list of FontSourceBase class members, see the FontSourceBase Members topic.

Public Instance Methods

GetAvailableFonts Returns list of fonts available via this source.

See Also

FontSourceBase Class | Aspose.Words.Fonts Namespace


FontSourceBase.GetAvailableFonts Method

Returns list of fonts available via this source.

[Visual Basic]
Public Function GetAvailableFonts() As IList(Of PhysicalFontInfo)
[C#]
public IList<PhysicalFontInfo> GetAvailableFonts();

Example

Shows how to get available fonts and information about them.

[C#]

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FontSourceBase[] folderFontSource = { new FolderFontSource(MyDir + @"MyFonts\", true) };

foreach (PhysicalFontInfo fontInfo in folderFontSource[0].GetAvailableFonts())
{
    Console.WriteLine("FontFamilyName : {0}", fontInfo.FontFamilyName);
    Console.WriteLine("FullFontName  : {0}", fontInfo.FullFontName);
    Console.WriteLine("Version  : {0}", fontInfo.Version);
    Console.WriteLine("FilePath : {0}\n", fontInfo.FilePath);
}

See Also

FontSourceBase Class | Aspose.Words.Fonts Namespace


FontSourceType Enumeration

Specifies the type of a font source.

[Visual Basic]
Public Enum FontSourceType
[C#]
public enum FontSourceType

Example

Shows how to create a file font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Create a font source from a file in our system
FileFontSource fileFontSource = new FileFontSource(MyDir + "Alte DIN 1451 Mittelschrift.ttf", 0);

// Import the font source into our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { fileFontSource });

Assert.AreEqual(MyDir + "Alte DIN 1451 Mittelschrift.ttf", fileFontSource.FilePath);
Assert.AreEqual(FontSourceType.FontFile, fileFontSource.Type);
Assert.AreEqual(0, fileFontSource.Priority);

Members

Member Name | Description | Value
FontFile | A FileFontSource object that represents single font file. | 0
FontsFolder | A FolderFontSource object that represents folder with font files. | 1
MemoryFont | A MemoryFontSource object that represents single font in memory. | 2
SystemFonts | A SystemFontSource object that represents all fonts installed to the system. | 3
FontStream | A StreamFontSource object that represents a stream with font data. | 4

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Fonts Namespace


FontSubstitutionRule Class

This is an abstract base class for the font substitution rule.

For a list of all members of this type, see FontSubstitutionRule Members.

System.Object
Aspose.Words.Fonts.FontSubstitutionRule
Aspose.Words.Fonts.DefaultFontSubstitutionRule
Aspose.Words.Fonts.FontConfigSubstitutionRule
Aspose.Words.Fonts.FontInfoSubstitutionRule
Aspose.Words.Fonts.TableSubstitutionRule

[Visual Basic]
MustInherit Public Class FontSubstitutionRule
[C#]
public abstract class FontSubstitutionRule

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontSubstitutionRule Members | Aspose.Words.Fonts Namespace


FontSubstitutionRule Members

FontSubstitutionRule overview

Public Instance Properties

Enabled Specifies whether the rule is enabled or not.

See Also

FontSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontSubstitutionRule Properties

The properties of the FontSubstitutionRule class are listed below. For a complete list of FontSubstitutionRule class members, see the FontSubstitutionRule Members topic.

Public Instance Properties

Enabled Specifies whether the rule is enabled or not.

See Also

FontSubstitutionRule Class | Aspose.Words.Fonts Namespace


Enabled Property

Aspose.Words

FontSubstitutionRule.Enabled Property

Specifies whether the rule is enabled or not.

[Visual Basic]
Overridable Public Property Enabled As Boolean
[C#]
public virtual bool Enabled {get; set;}

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}
Shows how to access a document's system font source and set font substitutes.
[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

FontSubstitutionRule Class | Aspose.Words.Fonts Namespace


FontSubstitutionSettings Class

Specifies font substitution mechanism settings.

For a list of all members of this type, see FontSubstitutionSettings Members.

System.Object
Aspose.Words.Fonts.FontSubstitutionSettings

[Visual Basic]
Public Class FontSubstitutionSettings
[C#]
public class FontSubstitutionSettings

Remarks

Font substitution process consists of several rules which are checked one by one in specific order. If the first rule can't resolve the font then second rule is checked and so on.

The order of the rules is following: 1. Font config substitution rule (disabled by default) 2. Table substitution rule (enabled by default) 3. Font info substitution rule (enabled by default) 4. Default font rule (enabled by default)

Note that font info substitution rule will always resolve the font if FontInfo is available and will override the default font rule. If you want to use the default font rule then you should disable the font info substitution rule.

Note that font config substitution rule will resolve the font in most cases and thus overrides all other rules.

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontSubstitutionSettings Members | Aspose.Words.Fonts Namespace


FontSubstitutionSettings Members

FontSubstitutionSettings overview

Public Instance Properties

DefaultFontSubstitution | Settings related to default font substitution rule.
FontConfigSubstitution | Settings related to font config substitution rule.
FontInfoSubstitution | Settings related to font info substitution rule.
TableSubstitution | Settings related to table substitution rule.

See Also

FontSubstitutionSettings Class | Aspose.Words.Fonts Namespace


FontSubstitutionSettings Properties

The properties of the FontSubstitutionSettings class are listed below. For a complete list of FontSubstitutionSettings class members, see the FontSubstitutionSettings Members topic.

Public Instance Properties

DefaultFontSubstitution | Settings related to default font substitution rule.
FontConfigSubstitution | Settings related to font config substitution rule.
FontInfoSubstitution | Settings related to font info substitution rule.
TableSubstitution | Settings related to table substitution rule.

See Also

FontSubstitutionSettings Class | Aspose.Words.Fonts Namespace


DefaultFontSubstitution Property

Aspose.Words

FontSubstitutionSettings.DefaultFontSubstitution Property

Settings related to default font substitution rule.

[Visual Basic]
Public ReadOnly Property DefaultFontSubstitution As DefaultFontSubstitutionRule
[C#]
public DefaultFontSubstitutionRule DefaultFontSubstitution {get;}

Example

Shows how to set the default font substitution rule.

[C#]

// Create a blank document and a new FontSettings property
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Get the default substitution rule within FontSettings, which will be enabled by default and will substitute all missing fonts with "Times New Roman"
DefaultFontSubstitutionRule defaultFontSubstitutionRule = fontSettings.SubstitutionSettings.DefaultFontSubstitution;
Assert.True(defaultFontSubstitutionRule.Enabled);
Assert.AreEqual("Times New Roman", defaultFontSubstitutionRule.DefaultFontName);

// Set the default font substitute to "Courier New"
defaultFontSubstitutionRule.DefaultFontName = "Courier New";

// Using a document builder, add some text in a font that we don't have to see the substitution take place,
// and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Font.Name = "Missing Font";
builder.Writeln("Line written in a missing font, which will be substituted with Courier New.");

doc.Save(ArtifactsDir + "Font.DefaultFontSubstitutionRule.pdf");

See Also

FontSubstitutionSettings Class | Aspose.Words.Fonts Namespace


FontConfigSubstitution Property

Aspose.Words

FontSubstitutionSettings.FontConfigSubstitution Property

Settings related to font config substitution rule.

[Visual Basic]
Public ReadOnly Property FontConfigSubstitution As FontConfigSubstitutionRule
[C#]
public FontConfigSubstitutionRule FontConfigSubstitution {get;}

Example

Shows OS-dependent font config substitution.

[C#]

// Create a new FontSettings object and get its font config substitution rule
FontSettings fontSettings = new FontSettings();
FontConfigSubstitutionRule fontConfigSubstitution = fontSettings.SubstitutionSettings.FontConfigSubstitution;

// The FontConfigSubstitutionRule object works differently on Windows/non-Windows platforms
// On Windows, it is unavailable
PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE;

if (isWindows)
{
    Assert.False(fontConfigSubstitution.Enabled);
    Assert.False(fontConfigSubstitution.IsFontConfigAvailable());
}

// On Linux/Mac, we will have access and will be able to perform operations
bool isLinuxOrMac = pid == PlatformID.Unix || pid == PlatformID.MacOSX;

if (isLinuxOrMac)
{
    Assert.True(fontConfigSubstitution.Enabled);
    Assert.True(fontConfigSubstitution.IsFontConfigAvailable());

    fontConfigSubstitution.ResetCache();
}

See Also

FontSubstitutionSettings Class | Aspose.Words.Fonts Namespace


FontInfoSubstitution Property

Aspose.Words

FontSubstitutionSettings.FontInfoSubstitution Property

Settings related to font info substitution rule.

[Visual Basic]
Public ReadOnly Property FontInfoSubstitution As FontInfoSubstitutionRule
[C#]
public FontInfoSubstitutionRule FontInfoSubstitution {get;}

Example

Shows how to set the property for finding the closest match font among the available font sources instead missing font.

[C#]

Document doc = new Document(MyDir + "Font.EnableFontSubstitution.docx");

// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;

FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.DefaultFontSubstitution.DefaultFontName = "Arial"; ;
fontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;

See Also

FontSubstitutionSettings Class | Aspose.Words.Fonts Namespace


TableSubstitution Property

Aspose.Words

FontSubstitutionSettings.TableSubstitution Property

Settings related to table substitution rule.

[Visual Basic]
Public ReadOnly Property TableSubstitution As TableSubstitutionRule
[C#]
public TableSubstitutionRule TableSubstitution {get;}

Example

Shows how to work with custom font substitution tables.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;

// If we select fonts exclusively from our own folder, we will need a custom substitution table
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// There are two ways of loading a substitution table from a file in the local file system
// 1: Loading from a stream
using (FileStream fileStream = new FileStream(MyDir + "Font.TableSubstitutionRule.Custom.xml", FileMode.Open))
{
    tableSubstitutionRule.Load(fileStream);
}

// 2: Load directly from file
tableSubstitutionRule.Load(MyDir + "Font.TableSubstitutionRule.Custom.xml");

// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font", which we don't have,
// and then with "Kreon", found in the "MyFonts" folder
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());

// If we find this substitution table lacking, we can also expand it programmatically
// In this case, we add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes()
// In case "Arvo" is unavailable, our table will look for "M+ 2m"
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// SetSubstitutes() can set a new list of substitute fonts for a font
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// TO demonstrate substitution, write text in fonts we have no access to and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");

builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");

doc.Save(ArtifactsDir + "Font.TableSubstitutionRule.Custom.pdf");

See Also

FontSubstitutionSettings Class | Aspose.Words.Fonts Namespace


MemoryFontSource Class

Represents the single TrueType font file stored in memory.

For a list of all members of this type, see MemoryFontSource Members.

System.Object
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.MemoryFontSource

[Visual Basic]
Public Class MemoryFontSource
Inherits FontSourceBase
[C#]
public class MemoryFontSource : FontSourceBase

Example

Shows how to create a memory font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Import a font file, putting its contents into a byte array
byte[] fontBytes = File.ReadAllBytes(MyDir + "Alte DIN 1451 Mittelschrift.ttf");

// Create a memory font source from our array
MemoryFontSource memoryFontSource = new MemoryFontSource(fontBytes, 0);

// Add that font source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { memoryFontSource });

Assert.AreEqual(52208, memoryFontSource.FontData.Length);
Assert.AreEqual(FontSourceType.MemoryFont, memoryFontSource.Type);
Assert.AreEqual(0, memoryFontSource.Priority);

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MemoryFontSource Members | Aspose.Words.Fonts Namespace


MemoryFontSource Members

MemoryFontSource overview

Public Instance Constructors

MemoryFontSource Overloaded. Initializes a new instance of the MemoryFontSource class.

Public Instance Properties

FontData | Binary font data.
Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) Returns list of fonts available via this source.

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


MemoryFontSource Constructor

Ctor.

Overload List

Ctor.

public MemoryFontSource(byte[]);

Ctor.

public MemoryFontSource(byte[],int);

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


MemoryFontSource Constructor (Byte[])

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal fontData As Byte() _
)
[C#]
public MemoryFontSource(
byte[] fontData
);

Parameters

fontData
Binary font data.

Example

Shows how to create a memory font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Import a font file, putting its contents into a byte array
byte[] fontBytes = File.ReadAllBytes(MyDir + "Alte DIN 1451 Mittelschrift.ttf");

// Create a memory font source from our array
MemoryFontSource memoryFontSource = new MemoryFontSource(fontBytes, 0);

// Add that font source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { memoryFontSource });

Assert.AreEqual(52208, memoryFontSource.FontData.Length);
Assert.AreEqual(FontSourceType.MemoryFont, memoryFontSource.Type);
Assert.AreEqual(0, memoryFontSource.Priority);

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace | MemoryFontSource Constructor Overload List


MemoryFontSource Constructor (Byte[], Int32)

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal fontData As Byte(), _
ByVal priority As Integer _
)
[C#]
public MemoryFontSource(
byte[] fontData,
int priority
);

Parameters

fontData
Binary font data.
priority
Font source priority. See the Priority property description for more information.

Example

Shows how to create a memory font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Import a font file, putting its contents into a byte array
byte[] fontBytes = File.ReadAllBytes(MyDir + "Alte DIN 1451 Mittelschrift.ttf");

// Create a memory font source from our array
MemoryFontSource memoryFontSource = new MemoryFontSource(fontBytes, 0);

// Add that font source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { memoryFontSource });

Assert.AreEqual(52208, memoryFontSource.FontData.Length);
Assert.AreEqual(FontSourceType.MemoryFont, memoryFontSource.Type);
Assert.AreEqual(0, memoryFontSource.Priority);

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace | MemoryFontSource Constructor Overload List


MemoryFontSource Properties

The properties of the MemoryFontSource class are listed below. For a complete list of MemoryFontSource class members, see the MemoryFontSource Members topic.

Public Instance Properties

FontData | Binary font data.
Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


FontData Property

Aspose.Words

MemoryFontSource.FontData Property

Binary font data.

[Visual Basic]
Public ReadOnly Property FontData As Byte()
[C#]
public byte[] FontData {get;}

Example

Shows how to create a memory font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Import a font file, putting its contents into a byte array
byte[] fontBytes = File.ReadAllBytes(MyDir + "Alte DIN 1451 Mittelschrift.ttf");

// Create a memory font source from our array
MemoryFontSource memoryFontSource = new MemoryFontSource(fontBytes, 0);

// Add that font source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { memoryFontSource });

Assert.AreEqual(52208, memoryFontSource.FontData.Length);
Assert.AreEqual(FontSourceType.MemoryFont, memoryFontSource.Type);
Assert.AreEqual(0, memoryFontSource.Priority);

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


Type Property

Aspose.Words

MemoryFontSource.Type Property

Returns the type of the font source.

[Visual Basic]
Overrides Public ReadOnly Property Type As FontSourceType
[C#]
public override FontSourceType Type {get;}

Example

Shows how to create a memory font source.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// Import a font file, putting its contents into a byte array
byte[] fontBytes = File.ReadAllBytes(MyDir + "Alte DIN 1451 Mittelschrift.ttf");

// Create a memory font source from our array
MemoryFontSource memoryFontSource = new MemoryFontSource(fontBytes, 0);

// Add that font source to our document
doc.FontSettings.SetFontsSources(new FontSourceBase[] { memoryFontSource });

Assert.AreEqual(52208, memoryFontSource.FontData.Length);
Assert.AreEqual(FontSourceType.MemoryFont, memoryFontSource.Type);
Assert.AreEqual(0, memoryFontSource.Priority);

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


PhysicalFontInfo Class

Specifies information about physical font available to Aspose.Words font engine.

For a list of all members of this type, see PhysicalFontInfo Members.

System.Object
Aspose.Words.Fonts.PhysicalFontInfo

[Visual Basic]
Public Class PhysicalFontInfo
[C#]
public class PhysicalFontInfo

Example

Shows how to get available fonts and information about them.

[C#]

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FontSourceBase[] folderFontSource = { new FolderFontSource(MyDir + @"MyFonts\", true) };

foreach (PhysicalFontInfo fontInfo in folderFontSource[0].GetAvailableFonts())
{
    Console.WriteLine("FontFamilyName : {0}", fontInfo.FontFamilyName);
    Console.WriteLine("FullFontName  : {0}", fontInfo.FullFontName);
    Console.WriteLine("Version  : {0}", fontInfo.Version);
    Console.WriteLine("FilePath : {0}\n", fontInfo.FilePath);
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PhysicalFontInfo Members | Aspose.Words.Fonts Namespace


PhysicalFontInfo Members

PhysicalFontInfo overview

Public Instance Properties

FilePath | Path to the font file if any.
FontFamilyName | Family name of the font.
FullFontName | Full name of the font.
Version | Version string of the font.

See Also

PhysicalFontInfo Class | Aspose.Words.Fonts Namespace


PhysicalFontInfo Properties

The properties of the PhysicalFontInfo class are listed below. For a complete list of PhysicalFontInfo class members, see the PhysicalFontInfo Members topic.

Public Instance Properties

FilePath | Path to the font file if any.
FontFamilyName | Family name of the font.
FullFontName | Full name of the font.
Version | Version string of the font.

See Also

PhysicalFontInfo Class | Aspose.Words.Fonts Namespace


FilePath Property

Aspose.Words

PhysicalFontInfo.FilePath Property

Path to the font file if any.

[Visual Basic]
Public ReadOnly Property FilePath As String
[C#]
public string FilePath {get;}

Example

Shows how to get available fonts and information about them.

[C#]

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FontSourceBase[] folderFontSource = { new FolderFontSource(MyDir + @"MyFonts\", true) };

foreach (PhysicalFontInfo fontInfo in folderFontSource[0].GetAvailableFonts())
{
    Console.WriteLine("FontFamilyName : {0}", fontInfo.FontFamilyName);
    Console.WriteLine("FullFontName  : {0}", fontInfo.FullFontName);
    Console.WriteLine("Version  : {0}", fontInfo.Version);
    Console.WriteLine("FilePath : {0}\n", fontInfo.FilePath);
}

See Also

PhysicalFontInfo Class | Aspose.Words.Fonts Namespace


FontFamilyName Property

Aspose.Words

PhysicalFontInfo.FontFamilyName Property

Family name of the font.

[Visual Basic]
Public ReadOnly Property FontFamilyName As String
[C#]
public string FontFamilyName {get;}

Example

Shows how to get available fonts and information about them.

[C#]

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FontSourceBase[] folderFontSource = { new FolderFontSource(MyDir + @"MyFonts\", true) };

foreach (PhysicalFontInfo fontInfo in folderFontSource[0].GetAvailableFonts())
{
    Console.WriteLine("FontFamilyName : {0}", fontInfo.FontFamilyName);
    Console.WriteLine("FullFontName  : {0}", fontInfo.FullFontName);
    Console.WriteLine("Version  : {0}", fontInfo.Version);
    Console.WriteLine("FilePath : {0}\n", fontInfo.FilePath);
}

See Also

PhysicalFontInfo Class | Aspose.Words.Fonts Namespace


FullFontName Property

Aspose.Words

PhysicalFontInfo.FullFontName Property

Full name of the font.

[Visual Basic]
Public ReadOnly Property FullFontName As String
[C#]
public string FullFontName {get;}

Example

Shows how to get available fonts and information about them.

[C#]

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FontSourceBase[] folderFontSource = { new FolderFontSource(MyDir + @"MyFonts\", true) };

foreach (PhysicalFontInfo fontInfo in folderFontSource[0].GetAvailableFonts())
{
    Console.WriteLine("FontFamilyName : {0}", fontInfo.FontFamilyName);
    Console.WriteLine("FullFontName  : {0}", fontInfo.FullFontName);
    Console.WriteLine("Version  : {0}", fontInfo.Version);
    Console.WriteLine("FilePath : {0}\n", fontInfo.FilePath);
}

See Also

PhysicalFontInfo Class | Aspose.Words.Fonts Namespace


Version Property

Aspose.Words

PhysicalFontInfo.Version Property

Version string of the font.

[Visual Basic]
Public ReadOnly Property Version As String
[C#]
public string Version {get;}

Example

Shows how to get available fonts and information about them.

[C#]

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FontSourceBase[] folderFontSource = { new FolderFontSource(MyDir + @"MyFonts\", true) };

foreach (PhysicalFontInfo fontInfo in folderFontSource[0].GetAvailableFonts())
{
    Console.WriteLine("FontFamilyName : {0}", fontInfo.FontFamilyName);
    Console.WriteLine("FullFontName  : {0}", fontInfo.FullFontName);
    Console.WriteLine("Version  : {0}", fontInfo.Version);
    Console.WriteLine("FilePath : {0}\n", fontInfo.FilePath);
}

See Also

PhysicalFontInfo Class | Aspose.Words.Fonts Namespace


StreamFontSource Class

Base class for user-defined stream font source.

For a list of all members of this type, see StreamFontSource Members.

System.Object
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.StreamFontSource

[Visual Basic]
MustInherit Public Class StreamFontSource
Inherits FontSourceBase
[C#]
public abstract class StreamFontSource : FontSourceBase

Remarks

In order to use the stream font source you should create a derived class from the StreamFontSource and provide implementation of the OpenFontDataStream method.

OpenFontDataStream method could be called several times. For the first time it will be called when Aspose.Words scans the provided font sources to get the list of available fonts. Later it may be called if the font is used in the document to parse the font data and to embed the font data to some output formats.

StreamFontSource may be useful because it allows to load the font data only when it is required and not to store it in the memory for the FontSettings lifetime.

Example

Shows how to allows to load fonts from stream.

[C#]

public void StreamFontSourceFileRendering()
{
    FontSettings fontSettings = new FontSettings();
    fontSettings.SetFontsSources(new FontSourceBase[] { new StreamFontSourceFile() });

    DocumentBuilder builder = new DocumentBuilder();
    builder.Document.FontSettings = fontSettings;
    builder.Font.Name = "Kreon-Regular";
    builder.Writeln("Test aspose text when saving to PDF.");

    builder.Document.Save(ArtifactsDir + "Font.StreamFontSourceFileRendering.pdf");
}

/// <summary>
/// Load the font data only when it is required and not to store it in the memory for the "FontSettings" lifetime.
/// </summary>
private class StreamFontSourceFile : StreamFontSource
{
    public override Stream OpenFontDataStream()
    {
        return File.OpenRead(FontsDir + "Kreon-Regular.ttf");
    }
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

StreamFontSource Members | Aspose.Words.Fonts Namespace


StreamFontSource Members

StreamFontSource overview

Public Instance Properties

Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) | Returns list of fonts available via this source.
OpenFontDataStream | This method should open the stream with font data on demand.

See Also

StreamFontSource Class | Aspose.Words.Fonts Namespace


StreamFontSource Properties

The properties of the StreamFontSource class are listed below. For a complete list of StreamFontSource class members, see the StreamFontSource Members topic.

Public Instance Properties

Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

See Also

StreamFontSource Class | Aspose.Words.Fonts Namespace


Type Property

Aspose.Words

StreamFontSource.Type Property

Returns the type of the font source.

[Visual Basic]
NotOverridable Public ReadOnly Property Type As FontSourceType
[C#]
public FontSourceType Type {get;}

See Also

StreamFontSource Class | Aspose.Words.Fonts Namespace


StreamFontSource Methods

The methods of the StreamFontSource class are listed below. For a complete list of StreamFontSource class members, see the StreamFontSource Members topic.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) | Returns list of fonts available via this source.
OpenFontDataStream | This method should open the stream with font data on demand.

See Also

StreamFontSource Class | Aspose.Words.Fonts Namespace


StreamFontSource.OpenFontDataStream Method

This method should open the stream with font data on demand.

[Visual Basic]
MustOverride Public Function OpenFontDataStream() As Stream
[C#]
public abstract Stream OpenFontDataStream();

Return Value

Font data stream.

Remarks

The stream will be closed after reading. There is no need to close it explicitly.

Example

Shows how to allows to load fonts from stream.

[C#]

public void StreamFontSourceFileRendering()
{
    FontSettings fontSettings = new FontSettings();
    fontSettings.SetFontsSources(new FontSourceBase[] { new StreamFontSourceFile() });

    DocumentBuilder builder = new DocumentBuilder();
    builder.Document.FontSettings = fontSettings;
    builder.Font.Name = "Kreon-Regular";
    builder.Writeln("Test aspose text when saving to PDF.");

    builder.Document.Save(ArtifactsDir + "Font.StreamFontSourceFileRendering.pdf");
}

/// <summary>
/// Load the font data only when it is required and not to store it in the memory for the "FontSettings" lifetime.
/// </summary>
private class StreamFontSourceFile : StreamFontSource
{
    public override Stream OpenFontDataStream()
    {
        return File.OpenRead(FontsDir + "Kreon-Regular.ttf");
    }
}

See Also

StreamFontSource Class | Aspose.Words.Fonts Namespace


SystemFontSource Class

Represents all TrueType fonts installed to the system.

For a list of all members of this type, see SystemFontSource Members.

System.Object
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.SystemFontSource

[Visual Basic]
Public Class SystemFontSource
Inherits FontSourceBase
[C#]
public class SystemFontSource : FontSourceBase

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SystemFontSource Members | Aspose.Words.Fonts Namespace


SystemFontSource Members

SystemFontSource overview

Public Static (Shared) Methods

GetSystemFontFolders Returns system font folders or empty array if folders are not accessible.

Public Instance Constructors

SystemFontSource Overloaded. Initializes a new instance of the SystemFontSource class.

Public Instance Properties

Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) Returns list of fonts available via this source.

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


SystemFontSource Constructor

Ctor.

Overload List

Ctor.

public SystemFontSource();

Ctor.

public SystemFontSource(int);

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


SystemFontSource Constructor ()

Ctor.

[Visual Basic]
Overloads Public Sub New()
[C#]
public SystemFontSource();

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace | SystemFontSource Constructor Overload List


SystemFontSource Constructor (Int32)

Ctor.

[Visual Basic]
Overloads Public Sub New( _
ByVal priority As Integer _
)
[C#]
public SystemFontSource(
int priority
);

Parameters

priority
Font source priority. See the Priority property description for more information.

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace | SystemFontSource Constructor Overload List


SystemFontSource Properties

The properties of the SystemFontSource class are listed below. For a complete list of SystemFontSource class members, see the SystemFontSource Members topic.

Public Instance Properties

Priority (inherited from FontSourceBase) | Returns the font source priority.
Type | Returns the type of the font source.

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


Type Property

Aspose.Words

SystemFontSource.Type Property

Returns the type of the font source.

[Visual Basic]
Overrides Public ReadOnly Property Type As FontSourceType
[C#]
public override FontSourceType Type {get;}

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


SystemFontSource Methods

The methods of the SystemFontSource class are listed below. For a complete list of SystemFontSource class members, see the SystemFontSource Members topic.

Public Static (Shared) Methods

GetSystemFontFolders Returns system font folders or empty array if folders are not accessible.

Public Instance Methods

GetAvailableFonts (inherited from IList<PhysicalFontInfo>) Returns list of fonts available via this source.

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


SystemFontSource.GetSystemFontFolders Method

Returns system font folders or empty array if folders are not accessible.

[Visual Basic]
Public Shared Function GetSystemFontFolders() As String()
[C#]
public static string[] GetSystemFontFolders();

Remarks

On some platforms Aspose.Words could search system fonts not only through folders but in other sources too. For example, on Windows platform Aspose.Words search fonts also in the registry.

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule Class

Table font substitution rule.

For a list of all members of this type, see TableSubstitutionRule Members.

System.Object
Aspose.Words.Fonts.FontSubstitutionRule
Aspose.Words.Fonts.TableSubstitutionRule

[Visual Basic]
Public Class TableSubstitutionRule
Inherits FontSubstitutionRule
[C#]
public class TableSubstitutionRule : FontSubstitutionRule

Remarks

This rule defines the list of substitute font names to be used if the original font is not available. Substitutes will be checked for the font name and the AltName (if any).

Example

Shows how to access font substitution tables for Windows and Linux.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
tableSubstitutionRule.LoadWindowsSettings();

// In Windows, the default substitute for the "Times New Roman CE" font is "Times New Roman"
Assert.AreEqual(new[] { "Times New Roman" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// We can save the table for viewing in the form of an XML document
tableSubstitutionRule.Save(ArtifactsDir + "Font.TableSubstitutionRule.Windows.xml");

// Linux has its own substitution table
// If "FreeSerif" is unavailable to substitute for "Times New Roman CE", we then look for "Liberation Serif", and so on
tableSubstitutionRule.LoadLinuxSettings();
Assert.AreEqual(new[] { "FreeSerif", "Liberation Serif", "DejaVu Serif" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// Save the Linux substitution table using a stream
using (FileStream fileStream = new FileStream(ArtifactsDir + "Font.TableSubstitutionRule.Linux.xml", FileMode.Create))
{
    tableSubstitutionRule.Save(fileStream);
}

Requirements

Namespace: Aspose.Words.Fonts

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TableSubstitutionRule Members | Aspose.Words.Fonts Namespace


TableSubstitutionRule Members

TableSubstitutionRule overview

Public Instance Properties

Enabled (inherited from FontSubstitutionRule) Specifies whether the rule is enabled or not.

Public Instance Methods

AddSubstitutes | Adds substitute font names for given original font name.
GetSubstitutes | Returns array containing substitute font names for the specified original font name.
Load | Overloaded. Loads table substitution settings from XML file.
LoadAndroidSettings | Loads predefined table substitution settings for Linux platform.
LoadLinuxSettings | Loads predefined table substitution settings for Linux platform.
LoadWindowsSettings | Loads predefined table substitution settings for Windows platform.
Save | Overloaded. Saves the current table substitution settings to file.
SetSubstitutes | Override substitute font names for given original font name.

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule Methods

The methods of the TableSubstitutionRule class are listed below. For a complete list of TableSubstitutionRule class members, see the TableSubstitutionRule Members topic.

Public Instance Methods

AddSubstitutes | Adds substitute font names for given original font name.
GetSubstitutes | Returns array containing substitute font names for the specified original font name.
Load | Overloaded. Loads table substitution settings from XML file.
LoadAndroidSettings | Loads predefined table substitution settings for Linux platform.
LoadLinuxSettings | Loads predefined table substitution settings for Linux platform.
LoadWindowsSettings | Loads predefined table substitution settings for Windows platform.
Save | Overloaded. Saves the current table substitution settings to file.
SetSubstitutes | Override substitute font names for given original font name.

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule.AddSubstitutes Method

Adds substitute font names for given original font name.

[Visual Basic]
Public Sub AddSubstitutes( _
ByVal originalFontName As String, _
ParamArray substituteFontNames As String() _
)
[C#]
public void AddSubstitutes(
string originalFontName,
params string[] substituteFontNames
);

Parameters

originalFontName
Original font name.
substituteFontNames
List of alternative font names.

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Shows how to work with custom font substitution tables.
[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;

// If we select fonts exclusively from our own folder, we will need a custom substitution table
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// There are two ways of loading a substitution table from a file in the local file system
// 1: Loading from a stream
using (FileStream fileStream = new FileStream(MyDir + "Font.TableSubstitutionRule.Custom.xml", FileMode.Open))
{
    tableSubstitutionRule.Load(fileStream);
}

// 2: Load directly from file
tableSubstitutionRule.Load(MyDir + "Font.TableSubstitutionRule.Custom.xml");

// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font", which we don't have,
// and then with "Kreon", found in the "MyFonts" folder
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());

// If we find this substitution table lacking, we can also expand it programmatically
// In this case, we add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes()
// In case "Arvo" is unavailable, our table will look for "M+ 2m"
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// SetSubstitutes() can set a new list of substitute fonts for a font
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// TO demonstrate substitution, write text in fonts we have no access to and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");

builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");

doc.Save(ArtifactsDir + "Font.TableSubstitutionRule.Custom.pdf");

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule.GetSubstitutes Method

Returns array containing substitute font names for the specified original font name.

[Visual Basic]
Public Function GetSubstitutes( _
ByVal originalFontName As String _
) As IEnumerable(Of String)
[C#]
public IEnumerable<string> GetSubstitutes(
string originalFontName
);

Parameters

originalFontName
Original font name.

Return Value

List of alternative font names.

Example

Shows how to access a document's system font source and set font substitutes.

[C#]

Document doc = new Document();

// Create a font settings object for our document
doc.FontSettings = new FontSettings();

// By default we always start with a system font source
Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);

SystemFontSource systemFontSource = (SystemFontSource)doc.FontSettings.GetFontsSources()[0];
Assert.AreEqual(FontSourceType.SystemFonts, systemFontSource.Type);
Assert.AreEqual(0, systemFontSource.Priority);

PlatformID pid = Environment.OSVersion.Platform;
bool isWindows = (pid == PlatformID.Win32NT) || (pid == PlatformID.Win32S) || (pid == PlatformID.Win32Windows) || (pid == PlatformID.WinCE);
if (isWindows)
{
    string fontsPath = @"C:\WINDOWS\Fonts";
    Assert.AreEqual(fontsPath.ToLower(), SystemFontSource.GetSystemFontFolders().FirstOrDefault()?.ToLower());
}

foreach (string systemFontFolder in SystemFontSource.GetSystemFontFolders())
{
    Console.WriteLine(systemFontFolder);
}

// Set a font that exists in the windows fonts directory as a substitute for one that doesn't
doc.FontSettings.SubstitutionSettings.FontInfoSubstitution.Enabled = true;
doc.FontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Kreon-Regular", new string[] { "Calibri" });

Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Assert.Contains("Calibri", doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").ToArray());

// Alternatively, we could add a folder font source in which the corresponding folder contains the font
FolderFontSource folderFontSource = new FolderFontSource(MyDir + "MyFonts", false);
doc.FontSettings.SetFontsSources(new FontSourceBase[] { systemFontSource, folderFontSource });
Assert.AreEqual(2, doc.FontSettings.GetFontsSources().Length);

// Resetting the font sources still leaves us with the system font source as well as our substitutes
doc.FontSettings.ResetFontSources();

Assert.AreEqual(1, doc.FontSettings.GetFontsSources().Length);
Assert.AreEqual(FontSourceType.SystemFonts, doc.FontSettings.GetFontsSources()[0].Type);
Assert.AreEqual(1, doc.FontSettings.SubstitutionSettings.TableSubstitution.GetSubstitutes("Kreon-Regular").Count());
Shows how to work with custom font substitution tables.
[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;

// If we select fonts exclusively from our own folder, we will need a custom substitution table
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// There are two ways of loading a substitution table from a file in the local file system
// 1: Loading from a stream
using (FileStream fileStream = new FileStream(MyDir + "Font.TableSubstitutionRule.Custom.xml", FileMode.Open))
{
    tableSubstitutionRule.Load(fileStream);
}

// 2: Load directly from file
tableSubstitutionRule.Load(MyDir + "Font.TableSubstitutionRule.Custom.xml");

// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font", which we don't have,
// and then with "Kreon", found in the "MyFonts" folder
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());

// If we find this substitution table lacking, we can also expand it programmatically
// In this case, we add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes()
// In case "Arvo" is unavailable, our table will look for "M+ 2m"
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// SetSubstitutes() can set a new list of substitute fonts for a font
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// TO demonstrate substitution, write text in fonts we have no access to and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");

builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");

doc.Save(ArtifactsDir + "Font.TableSubstitutionRule.Custom.pdf");

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


Load Method

Aspose.Words

TableSubstitutionRule.Load Method

Loads table substitution settings from XML stream.

Overload List

Loads table substitution settings from XML stream.

public void Load(Stream);

Loads table substitution settings from XML file.

public void Load(string);

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule.Load Method (Stream)

Loads table substitution settings from XML stream.

[Visual Basic]
Overloads Public Sub Load( _
ByVal stream As Stream _
)
[C#]
public void Load(
Stream stream
);

Parameters

stream
Input stream.

Example

Shows how to work with custom font substitution tables.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;

// If we select fonts exclusively from our own folder, we will need a custom substitution table
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// There are two ways of loading a substitution table from a file in the local file system
// 1: Loading from a stream
using (FileStream fileStream = new FileStream(MyDir + "Font.TableSubstitutionRule.Custom.xml", FileMode.Open))
{
    tableSubstitutionRule.Load(fileStream);
}

// 2: Load directly from file
tableSubstitutionRule.Load(MyDir + "Font.TableSubstitutionRule.Custom.xml");

// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font", which we don't have,
// and then with "Kreon", found in the "MyFonts" folder
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());

// If we find this substitution table lacking, we can also expand it programmatically
// In this case, we add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes()
// In case "Arvo" is unavailable, our table will look for "M+ 2m"
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// SetSubstitutes() can set a new list of substitute fonts for a font
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// TO demonstrate substitution, write text in fonts we have no access to and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");

builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");

doc.Save(ArtifactsDir + "Font.TableSubstitutionRule.Custom.pdf");

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace | TableSubstitutionRule.Load Overload List


TableSubstitutionRule.Load Method (String)

Loads table substitution settings from XML file.

[Visual Basic]
Overloads Public Sub Load( _
ByVal fileName As String _
)
[C#]
public void Load(
string fileName
);

Parameters

fileName
Input file name.

Example

Shows how to work with custom font substitution tables.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;

// If we select fonts exclusively from our own folder, we will need a custom substitution table
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// There are two ways of loading a substitution table from a file in the local file system
// 1: Loading from a stream
using (FileStream fileStream = new FileStream(MyDir + "Font.TableSubstitutionRule.Custom.xml", FileMode.Open))
{
    tableSubstitutionRule.Load(fileStream);
}

// 2: Load directly from file
tableSubstitutionRule.Load(MyDir + "Font.TableSubstitutionRule.Custom.xml");

// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font", which we don't have,
// and then with "Kreon", found in the "MyFonts" folder
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());

// If we find this substitution table lacking, we can also expand it programmatically
// In this case, we add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes()
// In case "Arvo" is unavailable, our table will look for "M+ 2m"
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// SetSubstitutes() can set a new list of substitute fonts for a font
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// TO demonstrate substitution, write text in fonts we have no access to and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");

builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");

doc.Save(ArtifactsDir + "Font.TableSubstitutionRule.Custom.pdf");

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace | TableSubstitutionRule.Load Overload List


TableSubstitutionRule.LoadAndroidSettings Method

Loads predefined table substitution settings for Linux platform.

[Visual Basic]
Public Sub LoadAndroidSettings()
[C#]
public void LoadAndroidSettings();

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule.LoadLinuxSettings Method

Loads predefined table substitution settings for Linux platform.

[Visual Basic]
Public Sub LoadLinuxSettings()
[C#]
public void LoadLinuxSettings();

Example

Shows how to access font substitution tables for Windows and Linux.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
tableSubstitutionRule.LoadWindowsSettings();

// In Windows, the default substitute for the "Times New Roman CE" font is "Times New Roman"
Assert.AreEqual(new[] { "Times New Roman" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// We can save the table for viewing in the form of an XML document
tableSubstitutionRule.Save(ArtifactsDir + "Font.TableSubstitutionRule.Windows.xml");

// Linux has its own substitution table
// If "FreeSerif" is unavailable to substitute for "Times New Roman CE", we then look for "Liberation Serif", and so on
tableSubstitutionRule.LoadLinuxSettings();
Assert.AreEqual(new[] { "FreeSerif", "Liberation Serif", "DejaVu Serif" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// Save the Linux substitution table using a stream
using (FileStream fileStream = new FileStream(ArtifactsDir + "Font.TableSubstitutionRule.Linux.xml", FileMode.Create))
{
    tableSubstitutionRule.Save(fileStream);
}

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule.LoadWindowsSettings Method

Loads predefined table substitution settings for Windows platform.

[Visual Basic]
Public Sub LoadWindowsSettings()
[C#]
public void LoadWindowsSettings();

Example

Shows how to access font substitution tables for Windows and Linux.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
tableSubstitutionRule.LoadWindowsSettings();

// In Windows, the default substitute for the "Times New Roman CE" font is "Times New Roman"
Assert.AreEqual(new[] { "Times New Roman" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// We can save the table for viewing in the form of an XML document
tableSubstitutionRule.Save(ArtifactsDir + "Font.TableSubstitutionRule.Windows.xml");

// Linux has its own substitution table
// If "FreeSerif" is unavailable to substitute for "Times New Roman CE", we then look for "Liberation Serif", and so on
tableSubstitutionRule.LoadLinuxSettings();
Assert.AreEqual(new[] { "FreeSerif", "Liberation Serif", "DejaVu Serif" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// Save the Linux substitution table using a stream
using (FileStream fileStream = new FileStream(ArtifactsDir + "Font.TableSubstitutionRule.Linux.xml", FileMode.Create))
{
    tableSubstitutionRule.Save(fileStream);
}

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


Save Method

Aspose.Words

TableSubstitutionRule.Save Method

Saves the current table substitution settings to stream.

Overload List

Saves the current table substitution settings to stream.

public void Save(Stream);

Saves the current table substitution settings to file.

public void Save(string);

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


TableSubstitutionRule.Save Method (Stream)

Saves the current table substitution settings to stream.

[Visual Basic]
Overloads Public Sub Save( _
ByVal outputStream As Stream _
)
[C#]
public void Save(
Stream outputStream
);

Parameters

outputStream
Output stream.

Example

Shows how to access font substitution tables for Windows and Linux.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
tableSubstitutionRule.LoadWindowsSettings();

// In Windows, the default substitute for the "Times New Roman CE" font is "Times New Roman"
Assert.AreEqual(new[] { "Times New Roman" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// We can save the table for viewing in the form of an XML document
tableSubstitutionRule.Save(ArtifactsDir + "Font.TableSubstitutionRule.Windows.xml");

// Linux has its own substitution table
// If "FreeSerif" is unavailable to substitute for "Times New Roman CE", we then look for "Liberation Serif", and so on
tableSubstitutionRule.LoadLinuxSettings();
Assert.AreEqual(new[] { "FreeSerif", "Liberation Serif", "DejaVu Serif" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// Save the Linux substitution table using a stream
using (FileStream fileStream = new FileStream(ArtifactsDir + "Font.TableSubstitutionRule.Linux.xml", FileMode.Create))
{
    tableSubstitutionRule.Save(fileStream);
}

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace | TableSubstitutionRule.Save Overload List


TableSubstitutionRule.Save Method (String)

Saves the current table substitution settings to file.

[Visual Basic]
Overloads Public Sub Save( _
ByVal fileName As String _
)
[C#]
public void Save(
string fileName
);

Parameters

fileName
Output file name.

Example

Shows how to access font substitution tables for Windows and Linux.

[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;
tableSubstitutionRule.LoadWindowsSettings();

// In Windows, the default substitute for the "Times New Roman CE" font is "Times New Roman"
Assert.AreEqual(new[] { "Times New Roman" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// We can save the table for viewing in the form of an XML document
tableSubstitutionRule.Save(ArtifactsDir + "Font.TableSubstitutionRule.Windows.xml");

// Linux has its own substitution table
// If "FreeSerif" is unavailable to substitute for "Times New Roman CE", we then look for "Liberation Serif", and so on
tableSubstitutionRule.LoadLinuxSettings();
Assert.AreEqual(new[] { "FreeSerif", "Liberation Serif", "DejaVu Serif" }, tableSubstitutionRule.GetSubstitutes("Times New Roman CE").ToArray());

// Save the Linux substitution table using a stream
using (FileStream fileStream = new FileStream(ArtifactsDir + "Font.TableSubstitutionRule.Linux.xml", FileMode.Create))
{
    tableSubstitutionRule.Save(fileStream);
}

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace | TableSubstitutionRule.Save Overload List


TableSubstitutionRule.SetSubstitutes Method

Override substitute font names for given original font name.

[Visual Basic]
Public Sub SetSubstitutes( _
ByVal originalFontName As String, _
ParamArray substituteFontNames As String() _
)
[C#]
public void SetSubstitutes(
string originalFontName,
params string[] substituteFontNames
);

Parameters

originalFontName
Original font name.
substituteFontNames
List of alternative font names.

Example

Shows how to define alternative fonts if original does not exist

[C#]

FontSettings fontSettings = new FontSettings();
fontSettings.SubstitutionSettings.TableSubstitution.SetSubstitutes("Times New Roman", new String[] { "Slab", "Arvo" });
Shows how to work with custom font substitution tables.
[C#]

// Create a blank document and a new FontSettings object
Document doc = new Document();
FontSettings fontSettings = new FontSettings();
doc.FontSettings = fontSettings;

// Create a new table substitution rule and load the default Windows font substitution table
TableSubstitutionRule tableSubstitutionRule = fontSettings.SubstitutionSettings.TableSubstitution;

// If we select fonts exclusively from our own folder, we will need a custom substitution table
FolderFontSource folderFontSource = new FolderFontSource(MyDir + @"\MyFonts", false);
fontSettings.SetFontsSources(new FontSourceBase[] { folderFontSource });

// There are two ways of loading a substitution table from a file in the local file system
// 1: Loading from a stream
using (FileStream fileStream = new FileStream(MyDir + "Font.TableSubstitutionRule.Custom.xml", FileMode.Open))
{
    tableSubstitutionRule.Load(fileStream);
}

// 2: Load directly from file
tableSubstitutionRule.Load(MyDir + "Font.TableSubstitutionRule.Custom.xml");

// Since we no longer have access to "Arial", our font table will first try substitute it with "Nonexistent Font", which we don't have,
// and then with "Kreon", found in the "MyFonts" folder
Assert.AreEqual(new[] { "Missing Font", "Kreon" }, tableSubstitutionRule.GetSubstitutes("Arial").ToArray());

// If we find this substitution table lacking, we can also expand it programmatically
// In this case, we add an entry that substitutes "Times New Roman" with "Arvo"
Assert.Null(tableSubstitutionRule.GetSubstitutes("Times New Roman"));
tableSubstitutionRule.AddSubstitutes("Times New Roman", "Arvo");
Assert.AreEqual(new[] { "Arvo" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// We can add a secondary fallback substitute for an existing font entry with AddSubstitutes()
// In case "Arvo" is unavailable, our table will look for "M+ 2m"
tableSubstitutionRule.AddSubstitutes("Times New Roman", "M+ 2m");
Assert.AreEqual(new[] { "Arvo", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// SetSubstitutes() can set a new list of substitute fonts for a font
tableSubstitutionRule.SetSubstitutes("Times New Roman", new[] { "Squarish Sans CT", "M+ 2m" });
Assert.AreEqual(new[] { "Squarish Sans CT", "M+ 2m" }, tableSubstitutionRule.GetSubstitutes("Times New Roman").ToArray());

// TO demonstrate substitution, write text in fonts we have no access to and render the result in a PDF
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Arial";
builder.Writeln("Text written in Arial, to be substituted by Kreon.");

builder.Font.Name = "Times New Roman";
builder.Writeln("Text written in Times New Roman, to be substituted by Squarish Sans CT.");

doc.Save(ArtifactsDir + "Font.TableSubstitutionRule.Custom.pdf");

See Also

TableSubstitutionRule Class | Aspose.Words.Fonts Namespace


Aspose.Words.Layout

Aspose.Words

Aspose.Words.Layout Namespace

The Aspose.Words.Layout namespace provides classes that allow to access information such as on what page and where on a page particular document elements are positioned, when the document is formatted into pages.

Namespace hierarchy

Classes

Class | Description
LayoutCollector | This class allows to compute page numbers of document nodes.
LayoutEnumerator | Enumerates page layout entities of a document. You can use this class to walk over the page layout model. Available properties are type, geometry, text and page index where entity is rendered, as well as overall structure and relationships. Use combination of GetEntity and Current move to the entity which corresponds to a document node.
LayoutOptions | Holds the options that allow controlling the document layout process.
RevisionOptions | Allows to control how document revisions are handled during layout process.

Enumerations

Enumeration | Description
LayoutEntityType | Types of the layout entities.
RevisionColor | Allows to specify color of document revisions.
RevisionTextEffect | Allows to specify decoration effect for revisions of document text.
ShowInBalloons | Specifies which revisions are rendered in balloons.


LayoutCollector Class

This class allows to compute page numbers of document nodes.

For a list of all members of this type, see LayoutCollector Members.

System.Object
Aspose.Words.Layout.LayoutCollector

[Visual Basic]
Public Class LayoutCollector
[C#]
public class LayoutCollector

Remarks

When you create a LayoutCollector and specify a Document document object to attach to, the collector will record mapping of document nodes to layout objects when the document is formatted into pages.

You will be able to find out on which page a particular document node (e.g. run, paragraph or table cell) is located by using the GetStartPageIndex, GetEndPageIndex and GetNumPagesSpanned methods. These methods automatically build page layout model of the document and update fields if required.

When you no longer need to collect layout information, it is best to set the Document property to null to avoid unnecessary collection of more layout mappings.

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

LayoutCollector Members | Aspose.Words.Layout Namespace


LayoutCollector Members

LayoutCollector overview

Public Instance Constructors

LayoutCollector Constructor Initializes an instance of this class.

Public Instance Properties

Document Gets or sets the document this collector instance is attached to.

Public Instance Methods

Clear | Clears all collected layout data. Call this method after document was manually updated, or layout was rebuilt.
GetEndPageIndex | Gets 1-based index of the page where node ends. Returns 0 if node cannot be mapped to a page.
GetEntity | Returns an opaque position of the LayoutEnumerator which corresponds to the specified node. You can use returned value as an argument to Current given the document being enumerated and the document of the node are the same.
GetNumPagesSpanned | Gets number of pages the specified node spans. 0 if node is within a single page. This is the same as GetEndPageIndex - GetStartPageIndex.
GetStartPageIndex | Gets 1-based index of the page where node begins. Returns 0 if node cannot be mapped to a page.

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector Constructor

Initializes an instance of this class.

[Visual Basic]
Public Sub New( _
ByVal doc As Document _
)
[C#]
public LayoutCollector(
Document doc
);

Parameters

doc
The document to which this collector instance will be attached to.

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector Properties

The properties of the LayoutCollector class are listed below. For a complete list of LayoutCollector class members, see the LayoutCollector Members topic.

Public Instance Properties

Document Gets or sets the document this collector instance is attached to.

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


Document Property

Aspose.Words

LayoutCollector.Document Property

Gets or sets the document this collector instance is attached to.

[Visual Basic]
Public Property Document As Document
[C#]
public Document Document {get; set;}

Remarks

If you need to access page indexes of the document nodes you need to set this property to point to a document instance, before page layout of the document is built. It is best to set this property to null afterwards, otherwise the collector continues to accumulate information from subsequent rebuilds of the document's page layout.

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector Methods

The methods of the LayoutCollector class are listed below. For a complete list of LayoutCollector class members, see the LayoutCollector Members topic.

Public Instance Methods

Clear | Clears all collected layout data. Call this method after document was manually updated, or layout was rebuilt.
GetEndPageIndex | Gets 1-based index of the page where node ends. Returns 0 if node cannot be mapped to a page.
GetEntity | Returns an opaque position of the LayoutEnumerator which corresponds to the specified node. You can use returned value as an argument to Current given the document being enumerated and the document of the node are the same.
GetNumPagesSpanned | Gets number of pages the specified node spans. 0 if node is within a single page. This is the same as GetEndPageIndex - GetStartPageIndex.
GetStartPageIndex | Gets 1-based index of the page where node begins. Returns 0 if node cannot be mapped to a page.

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector.Clear Method

Clears all collected layout data. Call this method after document was manually updated, or layout was rebuilt.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector.GetEndPageIndex Method

Gets 1-based index of the page where node ends. Returns 0 if node cannot be mapped to a page.

[Visual Basic]
Public Function GetEndPageIndex( _
ByVal node As Node _
) As Integer
[C#]
public int GetEndPageIndex(
Node node
);

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector.GetEntity Method

Returns an opaque position of the LayoutEnumerator which corresponds to the specified node. You can use returned value as an argument to Current given the document being enumerated and the document of the node are the same.

[Visual Basic]
Public Function GetEntity( _
ByVal node As Node _
) As Object
[C#]
public object GetEntity(
Node node
);

Remarks

This method works for only Paragraph nodes, as well as indivisible inline nodes, e.g. BookmarkStart or Shape. It doesn't work for Run, Cell Row or Table nodes, and nodes within header/footer.

Note that the entity returned for a Paragraph node is a paragraph break span. Use the appropriate method to ascend to the parent line

If you need to navigate to a Run of text then you can insert bookmark right before it and then navigate to the bookmark instead.

If you need to navigate to a Cell node then you can move to a Paragraph node in this cell and then ascend to a parent entity. The same approach can be used for Row and Table nodes.

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector.GetNumPagesSpanned Method

Gets number of pages the specified node spans. 0 if node is within a single page. This is the same as GetEndPageIndex - GetStartPageIndex.

[Visual Basic]
Public Function GetNumPagesSpanned( _
ByVal node As Node _
) As Integer
[C#]
public int GetNumPagesSpanned(
Node node
);

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutCollector.GetStartPageIndex Method

Gets 1-based index of the page where node begins. Returns 0 if node cannot be mapped to a page.

[Visual Basic]
Public Function GetStartPageIndex( _
ByVal node As Node _
) As Integer
[C#]
public int GetStartPageIndex(
Node node
);

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutEntityType Enumeration

Types of the layout entities.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum LayoutEntityType
[C#]
public enum LayoutEntityType

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

Members

Member Name | Description | Value
None | Default value. | 0
Page | Represents page of a document. Page may have Column, HeaderFooter and Comment child entities. | 1
Column | Represents a column of text on a page. Column may have the same child entities as Cell, plus Footnote, Endnote and NoteSeparator entities. | 2
Row | Represents a table row. Row may have Cell as child entities. | 8
Cell | Represents a table cell. Cell may have Line and Row child entities. | 16
Line | Represents line of characters of text and inline objects. Line may have Span child entities. | 32
Span | Represents one or more characters in a line. This include special characters like field start/end markers, bookmarks and comments. Span may not have child entities. | 64
Footnote | Represents placeholder for footnote content. Footnote may have Line and Row child entities. | 256
Endnote | Represents placeholder for endnote content. Endnote may have Line and Row child entities. | 512
HeaderFooter | Represents placeholder for header/footer content on a page. HeaderFooter may have Line and Row child entities. | 1024
TextBox | Represents text area inside of a shape. Textbox may have Line and Row child entities. | 2048
Comment | Represents placeholder for comment content. Comment may have Line and Row child entities. | 4096
NoteSeparator | Represents footnote/endnote separator. NoteSeparator may have Line and Row child entities. | 8192

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Layout Namespace


LayoutEnumerator Class

Enumerates page layout entities of a document. You can use this class to walk over the page layout model. Available properties are type, geometry, text and page index where entity is rendered, as well as overall structure and relationships. Use combination of GetEntity and Current move to the entity which corresponds to a document node.

For a list of all members of this type, see LayoutEnumerator Members.

System.Object
Aspose.Words.Layout.LayoutEnumerator

[Visual Basic]
Public Class LayoutEnumerator
[C#]
public class LayoutEnumerator

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

LayoutEnumerator Members | Aspose.Words.Layout Namespace


LayoutEnumerator Members

LayoutEnumerator overview

Public Instance Constructors

LayoutEnumerator Constructor Initializes new instance of this class.

Public Instance Properties

Current | Gets or sets current position in the page layout model. This property returns an opaque object which corresponds to the current layout entity.
Document | Gets document this instance enumerates.
Kind | Gets the kind of the current entity. This can be an empty string but never null.
PageIndex | Gets the 1-based index of a page which contains the current entity.
Rectangle | Returns the bounding rectangle of the current entity relative to the page top left corner (in points).
Text | Gets text of the current span entity. Throws for other entity types.
Type | Gets the type of the current entity.

Public Instance Methods

MoveFirstChild | Moves to the first child entity.
MoveLastChild | Moves to the last child entity.
MoveNext | Moves to the next sibling entity in visual order. When iterating lines of a paragraph broken across pages this method will not move to the next page but rather move to the next entity on the same page.
MoveNextLogical | Moves to the next sibling entity in a logical order. When iterating lines of a paragraph broken across pages this method will move to the next line even if it resides on another page.
MoveParent | Overloaded. Moves to the parent entity.
MovePrevious | Moves to the previous sibling entity.
MovePreviousLogical | Moves to the previous sibling entity in a logical order. When iterating lines of a paragraph broken across pages this method will move to the previous line even if it resides on another page.
Reset | Moves the enumerator to the first page of the document.

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator Constructor

Initializes new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal document As Document _
)
[C#]
public LayoutEnumerator(
Document document
);

Parameters

document
A document whose page layout model to enumerate.

Remarks

If page layout model of the document hasn't been built the enumerator calls UpdatePageLayout to build it.

Whenever document is updated and new page layout model is created, a new enumerator must be used to access it.

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator Properties

The properties of the LayoutEnumerator class are listed below. For a complete list of LayoutEnumerator class members, see the LayoutEnumerator Members topic.

Public Instance Properties

Current | Gets or sets current position in the page layout model. This property returns an opaque object which corresponds to the current layout entity.
Document | Gets document this instance enumerates.
Kind | Gets the kind of the current entity. This can be an empty string but never null.
PageIndex | Gets the 1-based index of a page which contains the current entity.
Rectangle | Returns the bounding rectangle of the current entity relative to the page top left corner (in points).
Text | Gets text of the current span entity. Throws for other entity types.
Type | Gets the type of the current entity.

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


Current Property

Aspose.Words

LayoutEnumerator.Current Property

Gets or sets current position in the page layout model. This property returns an opaque object which corresponds to the current layout entity.

[Visual Basic]
Public Property Current As Object
[C#]
public object Current {get; set;}

Example

Shows how to see the page spans of nodes.

[C#]

// Open a blank document and create a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a LayoutCollector object for our document that will have information about the nodes we placed
LayoutCollector layoutCollector = new LayoutCollector(doc);

// The document itself is a node that contains everything, which currently spans 0 pages
Assert.AreEqual(doc, layoutCollector.Document);
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// Populate the document with sections and page breaks
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
doc.AppendChild(new Section(doc));
doc.LastSection.AppendChild(new Body(doc));
builder.MoveToDocumentEnd();
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);

// The collected layout data won't automatically keep up with the real document contents
Assert.AreEqual(0, layoutCollector.GetNumPagesSpanned(doc));

// After we clear the layout collection and update it, the layout entity collection will be populated with up-to-date information about our nodes
// The page span for the document now shows 5, which is what we would expect after placing 4 page breaks
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.AreEqual(5, layoutCollector.GetNumPagesSpanned(doc));

// We can also see the start/end pages of any other 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.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

// The LayoutEnumerator can traverse the collection of layout entities like a tree
// We can also point it to any node's corresponding layout entity like this
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
Assert.AreEqual("¶", layoutEnumerator.Text);

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


Document Property

Aspose.Words

LayoutEnumerator.Document Property

Gets document this instance enumerates.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


Kind Property

Aspose.Words

LayoutEnumerator.Kind Property

Gets the kind of the current entity. This can be an empty string but never null.

[Visual Basic]
Public ReadOnly Property Kind As String
[C#]
public string Kind {get;}

Remarks

This is a more specific type of the current entity, e.g. bookmark span has Span type and may have either a BOOKMARKSTART or BOOKMARKEND kind.

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


PageIndex Property

Aspose.Words

LayoutEnumerator.PageIndex Property

Gets the 1-based index of a page which contains the current entity.

[Visual Basic]
Public ReadOnly Property PageIndex As Integer
[C#]
public int PageIndex {get;}

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


Rectangle Property

Aspose.Words

LayoutEnumerator.Rectangle Property

Returns the bounding rectangle of the current entity relative to the page top left corner (in points).

[Visual Basic]
Public ReadOnly Property Rectangle As RectangleF
[C#]
public RectangleF Rectangle {get;}

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


Text Property

Aspose.Words

LayoutEnumerator.Text Property

Gets text of the current span entity. Throws for other entity types.

[Visual Basic]
Public ReadOnly Property Text As String
[C#]
public string Text {get;}

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


Type Property

Aspose.Words

LayoutEnumerator.Type Property

Gets the type of the current entity.

[Visual Basic]
Public ReadOnly Property Type As LayoutEntityType
[C#]
public LayoutEntityType Type {get;}

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator Methods

The methods of the LayoutEnumerator class are listed below. For a complete list of LayoutEnumerator class members, see the LayoutEnumerator Members topic.

Public Instance Methods

MoveFirstChild | Moves to the first child entity.
MoveLastChild | Moves to the last child entity.
MoveNext | Moves to the next sibling entity in visual order. When iterating lines of a paragraph broken across pages this method will not move to the next page but rather move to the next entity on the same page.
MoveNextLogical | Moves to the next sibling entity in a logical order. When iterating lines of a paragraph broken across pages this method will move to the next line even if it resides on another page.
MoveParent | Overloaded. Moves to the parent entity.
MovePrevious | Moves to the previous sibling entity.
MovePreviousLogical | Moves to the previous sibling entity in a logical order. When iterating lines of a paragraph broken across pages this method will move to the previous line even if it resides on another page.
Reset | Moves the enumerator to the first page of the document.

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveFirstChild Method

Moves to the first child entity.

[Visual Basic]
Public Function MoveFirstChild() As Boolean
[C#]
public bool MoveFirstChild();

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveLastChild Method

Moves to the last child entity.

[Visual Basic]
Public Function MoveLastChild() As Boolean
[C#]
public bool MoveLastChild();

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveNext Method

Moves to the next sibling entity in visual order. When iterating lines of a paragraph broken across pages this method will not move to the next page but rather move to the next entity on the same page.

[Visual Basic]
Public Function MoveNext() As Boolean
[C#]
public bool MoveNext();

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveNextLogical Method

Moves to the next sibling entity in a logical order. When iterating lines of a paragraph broken across pages this method will move to the next line even if it resides on another page.

[Visual Basic]
Public Function MoveNextLogical() As Boolean
[C#]
public bool MoveNextLogical();

Remarks

Note that all Span entities are linked together thus if Current entity is span repeated calling of this method will iterates complete story of the document.

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


MoveParent Method

Aspose.Words

LayoutEnumerator.MoveParent Method

Moves to the parent entity.

Overload List

Moves to the parent entity.

public bool MoveParent();

Moves to the parent entity of the specified type.

public bool MoveParent(LayoutEntityType);

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveParent Method ()

Moves to the parent entity.

[Visual Basic]
Overloads Public Function MoveParent() As Boolean
[C#]
public bool MoveParent();

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace | LayoutEnumerator.MoveParent Overload List


LayoutEnumerator.MoveParent Method (LayoutEntityType)

Moves to the parent entity of the specified type.

[Visual Basic]
Overloads Public Function MoveParent( _
ByVal types As LayoutEntityType _
) As Boolean
[C#]
public bool MoveParent(
LayoutEntityType types
);

Parameters

types
The parent entity type to move to. Use bitwise-OR to specify multiple parent types.

Remarks

This method is useful if you need to find the cell, column or header/footer parent of the entity.

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace | LayoutEnumerator.MoveParent Overload List


LayoutEnumerator.MovePrevious Method

Moves to the previous sibling entity.

[Visual Basic]
Public Function MovePrevious() As Boolean
[C#]
public bool MovePrevious();

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MovePreviousLogical Method

Moves to the previous sibling entity in a logical order. When iterating lines of a paragraph broken across pages this method will move to the previous line even if it resides on another page.

[Visual Basic]
Public Function MovePreviousLogical() As Boolean
[C#]
public bool MovePreviousLogical();

Remarks

Note that all Span entities are linked together thus if Current entity is span repeated calling of this method will iterates complete story of the document.

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.Reset Method

Moves the enumerator to the first page of the document.

[Visual Basic]
Public Sub Reset()
[C#]
public void Reset();

Example

Demonstrates ways of traversing a document's layout entities.

[C#]

public void LayoutEnumerator()
{
    // Open a document that contains a variety of layout entities
    // Layout entities are pages, cells, rows, lines and other objects included in the LayoutEntityType enum
    // They are defined visually by the rectangular space that they occupy in the document
    Document doc = new Document(MyDir + "Document.LayoutEntities.docx");

    // Create an enumerator that can traverse these entities
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
    Assert.AreEqual(doc, layoutEnumerator.Document);

    // The enumerator points to the first element on the first page and can be traversed like a tree
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveFirstChild();
    layoutEnumerator.MoveLastChild();
    layoutEnumerator.MovePrevious();
    Assert.AreEqual(LayoutEntityType.Span, layoutEnumerator.Type);
    Assert.AreEqual("TTT", layoutEnumerator.Text);

    // Only spans can contain text
    layoutEnumerator.MoveParent(LayoutEntityType.Page);
    Assert.AreEqual(LayoutEntityType.Page, layoutEnumerator.Type);

    // We can call this method to make sure that the enumerator points to the very first entity before we go through it forwards
    layoutEnumerator.Reset();

    // "Visual order" means when moving through an entity's children that are broken across pages,
    // page layout takes precedence and we avoid elements in other pages and move to others on the same page
    Console.WriteLine("Traversing from first to last, elements between pages separated:");
    TraverseLayoutForward(layoutEnumerator, 1);

    // Our enumerator is conveniently at the end of the collection for us to go through the collection backwards
    Console.WriteLine("Traversing from last to first, elements between pages separated:");
    TraverseLayoutBackward(layoutEnumerator, 1);

    // "Logical order" means when moving through an entity's children that are broken across pages,
    // node relationships take precedence
    Console.WriteLine("Traversing from first to last, elements between pages mixed:");
    TraverseLayoutForwardLogical(layoutEnumerator, 1);

    Console.WriteLine("Traversing from last to first, elements between pages mixed:");
    TraverseLayoutBackwardLogical(layoutEnumerator, 1);
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutForward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNext());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Visual" order
/// </summary>
private void TraverseLayoutBackward(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackward(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePrevious());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection front-to-back, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutForwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveFirstChild())
        {
            TraverseLayoutForwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MoveNextLogical());
}

/// <summary>
/// Enumerate through layoutEnumerator's layout entity collection back-to-front, in a DFS manner, and in a "Logical" order
/// </summary>
private void TraverseLayoutBackwardLogical(LayoutEnumerator layoutEnumerator, int depth)
{
    do
    {
        PrintCurrentEntity(layoutEnumerator, depth);

        if (layoutEnumerator.MoveLastChild())
        {
            TraverseLayoutBackwardLogical(layoutEnumerator, depth + 1);
            layoutEnumerator.MoveParent();
        }
    } while (layoutEnumerator.MovePreviousLogical());
}

/// <summary>
/// Print information about layoutEnumerator's current entity to the console, indented by a number of tab characters specified by indent
/// The rectangle that we process at the end represents the area and location thereof that the element takes up in the document
/// </summary>
private void PrintCurrentEntity(LayoutEnumerator layoutEnumerator, int indent)
{
    string tabs = new String('\t', indent);

    if (layoutEnumerator.Kind == String.Empty)
    {
        Console.WriteLine($"{tabs}-> Entity type: {layoutEnumerator.Type}");
    }
    else
    {
        Console.WriteLine($"{tabs}-> Entity type & kind: {layoutEnumerator.Type}, {layoutEnumerator.Kind}");
    }

    if (layoutEnumerator.Type == LayoutEntityType.Span)
    {
        Console.WriteLine($"{tabs}   Span contents: \"{layoutEnumerator.Text}\"");
    }

    RectangleF leRect = layoutEnumerator.Rectangle;
    Console.WriteLine($"{tabs}   Rectangle dimensions {leRect.Width}x{leRect.Height}, X={leRect.X} Y={leRect.Y}");
    Console.WriteLine($"{tabs}   Page {layoutEnumerator.PageIndex}");
}

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutOptions Class

Holds the options that allow controlling the document layout process.

For a list of all members of this type, see LayoutOptions Members.

System.Object
Aspose.Words.Layout.LayoutOptions

[Visual Basic]
Public Class LayoutOptions
[C#]
public class LayoutOptions

Remarks

You do not create instances of this class directly. Use the LayoutOptions property to access layout options for this document.

Note that after changing any of the options present in this class, UpdatePageLayout method should be called in order for the changed options to be applied to the layout.

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

LayoutOptions Members | Aspose.Words.Layout Namespace


LayoutOptions Members

LayoutOptions overview

Public Instance Properties

RevisionOptions | Gets revision options.
ShowComments | Gets or sets indication of whether comments are rendered. Default is True.
ShowHiddenText | Gets or sets indication of whether hidden text in the document is rendered. Default is False.
ShowParagraphMarks | Gets or sets indication of whether paragraph marks are rendered. Default is False.
TextShaperFactory | Gets or sets ITextShaperFactory implementation used for Advanced Typography rendering features.

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


LayoutOptions Properties

The properties of the LayoutOptions class are listed below. For a complete list of LayoutOptions class members, see the LayoutOptions Members topic.

Public Instance Properties

RevisionOptions | Gets revision options.
ShowComments | Gets or sets indication of whether comments are rendered. Default is True.
ShowHiddenText | Gets or sets indication of whether hidden text in the document is rendered. Default is False.
ShowParagraphMarks | Gets or sets indication of whether paragraph marks are rendered. Default is False.
TextShaperFactory | Gets or sets ITextShaperFactory implementation used for Advanced Typography rendering features.

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


RevisionOptions Property

Aspose.Words

LayoutOptions.RevisionOptions Property

Gets revision options.

[Visual Basic]
Public ReadOnly Property RevisionOptions As RevisionOptions
[C#]
public RevisionOptions RevisionOptions {get;}

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


ShowComments Property

Aspose.Words

LayoutOptions.ShowComments Property

Gets or sets indication of whether comments are rendered. Default is True.

[Visual Basic]
Public Property ShowComments As Boolean
[C#]
public bool ShowComments {get; set;}

Example

Shows how to show or hide comments in PDF document.

[C#]

Document doc = new Document(MyDir + "Comment.Document.docx");

doc.LayoutOptions.ShowComments = false;

doc.Save(ArtifactsDir + "Document.DoNotShowComments.pdf");

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


ShowHiddenText Property

Aspose.Words

LayoutOptions.ShowHiddenText Property

Gets or sets indication of whether hidden text in the document is rendered. Default is False.

[Visual Basic]
Public Property ShowHiddenText As Boolean
[C#]
public bool ShowHiddenText {get; set;}

Remarks

This property affects all hidden content, not just text.

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


ShowParagraphMarks Property

Aspose.Words

LayoutOptions.ShowParagraphMarks Property

Gets or sets indication of whether paragraph marks are rendered. Default is False.

[Visual Basic]
Public Property ShowParagraphMarks As Boolean
[C#]
public bool ShowParagraphMarks {get; set;}

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


TextShaperFactory Property

Aspose.Words

LayoutOptions.TextShaperFactory Property

Gets or sets ITextShaperFactory implementation used for Advanced Typography rendering features.

[Visual Basic]
Public Property TextShaperFactory As ITextShaperFactory
[C#]
public ITextShaperFactory TextShaperFactory {get; set;}

Example

Shows how to support OpenType features using HarfBuzz text shaping engine.

[C#]

// Open a document
Document doc = new Document(MyDir + "OpenType.Document.docx");

// Please note that text shaping is only performed when exporting to PDF or XPS formats now

// Aspose.Words is capable of using text shaper objects provided externally.
// A text shaper represents a font and computes shaping information for a text.
// A document typically refers to multiple fonts thus a text shaper factory is necessary.
// When text shaper factory is set, layout starts to use OpenType features.
// An Instance property returns static BasicTextShaperCache object wrapping HarfBuzzTextShaperFactory
doc.LayoutOptions.TextShaperFactory = HarfBuzzTextShaperFactory.Instance;

// Render the document to PDF format
doc.Save(ArtifactsDir + "OpenType.Document.pdf");

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


RevisionColor Enumeration

Allows to specify color of document revisions.

[Visual Basic]
Public Enum RevisionColor
[C#]
public enum RevisionColor

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

Members

Member Name | Description | Value
Auto | Default. | 0
Black | Represents 000000 color. | 1
Blue | Represents 2e97d3 color. | 2
BrightGreen | Represents 84a35b color. | 3
DarkBlue | Represents 376e96 color. | 4
DarkRed | Represents 881824 color. | 5
DarkYellow | Represents e09a2b color. | 6
Gray25 | Represents a0a3a9 color. | 7
Gray50 | Represents 50565e color. | 8
Green | Represents 2c6234 color. | 9
Pink | Represents ce338f color. | 10
Red | Represents b5082e color. | 11
Teal | Represents 1b9cab color. | 12
Turquoise | Represents 3eafc2 color. | 13
Violet | Represents 633277 color. | 14
White | Represents ffffff color. | 15
Yellow | Represents fad272 color. | 16
NoHighlight | No color is used to highlight revision changes. | 17
ByAuthor | Revisions of each author receive their own color for highlighting from a predfined set of hi-contrast colors. | 18

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Layout Namespace


RevisionOptions Class

Allows to control how document revisions are handled during layout process.

For a list of all members of this type, see RevisionOptions Members.

System.Object
Aspose.Words.Layout.RevisionOptions

[Visual Basic]
Public Class RevisionOptions
[C#]
public class RevisionOptions

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RevisionOptions Members | Aspose.Words.Layout Namespace


RevisionOptions Members

RevisionOptions overview

Public Instance Properties

CommentColor | Allows to specify the color to be used for comments. Default value for this property is Red. If set this property to ByAuthor or NoHighlight values, as the result this property will be set to default color.
DeletedTextColor | Allows to specify the color to be used for deleted content Deletion. Default value for this property is ByAuthor.
DeletedTextEffect | Allows to specify the effect to be applied to the deleted content Deletion. Default value is StrikeThrough
InsertedTextColor | Allows to specify the color to be used for inserted content Insertion. Default value for this property is ByAuthor.
InsertedTextEffect | Allows to specify the effect to be applied to the inserted content Insertion. Default value is Underline.
MovedFromTextColor | Allows to specify the color to be used for areas where content was moved from Moving. Default value for this property is ByAuthor.
MovedFromTextEffect | Allows to specify the effect to be applied to the areas where content was moved from Moving. Default value is DoubleStrikeThrough
MovedToTextColor | Allows to specify the color to be used for areas where content was moved to Moving. Default value for this property is ByAuthor.
MovedToTextEffect | Allows to specify the effect to be applied to the areas where content was moved to Moving. Default value is DoubleUnderline
RevisedPropertiesColor | Allows to specify the color to be used for content with changes of formatting properties FormatChange Default value for this property is NoHighlight.
RevisedPropertiesEffect | Allows to specify the effect for content areas with changes of formatting properties FormatChange Default value is None
RevisionBarsColor | Allows to specify the color to be used for side bars that identify document lines containing revised information. Default value for this property is Red.
RevisionBarsWidth | Gets or sets width of revision bars, points.
ShowInBalloons | Allows to specify whether the revisions are rendered in the balloons. Default value for this property is None
ShowOriginalRevision | Allows to specify whether the original text should be shown instead of revised one. Default value for this property is false.
ShowRevisionBars | Allows to specify whether revision bars should be rendered near lines containing revised content. Default value for this property is true.
ShowRevisionMarks | Allow to specify whether revision text should be marked with special formatting markup. Default value for this property is true.

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


RevisionOptions Properties

The properties of the RevisionOptions class are listed below. For a complete list of RevisionOptions class members, see the RevisionOptions Members topic.

Public Instance Properties

CommentColor | Allows to specify the color to be used for comments. Default value for this property is Red. If set this property to ByAuthor or NoHighlight values, as the result this property will be set to default color.
DeletedTextColor | Allows to specify the color to be used for deleted content Deletion. Default value for this property is ByAuthor.
DeletedTextEffect | Allows to specify the effect to be applied to the deleted content Deletion. Default value is StrikeThrough
InsertedTextColor | Allows to specify the color to be used for inserted content Insertion. Default value for this property is ByAuthor.
InsertedTextEffect | Allows to specify the effect to be applied to the inserted content Insertion. Default value is Underline.
MovedFromTextColor | Allows to specify the color to be used for areas where content was moved from Moving. Default value for this property is ByAuthor.
MovedFromTextEffect | Allows to specify the effect to be applied to the areas where content was moved from Moving. Default value is DoubleStrikeThrough
MovedToTextColor | Allows to specify the color to be used for areas where content was moved to Moving. Default value for this property is ByAuthor.
MovedToTextEffect | Allows to specify the effect to be applied to the areas where content was moved to Moving. Default value is DoubleUnderline
RevisedPropertiesColor | Allows to specify the color to be used for content with changes of formatting properties FormatChange Default value for this property is NoHighlight.
RevisedPropertiesEffect | Allows to specify the effect for content areas with changes of formatting properties FormatChange Default value is None
RevisionBarsColor | Allows to specify the color to be used for side bars that identify document lines containing revised information. Default value for this property is Red.
RevisionBarsWidth | Gets or sets width of revision bars, points.
ShowInBalloons | Allows to specify whether the revisions are rendered in the balloons. Default value for this property is None
ShowOriginalRevision | Allows to specify whether the original text should be shown instead of revised one. Default value for this property is false.
ShowRevisionBars | Allows to specify whether revision bars should be rendered near lines containing revised content. Default value for this property is true.
ShowRevisionMarks | Allow to specify whether revision text should be marked with special formatting markup. Default value for this property is true.

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


CommentColor Property

Aspose.Words

RevisionOptions.CommentColor Property

Allows to specify the color to be used for comments. Default value for this property is Red. If set this property to ByAuthor or NoHighlight values, as the result this property will be set to default color.

[Visual Basic]
Public Property CommentColor As RevisionColor
[C#]
public RevisionColor CommentColor {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


DeletedTextColor Property

Aspose.Words

RevisionOptions.DeletedTextColor Property

Allows to specify the color to be used for deleted content Deletion. Default value for this property is ByAuthor.

[Visual Basic]
Public Property DeletedTextColor As RevisionColor
[C#]
public RevisionColor DeletedTextColor {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


DeletedTextEffect Property

Aspose.Words

RevisionOptions.DeletedTextEffect Property

Allows to specify the effect to be applied to the deleted content Deletion. Default value is StrikeThrough

[Visual Basic]
Public Property DeletedTextEffect As RevisionTextEffect
[C#]
public RevisionTextEffect DeletedTextEffect {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


InsertedTextColor Property

Aspose.Words

RevisionOptions.InsertedTextColor Property

Allows to specify the color to be used for inserted content Insertion. Default value for this property is ByAuthor.

[Visual Basic]
Public Property InsertedTextColor As RevisionColor
[C#]
public RevisionColor InsertedTextColor {get; set;}

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


InsertedTextEffect Property

Aspose.Words

RevisionOptions.InsertedTextEffect Property

Allows to specify the effect to be applied to the inserted content Insertion. Default value is Underline.

[Visual Basic]
Public Property InsertedTextEffect As RevisionTextEffect
[C#]
public RevisionTextEffect InsertedTextEffect {get; set;}

Remarks

Values of Hidden and DoubleStrikeThrough are not allowed and will cause ArgumentOutOfRangeException.

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


MovedFromTextColor Property

Aspose.Words

RevisionOptions.MovedFromTextColor Property

Allows to specify the color to be used for areas where content was moved from Moving. Default value for this property is ByAuthor.

[Visual Basic]
Public Property MovedFromTextColor As RevisionColor
[C#]
public RevisionColor MovedFromTextColor {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


MovedFromTextEffect Property

Aspose.Words

RevisionOptions.MovedFromTextEffect Property

Allows to specify the effect to be applied to the areas where content was moved from Moving. Default value is DoubleStrikeThrough

[Visual Basic]
Public Property MovedFromTextEffect As RevisionTextEffect
[C#]
public RevisionTextEffect MovedFromTextEffect {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


MovedToTextColor Property

Aspose.Words

RevisionOptions.MovedToTextColor Property

Allows to specify the color to be used for areas where content was moved to Moving. Default value for this property is ByAuthor.

[Visual Basic]
Public Property MovedToTextColor As RevisionColor
[C#]
public RevisionColor MovedToTextColor {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


MovedToTextEffect Property

Aspose.Words

RevisionOptions.MovedToTextEffect Property

Allows to specify the effect to be applied to the areas where content was moved to Moving. Default value is DoubleUnderline

[Visual Basic]
Public Property MovedToTextEffect As RevisionTextEffect
[C#]
public RevisionTextEffect MovedToTextEffect {get; set;}

Remarks

Values of Hidden and DoubleStrikeThrough are not allowed and will cause ArgumentOutOfRangeException.

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


RevisedPropertiesColor Property

Aspose.Words

RevisionOptions.RevisedPropertiesColor Property

Allows to specify the color to be used for content with changes of formatting properties FormatChange Default value for this property is NoHighlight.

[Visual Basic]
Public Property RevisedPropertiesColor As RevisionColor
[C#]
public RevisionColor RevisedPropertiesColor {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


RevisedPropertiesEffect Property

Aspose.Words

RevisionOptions.RevisedPropertiesEffect Property

Allows to specify the effect for content areas with changes of formatting properties FormatChange Default value is None

[Visual Basic]
Public Property RevisedPropertiesEffect As RevisionTextEffect
[C#]
public RevisionTextEffect RevisedPropertiesEffect {get; set;}

Remarks

Hidden is not allowed and will cause ArgumentOutOfRangeException.

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


RevisionBarsColor Property

Aspose.Words

RevisionOptions.RevisionBarsColor Property

Allows to specify the color to be used for side bars that identify document lines containing revised information. Default value for this property is Red.

[Visual Basic]
Public Property RevisionBarsColor As RevisionColor
[C#]
public RevisionColor RevisionBarsColor {get; set;}

Remarks

Setting this property to ByAuthor or NoHighlight values will result in hiding revision bars from the layout.

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


RevisionBarsWidth Property

Aspose.Words

RevisionOptions.RevisionBarsWidth Property

Gets or sets width of revision bars, points.

[Visual Basic]
Public Property RevisionBarsWidth As Single
[C#]
public float RevisionBarsWidth {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


ShowInBalloons Property

Aspose.Words

RevisionOptions.ShowInBalloons Property

Allows to specify whether the revisions are rendered in the balloons. Default value for this property is None

[Visual Basic]
Public Property ShowInBalloons As ShowInBalloons
[C#]
public ShowInBalloons ShowInBalloons {get; set;}

Example

Shows how render tracking changes in balloons

[C#]

Document doc = new Document(MyDir + "ShowRevisionBalloons.docx");

//Set option true, if you need render tracking changes in balloons in pdf document
doc.LayoutOptions.RevisionOptions.ShowInBalloons = ShowInBalloons.Format;

//Check that revisions are in balloons
doc.Save(ArtifactsDir + "ShowRevisionBalloons.pdf");
Show how to render revisions in the balloons and edit their appearance.
[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


ShowOriginalRevision Property

Aspose.Words

RevisionOptions.ShowOriginalRevision Property

Allows to specify whether the original text should be shown instead of revised one. Default value for this property is false.

[Visual Basic]
Public Property ShowOriginalRevision As Boolean
[C#]
public bool ShowOriginalRevision {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


ShowRevisionBars Property

Aspose.Words

RevisionOptions.ShowRevisionBars Property

Allows to specify whether revision bars should be rendered near lines containing revised content. Default value for this property is true.

[Visual Basic]
Public Property ShowRevisionBars As Boolean
[C#]
public bool ShowRevisionBars {get; set;}

Example

Shows how to set a document's layout options.

[C#]

Document doc = new Document();

Assert.IsFalse(doc.LayoutOptions.ShowHiddenText);
Assert.IsFalse(doc.LayoutOptions.ShowParagraphMarks);

// The appearance of revisions can be controlled from the layout options property
doc.StartTrackRevisions("John Doe", DateTime.Now);
doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln(
    "This is a revision. Normally the text is red with a bar to the left, but we made some changes to the revision options.");

doc.StopTrackRevisions();

// Layout options can be used to show hidden text too
builder.Writeln("This text is not hidden.");
builder.Font.Hidden = true;
builder.Writeln(
    "This text is hidden. It will only show up in the output if we allow it to via doc.LayoutOptions.");

doc.LayoutOptions.ShowHiddenText = true;

doc.Save(ArtifactsDir + "Document.LayoutOptions.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


ShowRevisionMarks Property

Aspose.Words

RevisionOptions.ShowRevisionMarks Property

Allow to specify whether revision text should be marked with special formatting markup. Default value for this property is true.

[Visual Basic]
Public Property ShowRevisionMarks As Boolean
[C#]
public bool ShowRevisionMarks {get; set;}

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

See Also

RevisionOptions Class | Aspose.Words.Layout Namespace


RevisionTextEffect Enumeration

Allows to specify decoration effect for revisions of document text.

[Visual Basic]
Public Enum RevisionTextEffect
[C#]
public enum RevisionTextEffect

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

Members

Member Name | Description | Value
None | Revised content has no special effects applied. This corresponds to NoHighlight. | 0
Color | Revised content is highlighted with color only. | 1
Bold | Revised content is made bold and colored. | 2
Italic | Revised content is made italic and colored. | 3
Underline | Revised content is underlined and colored. | 4
DoubleUnderline | Revised content is double underlined and colored. | 5
StrikeThrough | Revised content is stroked through and colored. | 6
DoubleStrikeThrough | Revised content is double stroked through and colored. | 7
Hidden | Revised content is hidden. | 8

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Layout Namespace


ShowInBalloons Enumeration

Specifies which revisions are rendered in balloons.

[Visual Basic]
Public Enum ShowInBalloons
[C#]
public enum ShowInBalloons

Remarks

Note that these values do not affect rendering of comments, which are controlled by ShowComments.

Example

Show how to render revisions in the balloons and edit their appearance.

[C#]

Document doc = new Document(MyDir + "Document.Revisions.docx");

// Get the RevisionOptions object that controls the appearance of revisions
RevisionOptions revisionOptions = doc.LayoutOptions.RevisionOptions;

// Get movement, deletion, formatting revisions and comments to show up in green balloons on the right side of the page
revisionOptions.ShowInBalloons = ShowInBalloons.Format;
revisionOptions.CommentColor = RevisionColor.BrightGreen;

// Render text inserted while revisions were being tracked in italic green
revisionOptions.InsertedTextColor = RevisionColor.Green;
revisionOptions.InsertedTextEffect = RevisionTextEffect.Italic;

// Render text deleted while revisions were being tracked in bold red
revisionOptions.DeletedTextColor = RevisionColor.Red;
revisionOptions.DeletedTextEffect = RevisionTextEffect.Bold;

// In a movement revision, the same text will appear twice: once at the departure point and once at the arrival destination
// Render the text at the moved-from revision yellow with double strike through and double underlined blue at the moved-to revision
revisionOptions.MovedFromTextColor = RevisionColor.Yellow;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleStrikeThrough;
revisionOptions.MovedToTextColor = RevisionColor.Blue;
revisionOptions.MovedFromTextEffect = RevisionTextEffect.DoubleUnderline;

// Render text which had its format changed while revisions were being tracked in bold dark red
revisionOptions.RevisedPropertiesColor = RevisionColor.DarkRed;
revisionOptions.RevisedPropertiesEffect = RevisionTextEffect.Bold;

// Place a thick dark blue bar on the left side of the page next to lines affected by revisions
revisionOptions.RevisionBarsColor = RevisionColor.DarkBlue;
revisionOptions.RevisionBarsWidth = 15.0f;

// Show revision marks and original text
revisionOptions.ShowOriginalRevision = true;
revisionOptions.ShowRevisionMarks = true;

doc.Save(ArtifactsDir + "Document.ShowRevisionsInBalloons.pdf");

Members

Member Name | Description | Value
None | Renders insert, delete and format revisions inline. | 0
Format | Renders insert and delete revisions inline, format revisions in balloons. | 1
FormatAndDelete | Renders insert revisions inline, delete and format revisions in balloons. | 2

Requirements

Namespace: Aspose.Words.Layout

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Layout Namespace


Aspose.Words.Lists

Aspose.Words

Aspose.Words.Lists Namespace

The Aspose.Words.Lists namespace contains classes for working with bulleted and numbered lists defined in a document.

Namespace hierarchy

Classes

Class | Description
List | Represents formatting of a list.
ListCollection | Stores and manages formatting of bulleted and numbered lists used in a document.
ListLabel | Defines properties specific to a list label.
ListLevel | Defines formatting for a list level.
ListLevelCollection | A collection of list formatting for each level in a list.

Enumerations

Enumeration | Description
ListLevelAlignment | Specifies alignment for the list number or bullet.
ListTemplate | Specifies one of the predefined list formats available in Microsoft Word.
ListTrailingCharacter | Specifies the character that separates the list label from the text of the paragraph.


List Class

Represents formatting of a list.

For a list of all members of this type, see List Members.

System.Object
Aspose.Words.Lists.List

[Visual Basic]
Public Class List
Implements IComparable
[C#]
public class List : IComparable

Remarks

A list in a Microsoft Word document is a set of list formatting properties. Each list can have up to 9 levels and formatting properties, such as number style, start value, indent, tab position etc are defined separately for each level.

A List object always belongs to the ListCollection collection.

To create a new list, use the Add methods of the ListCollection collection.

To modify formatting of a list, use ListLevel objects found in the ListLevels collection.

To apply or remove list formatting from a paragraph, use ListFormat.

Example

Shows how to specify list level number when building a list using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");
Shows how to restart numbering in a list by copying a list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");
Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.
[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

List Members | Aspose.Words.Lists Namespace | ListCollection | ListLevel | ListFormat


List Members

List overview

Public Instance Properties

Document | Gets the owner document.
IsListStyleDefinition | Returns true if this list is a definition of a list style.
IsListStyleReference | Returns true if this list is a reference to a list style.
IsMultiLevel | Returns true when the list contains 9 levels; false when 1 level.
IsRestartAtEachSection | Specifies whether list should be restarted at each section. Default value is false.
ListId | Gets the unique identifier of the list.
ListLevels | Gets the collection of list levels for this list.
Style | Gets the list style that this list references or defines.

Public Instance Methods

CompareTo
Equals
GetHashCode

See Also

List Class | Aspose.Words.Lists Namespace | ListCollection | ListLevel | ListFormat


List Properties

The properties of the List class are listed below. For a complete list of List class members, see the List Members topic.

Public Instance Properties

Document | Gets the owner document.
IsListStyleDefinition | Returns true if this list is a definition of a list style.
IsListStyleReference | Returns true if this list is a reference to a list style.
IsMultiLevel | Returns true when the list contains 9 levels; false when 1 level.
IsRestartAtEachSection | Specifies whether list should be restarted at each section. Default value is false.
ListId | Gets the unique identifier of the list.
ListLevels | Gets the collection of list levels for this list.
Style | Gets the list style that this list references or defines.

See Also

List Class | Aspose.Words.Lists Namespace | ListCollection | ListLevel | ListFormat


Document Property

Aspose.Words

List.Document Property

Gets the owner document.

[Visual Basic]
Public ReadOnly Property Document As DocumentBase
[C#]
public DocumentBase Document {get;}

Remarks

A list always has a parent document and is valid only in the context of that document.

Example

Illustrates the owner document properties of lists.

[C#]

Document doc = new Document();

ListCollection lists = doc.Lists;
// All of these should be equal.
Console.WriteLine("ListCollection document is doc: " + (doc == lists.Document));
Console.WriteLine("Starting list count: " + lists.Count);

List list = lists.Add(ListTemplate.BulletDefault);
Console.WriteLine("List document is doc: " + (list.Document == doc));
Console.WriteLine("List count after adding list: " + lists.Count);
Console.WriteLine("Is the first document list: " + (lists[0].Equals(list)));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1).Equals(list)));

See Also

List Class | Aspose.Words.Lists Namespace


IsListStyleDefinition Property

Aspose.Words

List.IsListStyleDefinition Property

Returns true if this list is a definition of a list style.

[Visual Basic]
Public ReadOnly Property IsListStyleDefinition As Boolean
[C#]
public bool IsListStyleDefinition {get;}

Remarks

When this property is true, the Style property returns the list style that this list defines.

By modifying properties of a list that defines a list style, you modify the properties of the list style.

A list that is a definition of a list style cannot be applied directly to paragraphs to make them numbered.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

List Class | Aspose.Words.Lists Namespace | Style | IsListStyleReference


IsListStyleReference Property

Aspose.Words

List.IsListStyleReference Property

Returns true if this list is a reference to a list style.

[Visual Basic]
Public ReadOnly Property IsListStyleReference As Boolean
[C#]
public bool IsListStyleReference {get;}

Remarks

Note, modifying properties of a list that is a reference to list style has no effect. The list formatting specified in the list style itself always takes precedence.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

List Class | Aspose.Words.Lists Namespace | Style | IsListStyleDefinition


IsMultiLevel Property

Aspose.Words

List.IsMultiLevel Property

Returns true when the list contains 9 levels; false when 1 level.

[Visual Basic]
Public ReadOnly Property IsMultiLevel As Boolean
[C#]
public bool IsMultiLevel {get;}

Remarks

The lists that you create with Aspose.Words are always multi-level lists and contain 9 levels.

Microsoft Word 2003 and later always create multi-level lists with 9 levels. But in some documents, created with earlier versions of Microsoft Word you might encounter lists that have 1 level only.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

List Class | Aspose.Words.Lists Namespace


IsRestartAtEachSection Property

Aspose.Words

List.IsRestartAtEachSection Property

Specifies whether list should be restarted at each section. Default value is false.

[Visual Basic]
Public Property IsRestartAtEachSection As Boolean
[C#]
public bool IsRestartAtEachSection {get; set;}

Remarks

This option is supported only in RTF, DOC and DOCX document formats.

This option will be written to DOCX only if OoxmlCompliance is higher then Ecma376_2006.

Example

Shows how to specify that the list has to be restarted at each section.

[C#]

Document doc = new Document();

doc.Lists.Add(ListTemplate.NumberDefault);

Aspose.Words.Lists.List list = doc.Lists[0];

// Set true to specify that the list has to be restarted at each section.
list.IsRestartAtEachSection = true;

DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;

for (int i = 1; i <= 45; i++)
{
    builder.Write($"List Item {i}\n");

    // Insert section break.
    if (i == 15 || i == 30)
        builder.InsertBreak(BreakType.SectionBreakNewPage);
}

// IsRestartAtEachSection will be written only if compliance is higher then OoxmlComplianceCore.Ecma376
OoxmlSaveOptions options = new OoxmlSaveOptions
{
    Compliance = OoxmlCompliance.Iso29500_2008_Transitional
};

doc.Save(ArtifactsDir + "RestartingDocumentList.docx", options);

See Also

List Class | Aspose.Words.Lists Namespace


ListId Property

Aspose.Words

List.ListId Property

Gets the unique identifier of the list.

[Visual Basic]
Public ReadOnly Property ListId As Integer
[C#]
public int ListId {get;}

Remarks

You do not normally need to use this property. But if you use it, you normally do so in conjunction with the GetListByListId method to find a list by its identifier.

Example

Finds and outputs all paragraphs in a document that are bulleted or numbered.

[C#]

NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph para in paras.OfType<Paragraph>())
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}",
            para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}
Illustrates the owner document properties of lists.
[C#]

Document doc = new Document();

ListCollection lists = doc.Lists;
// All of these should be equal.
Console.WriteLine("ListCollection document is doc: " + (doc == lists.Document));
Console.WriteLine("Starting list count: " + lists.Count);

List list = lists.Add(ListTemplate.BulletDefault);
Console.WriteLine("List document is doc: " + (list.Document == doc));
Console.WriteLine("List count after adding list: " + lists.Count);
Console.WriteLine("Is the first document list: " + (lists[0].Equals(list)));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1).Equals(list)));

See Also

List Class | Aspose.Words.Lists Namespace


ListLevels Property

Aspose.Words

List.ListLevels Property

Gets the collection of list levels for this list.

[Visual Basic]
Public ReadOnly Property ListLevels As ListLevelCollection
[C#]
public ListLevelCollection ListLevels {get;}

Remarks

Use this property to access and modify formatting individual to each level of the list.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

List Class | Aspose.Words.Lists Namespace


Style Property

Aspose.Words

List.Style Property

Gets the list style that this list references or defines.

[Visual Basic]
Public ReadOnly Property Style As Style
[C#]
public Style Style {get;}

Remarks

If this list is not associated with a list style, the property will return null.

A list could be a reference to a list style, in this case IsListStyleReference will be true.

A list could be a definition of a list style, in this case IsListStyleDefinition will be true. Such a list cannot be applied to paragraphs in the document directly.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

List Class | Aspose.Words.Lists Namespace


List Methods

The methods of the List class are listed below. For a complete list of List class members, see the List Members topic.

Public Instance Methods

CompareTo
Equals
GetHashCode

See Also

List Class | Aspose.Words.Lists Namespace | ListCollection | ListLevel | ListFormat


List.CompareTo Method

[Visual Basic]
NotOverridable Public Function CompareTo( _
ByVal obj As Object _
) As Integer _
Implements IComparable.CompareTo
[C#]
public int CompareTo(
object obj
);

Parameters

obj

Return Value

Implements

IComparable.CompareTo

See Also

List Class | Aspose.Words.Lists Namespace


List.Equals Method

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

See Also

List Class | Aspose.Words.Lists Namespace


List.GetHashCode Method

[Visual Basic]
Overrides Public Function GetHashCode() As Integer
[C#]
public override int GetHashCode();

See Also

List Class | Aspose.Words.Lists Namespace


ListCollection Class

Stores and manages formatting of bulleted and numbered lists used in a document.

For a list of all members of this type, see ListCollection Members.

System.Object
Aspose.Words.Lists.ListCollection

[Visual Basic]
Public Class ListCollection
Implements IEnumerable`1([Aspose.Words.Lists.List, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class ListCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

A list in a Microsoft Word document is a set of list formatting properties. The formatting of the lists is stored in the ListCollection collection separately from the paragraphs of text.

You do not create objects of this class. There is always only one ListCollection object per document and it is accessible via the Lists property.

To create a new list based on a predefined list template or based on a list style, use the Add method.

To create a new list with formatting identical to an existing list, use the AddCopy method.

To make a paragraph bulleted or numbered, you need to apply list formatting to a paragraph by assigning a List object to the List property of ListFormat.

To remove list formatting from a paragraph, use the RemoveNumbers method.

If you know a bit about WordprocessingML, then you might know it defines separate concepts for "list" and "list definition". This exactly corresponds to how list formatting is stored in a Microsoft Word document at the low level. List definition is like a "schema" and list is like an instance of a list definition.

To simplify programming model, Aspose.Words hides the distinction between list and list definition in much the same way like Microsoft Word hides this in its user interface. This allows you to concentrate more on how you want your document to look like, rather than building low-level objects to satisfy requirements of the Microsoft Word file format.

It is not possible to delete lists once they are created in the current version of Aspose.Words. This is similar to Microsoft Word where user does not have explicit control over list definitions.

Example

Shows how to specify list level number when building a list using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");
Enumerates through all lists defined in one document and creates a sample of those lists in another document.
[C#]

// You can use any of your documents to try this little program out.
    Document srcDoc = new Document(MyDir + "Lists.PrintOutAllLists.doc");

    // This will be the sample document we product.
    Document dstDoc = new Document();
    DocumentBuilder builder = new DocumentBuilder(dstDoc);

    foreach (List srcList in srcDoc.Lists)
    {
        // This copies the list formatting from the source into the destination document.
        List dstList = dstDoc.Lists.AddCopy(srcList);
        AddListSample(builder, dstList);
    }

    dstDoc.Save(ArtifactsDir + "Lists.PrintOutAllLists.doc");
}

private static void AddListSample(DocumentBuilder builder, List list)
{
    builder.Writeln("Sample formatting of list with ListId:" + list.ListId);
    builder.ListFormat.List = list;
    for (int i = 0; i < list.ListLevels.Count; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }

    builder.ListFormat.RemoveNumbers();
    builder.Writeln();
}
Shows how to restart numbering in a list by copying a list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ListCollection Members | Aspose.Words.Lists Namespace | List | ListLevel | ListFormat


ListCollection Members

ListCollection overview

Public Instance Properties

Count | Gets the count of numbered and bulleted lists in the document.
Document | Gets the owner document.
Item | Gets a list by index.

Public Instance Methods

Add | Overloaded. Creates a new list and adds it to the collection of lists in the document.
AddCopy | Creates a new list by copying the specified list and adding it to the collection of lists in the document.
GetEnumerator | Gets the enumerator object that will enumerate lists in the document.
GetListByListId | Gets a list by a list identifier.

See Also

ListCollection Class | Aspose.Words.Lists Namespace | List | ListLevel | ListFormat


ListCollection Properties

The properties of the ListCollection class are listed below. For a complete list of ListCollection class members, see the ListCollection Members topic.

Public Instance Properties

Count | Gets the count of numbered and bulleted lists in the document.
Document | Gets the owner document.
Item | Gets a list by index.

See Also

ListCollection Class | Aspose.Words.Lists Namespace | List | ListLevel | ListFormat


Count Property

Aspose.Words

ListCollection.Count Property

Gets the count of numbered and bulleted lists in the document.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Illustrates the owner document properties of lists.

[C#]

Document doc = new Document();

ListCollection lists = doc.Lists;
// All of these should be equal.
Console.WriteLine("ListCollection document is doc: " + (doc == lists.Document));
Console.WriteLine("Starting list count: " + lists.Count);

List list = lists.Add(ListTemplate.BulletDefault);
Console.WriteLine("List document is doc: " + (list.Document == doc));
Console.WriteLine("List count after adding list: " + lists.Count);
Console.WriteLine("Is the first document list: " + (lists[0].Equals(list)));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1).Equals(list)));

See Also

ListCollection Class | Aspose.Words.Lists Namespace


Document Property

Aspose.Words

ListCollection.Document Property

Gets the owner document.

[Visual Basic]
Public ReadOnly Property Document As DocumentBase
[C#]
public DocumentBase Document {get;}

Example

Illustrates the owner document properties of lists.

[C#]

Document doc = new Document();

ListCollection lists = doc.Lists;
// All of these should be equal.
Console.WriteLine("ListCollection document is doc: " + (doc == lists.Document));
Console.WriteLine("Starting list count: " + lists.Count);

List list = lists.Add(ListTemplate.BulletDefault);
Console.WriteLine("List document is doc: " + (list.Document == doc));
Console.WriteLine("List count after adding list: " + lists.Count);
Console.WriteLine("Is the first document list: " + (lists[0].Equals(list)));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1).Equals(list)));

See Also

ListCollection Class | Aspose.Words.Lists Namespace


Item Property

Aspose.Words

ListCollection.Item Property

Gets a list by index.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As List
[C#]
public List this[
int index
] {get;}

Example

Applies list formatting of an existing list to a collection of paragraphs.

[C#]

Body body = doc.FirstSection.Body;
List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
Illustrates the owner document properties of lists.
[C#]

Document doc = new Document();

ListCollection lists = doc.Lists;
// All of these should be equal.
Console.WriteLine("ListCollection document is doc: " + (doc == lists.Document));
Console.WriteLine("Starting list count: " + lists.Count);

List list = lists.Add(ListTemplate.BulletDefault);
Console.WriteLine("List document is doc: " + (list.Document == doc));
Console.WriteLine("List count after adding list: " + lists.Count);
Console.WriteLine("Is the first document list: " + (lists[0].Equals(list)));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1).Equals(list)));

See Also

ListCollection Class | Aspose.Words.Lists Namespace


ListCollection Methods

The methods of the ListCollection class are listed below. For a complete list of ListCollection class members, see the ListCollection Members topic.

Public Instance Methods

Add | Overloaded. Creates a new list and adds it to the collection of lists in the document.
AddCopy | Creates a new list by copying the specified list and adding it to the collection of lists in the document.
GetEnumerator | Gets the enumerator object that will enumerate lists in the document.
GetListByListId | Gets a list by a list identifier.

See Also

ListCollection Class | Aspose.Words.Lists Namespace | List | ListLevel | ListFormat


Add Method

Aspose.Words

ListCollection.Add Method

Creates a new list and adds it to the collection of lists in the document.

Overload List

Creates a new list based on a predefined template and adds it to the collection of lists in the document.

public List Add(ListTemplate);

Creates a new list that references a list style and adds it to the collection of lists in the document.

public List Add(Style);

See Also

ListCollection Class | Aspose.Words.Lists Namespace


ListCollection.Add Method (ListTemplate)

Creates a new list based on a predefined template and adds it to the collection of lists in the document.

[Visual Basic]
Overloads Public Function Add( _
ByVal template As ListTemplate _
) As List
[C#]
public List Add(
ListTemplate template
);

Parameters

template
The template of the list.

Return Value

The newly created list.

Remarks

Aspose.Words list templates correspond to the 21 list templates available in the Bullets and Numbering dialog box in Microsoft Word 2003.

All lists created using this method have 9 list levels.

Example

Creates new list formatting and applies it to a collection of paragraphs.

[C#]

List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

Body body = doc.FirstSection.Body;
foreach (Paragraph paragraph in body.Paragraphs.OfType<Paragraph>())
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 1;
}
Shows how to specify list level number when building a list using DocumentBuilder.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");
Shows how to restart numbering in a list by copying a list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");

See Also

ListCollection Class | Aspose.Words.Lists Namespace | ListCollection.Add Overload List


ListCollection.Add Method (Style)

Creates a new list that references a list style and adds it to the collection of lists in the document.

[Visual Basic]
Overloads Public Function Add( _
ByVal listStyle As Style _
) As List
[C#]
public List Add(
Style listStyle
);

Parameters

listStyle
The list style.

Return Value

The newly created list.

Remarks

The newly created list references the list style. If you change the properties of the list style, it is reflected in the properties of the list. Vice versa, if you change the properties of the list, it is reflected in the properties of the list style.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

ListCollection Class | Aspose.Words.Lists Namespace | ListCollection.Add Overload List


ListCollection.AddCopy Method

Creates a new list by copying the specified list and adding it to the collection of lists in the document.

[Visual Basic]
Public Function AddCopy( _
ByVal srcList As List _
) As List
[C#]
public List AddCopy(
List srcList
);

Parameters

srcList
The source list to copy from.

Return Value

The newly created list.

Remarks

The source list can be from any document. If the source list belongs to a different document, a copy of the list is created and added to the current document.

If the source list is a reference to or a definition of a list style, the newly created list is not related to the original list style.

Example

Enumerates through all lists defined in one document and creates a sample of those lists in another document.

[C#]

// You can use any of your documents to try this little program out.
    Document srcDoc = new Document(MyDir + "Lists.PrintOutAllLists.doc");

    // This will be the sample document we product.
    Document dstDoc = new Document();
    DocumentBuilder builder = new DocumentBuilder(dstDoc);

    foreach (List srcList in srcDoc.Lists)
    {
        // This copies the list formatting from the source into the destination document.
        List dstList = dstDoc.Lists.AddCopy(srcList);
        AddListSample(builder, dstList);
    }

    dstDoc.Save(ArtifactsDir + "Lists.PrintOutAllLists.doc");
}

private static void AddListSample(DocumentBuilder builder, List list)
{
    builder.Writeln("Sample formatting of list with ListId:" + list.ListId);
    builder.ListFormat.List = list;
    for (int i = 0; i < list.ListLevels.Count; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }

    builder.ListFormat.RemoveNumbers();
    builder.Writeln();
}
Shows how to restart numbering in a list by copying a list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");

See Also

ListCollection Class | Aspose.Words.Lists Namespace


ListCollection.GetEnumerator Method

Gets the enumerator object that will enumerate lists in the document.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of List) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<List> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Enumerates through all lists defined in one document and creates a sample of those lists in another document.

[C#]

// You can use any of your documents to try this little program out.
    Document srcDoc = new Document(MyDir + "Lists.PrintOutAllLists.doc");

    // This will be the sample document we product.
    Document dstDoc = new Document();
    DocumentBuilder builder = new DocumentBuilder(dstDoc);

    foreach (List srcList in srcDoc.Lists)
    {
        // This copies the list formatting from the source into the destination document.
        List dstList = dstDoc.Lists.AddCopy(srcList);
        AddListSample(builder, dstList);
    }

    dstDoc.Save(ArtifactsDir + "Lists.PrintOutAllLists.doc");
}

private static void AddListSample(DocumentBuilder builder, List list)
{
    builder.Writeln("Sample formatting of list with ListId:" + list.ListId);
    builder.ListFormat.List = list;
    for (int i = 0; i < list.ListLevels.Count; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }

    builder.ListFormat.RemoveNumbers();
    builder.Writeln();
}

See Also

ListCollection Class | Aspose.Words.Lists Namespace


ListCollection.GetListByListId Method

Gets a list by a list identifier.

[Visual Basic]
Public Function GetListByListId( _
ByVal listId As Integer _
) As List
[C#]
public List GetListByListId(
int listId
);

Parameters

listId
The list identifier.

Return Value

Returns the list object. Returns null if a list with the specified identifier was not found.

Remarks

You don't normally need to use this method. Most of the time you apply list formatting to paragraphs just by settings the List property of the ListFormat object.

Example

Illustrates the owner document properties of lists.

[C#]

Document doc = new Document();

ListCollection lists = doc.Lists;
// All of these should be equal.
Console.WriteLine("ListCollection document is doc: " + (doc == lists.Document));
Console.WriteLine("Starting list count: " + lists.Count);

List list = lists.Add(ListTemplate.BulletDefault);
Console.WriteLine("List document is doc: " + (list.Document == doc));
Console.WriteLine("List count after adding list: " + lists.Count);
Console.WriteLine("Is the first document list: " + (lists[0].Equals(list)));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1).Equals(list)));

See Also

ListCollection Class | Aspose.Words.Lists Namespace


ListLabel Class

Defines properties specific to a list label.

For a list of all members of this type, see ListLabel Members.

System.Object
Aspose.Words.Lists.ListLabel

[Visual Basic]
Public Class ListLabel
[C#]
public class ListLabel

Example

Shows how to extract the label of each paragraph in a list as a value or a String.

[C#]

Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
doc.UpdateListLabels();
int listParaCount = 1;

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
    // which start at three and ends at six.
    if (paragraph.ListFormat.IsListItem)
    {
        Console.WriteLine("Paragraph #{0}", listParaCount);

        // This is the text we get when actually getting when we output this node to text format.
        // The list labels are not included in this text output. Trim any paragraph formatting characters.
        String paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
        Console.WriteLine("Exported Text: " + paragraphText);

        ListLabel label = paragraph.ListLabel;
        // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
        // will tell us what position it is on that particular level.
        Console.WriteLine("Numerical Id: " + label.LabelValue);

        // Combine them together to include the list label with the text in the output.
        Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

        listParaCount++;
    }
}

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ListLabel Members | Aspose.Words.Lists Namespace


ListLabel Members

ListLabel overview

Public Instance Properties

Font | Gets the list label font.
LabelString | Gets a string representation of list label.
LabelValue | Gets a numeric value for this label.

See Also

ListLabel Class | Aspose.Words.Lists Namespace


ListLabel Properties

The properties of the ListLabel class are listed below. For a complete list of ListLabel class members, see the ListLabel Members topic.

Public Instance Properties

Font | Gets the list label font.
LabelString | Gets a string representation of list label.
LabelValue | Gets a numeric value for this label.

See Also

ListLabel Class | Aspose.Words.Lists Namespace


Font Property

Aspose.Words

ListLabel.Font Property

Gets the list label font.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

See Also

ListLabel Class | Aspose.Words.Lists Namespace


LabelString Property

Aspose.Words

ListLabel.LabelString Property

Gets a string representation of list label.

[Visual Basic]
Public ReadOnly Property LabelString As String
[C#]
public string LabelString {get;}

Example

Shows how to extract the label of each paragraph in a list as a value or a String.

[C#]

Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
doc.UpdateListLabels();
int listParaCount = 1;

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
    // which start at three and ends at six.
    if (paragraph.ListFormat.IsListItem)
    {
        Console.WriteLine("Paragraph #{0}", listParaCount);

        // This is the text we get when actually getting when we output this node to text format.
        // The list labels are not included in this text output. Trim any paragraph formatting characters.
        String paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
        Console.WriteLine("Exported Text: " + paragraphText);

        ListLabel label = paragraph.ListLabel;
        // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
        // will tell us what position it is on that particular level.
        Console.WriteLine("Numerical Id: " + label.LabelValue);

        // Combine them together to include the list label with the text in the output.
        Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

        listParaCount++;
    }
}

See Also

ListLabel Class | Aspose.Words.Lists Namespace


LabelValue Property

Aspose.Words

ListLabel.LabelValue Property

Gets a numeric value for this label.

[Visual Basic]
Public ReadOnly Property LabelValue As Integer
[C#]
public int LabelValue {get;}

Remarks

Use the UpdateListLabels method to update the value of this property.

Example

Shows how to extract the label of each paragraph in a list as a value or a String.

[C#]

Document doc = new Document(MyDir + "Lists.PrintOutAllLists.doc");
doc.UpdateListLabels();
int listParaCount = 1;

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true).OfType<Paragraph>())
{
    // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
    // which start at three and ends at six.
    if (paragraph.ListFormat.IsListItem)
    {
        Console.WriteLine("Paragraph #{0}", listParaCount);

        // This is the text we get when actually getting when we output this node to text format.
        // The list labels are not included in this text output. Trim any paragraph formatting characters.
        String paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
        Console.WriteLine("Exported Text: " + paragraphText);

        ListLabel label = paragraph.ListLabel;
        // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
        // will tell us what position it is on that particular level.
        Console.WriteLine("Numerical Id: " + label.LabelValue);

        // Combine them together to include the list label with the text in the output.
        Console.WriteLine("List label combined with text: " + label.LabelString + " " + paragraphText);

        listParaCount++;
    }
}

See Also

ListLabel Class | Aspose.Words.Lists Namespace


ListLevel Class

Defines formatting for a list level.

For a list of all members of this type, see ListLevel Members.

System.Object
Aspose.Words.Lists.ListLevel

[Visual Basic]
Public Class ListLevel
[C#]
public class ListLevel

Remarks

You do not create objects of this class. List level objects are created automatically when a list is created. You access ListLevel objects via the ListLevelCollection collection.

Use the properties of ListLevel to specify list formatting for individual list levels.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ListLevel Members | Aspose.Words.Lists Namespace


ListLevel Members

ListLevel overview

Public Instance Properties

Alignment | Gets or sets the justification of the actual number of the list item.
Font | Specifies character formatting used for the list label.
ImageData | Returns image data of the picture bullet shape for the current list level.
IsLegal | True if the level turns all inherited numbers to Arabic, false if it preserves their number style.
LinkedStyle | Gets or sets the paragraph style that is linked to this list level.
NumberFormat | Returns or sets the number format for the list level.
NumberPosition | Returns or sets the position (in points) of the number or bullet for the list level.
NumberStyle | Returns or sets the number style for this list level.
RestartAfterLevel | Sets or returns the list level that must appear before the specified list level restarts numbering.
StartAt | Returns or sets the starting number for this list level.
TabPosition | Returns or sets the tab position (in points) for the list level.
TextPosition | Returns or sets the position (in points) for the second line of wrapping text for the list level.
TrailingCharacter | Returns or sets the character inserted after the number for the list level.

Public Instance Methods

CreatePictureBullet | Creates picture bullet shape for the current list level.
DeletePictureBullet | Deletes picture bullet for the current list level.

See Also

ListLevel Class | Aspose.Words.Lists Namespace


ListLevel Properties

The properties of the ListLevel class are listed below. For a complete list of ListLevel class members, see the ListLevel Members topic.

Public Instance Properties

Alignment | Gets or sets the justification of the actual number of the list item.
Font | Specifies character formatting used for the list label.
ImageData | Returns image data of the picture bullet shape for the current list level.
IsLegal | True if the level turns all inherited numbers to Arabic, false if it preserves their number style.
LinkedStyle | Gets or sets the paragraph style that is linked to this list level.
NumberFormat | Returns or sets the number format for the list level.
NumberPosition | Returns or sets the position (in points) of the number or bullet for the list level.
NumberStyle | Returns or sets the number style for this list level.
RestartAfterLevel | Sets or returns the list level that must appear before the specified list level restarts numbering.
StartAt | Returns or sets the starting number for this list level.
TabPosition | Returns or sets the tab position (in points) for the list level.
TextPosition | Returns or sets the position (in points) for the second line of wrapping text for the list level.
TrailingCharacter | Returns or sets the character inserted after the number for the list level.

See Also

ListLevel Class | Aspose.Words.Lists Namespace


Alignment Property

Aspose.Words

ListLevel.Alignment Property

Gets or sets the justification of the actual number of the list item.

[Visual Basic]
Public Property Alignment As ListLevelAlignment
[C#]
public ListLevelAlignment Alignment {get; set;}

Remarks

The list label is justified relative to the NumberPosition property.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


Font Property

Aspose.Words

ListLevel.Font Property

Specifies character formatting used for the list label.

[Visual Basic]
Public ReadOnly Property Font As Font
[C#]
public Font Font {get;}

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


ImageData Property

Aspose.Words

ListLevel.ImageData Property

Returns image data of the picture bullet shape for the current list level.

[Visual Basic]
Public ReadOnly Property ImageData As ImageData
[C#]
public ImageData ImageData {get;}

Remarks

If this level doesn't define picture bullet returns null. Before setting new image for non picture bullet shape, please use CreatePictureBullet method first.

See Also

ListLevel Class | Aspose.Words.Lists Namespace


IsLegal Property

Aspose.Words

ListLevel.IsLegal Property

True if the level turns all inherited numbers to Arabic, false if it preserves their number style.

[Visual Basic]
Public Property IsLegal As Boolean
[C#]
public bool IsLegal {get; set;}

Example

Shows how to create a list with some advanced formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Level 1 labels will be "Appendix A", continuous and linked to the Heading 1 paragraph style.
list.ListLevels[0].NumberFormat = "Appendix \x0000";
list.ListLevels[0].NumberStyle = NumberStyle.UppercaseLetter;
list.ListLevels[0].LinkedStyle = doc.Styles["Heading 1"];

// Level 2 labels will be "Section (1.01)" and restarting after Level 2 item appears.
list.ListLevels[1].NumberFormat = "Section (\x0000.\x0001)";
list.ListLevels[1].NumberStyle = NumberStyle.LeadingZero;
// Notice the higher level uses UppercaseLetter numbering, but we want arabic number
// of the higher levels to appear in this level, therefore set this property.
list.ListLevels[1].IsLegal = true;
list.ListLevels[1].RestartAfterLevel = 0;

// Level 3 labels will be "-I-" and restarting after Level 2 item appears.
list.ListLevels[2].NumberFormat = "-\x0002-";
list.ListLevels[2].NumberStyle = NumberStyle.UppercaseRoman;
list.ListLevels[2].RestartAfterLevel = 1;

// Make labels of all list levels bold.
foreach (ListLevel level in list.ListLevels)
    level.Font.Bold = true;

// Apply list formatting to the current paragraph.
builder.ListFormat.List = list;

// Exercise the 3 levels we created two times.
for (int n = 0; n < 2; n++)
{
    for (int i = 0; i < 3; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }
}

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateListRestartAfterHigher.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


LinkedStyle Property

Aspose.Words

ListLevel.LinkedStyle Property

Gets or sets the paragraph style that is linked to this list level.

[Visual Basic]
Public Property LinkedStyle As Style
[C#]
public Style LinkedStyle {get; set;}

Remarks

This property is null when the list level is not linked to a paragraph style. This property can be set to null.

Example

Shows how to create a list with some advanced formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Level 1 labels will be "Appendix A", continuous and linked to the Heading 1 paragraph style.
list.ListLevels[0].NumberFormat = "Appendix \x0000";
list.ListLevels[0].NumberStyle = NumberStyle.UppercaseLetter;
list.ListLevels[0].LinkedStyle = doc.Styles["Heading 1"];

// Level 2 labels will be "Section (1.01)" and restarting after Level 2 item appears.
list.ListLevels[1].NumberFormat = "Section (\x0000.\x0001)";
list.ListLevels[1].NumberStyle = NumberStyle.LeadingZero;
// Notice the higher level uses UppercaseLetter numbering, but we want arabic number
// of the higher levels to appear in this level, therefore set this property.
list.ListLevels[1].IsLegal = true;
list.ListLevels[1].RestartAfterLevel = 0;

// Level 3 labels will be "-I-" and restarting after Level 2 item appears.
list.ListLevels[2].NumberFormat = "-\x0002-";
list.ListLevels[2].NumberStyle = NumberStyle.UppercaseRoman;
list.ListLevels[2].RestartAfterLevel = 1;

// Make labels of all list levels bold.
foreach (ListLevel level in list.ListLevels)
    level.Font.Bold = true;

// Apply list formatting to the current paragraph.
builder.ListFormat.List = list;

// Exercise the 3 levels we created two times.
for (int n = 0; n < 2; n++)
{
    for (int i = 0; i < 3; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }
}

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateListRestartAfterHigher.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


NumberFormat Property

Aspose.Words

ListLevel.NumberFormat Property

Returns or sets the number format for the list level.

[Visual Basic]
Public Property NumberFormat As String
[C#]
public string NumberFormat {get; set;}

Remarks

Among normal text characters, the string can contain placeholder characters \x0000 to \x0008 representing the numbers from the corresponding list levels.

For example, the string "\x0000.\x0001)" will generate a list label that looks something like "1.5)". The number "1" is the current number from the 1st list level, the number "5" is the current number from the 2nd list level.

Null is not allowed, but an empty string meaning no number is valid.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");
Shows how to create a list with some advanced formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Level 1 labels will be "Appendix A", continuous and linked to the Heading 1 paragraph style.
list.ListLevels[0].NumberFormat = "Appendix \x0000";
list.ListLevels[0].NumberStyle = NumberStyle.UppercaseLetter;
list.ListLevels[0].LinkedStyle = doc.Styles["Heading 1"];

// Level 2 labels will be "Section (1.01)" and restarting after Level 2 item appears.
list.ListLevels[1].NumberFormat = "Section (\x0000.\x0001)";
list.ListLevels[1].NumberStyle = NumberStyle.LeadingZero;
// Notice the higher level uses UppercaseLetter numbering, but we want arabic number
// of the higher levels to appear in this level, therefore set this property.
list.ListLevels[1].IsLegal = true;
list.ListLevels[1].RestartAfterLevel = 0;

// Level 3 labels will be "-I-" and restarting after Level 2 item appears.
list.ListLevels[2].NumberFormat = "-\x0002-";
list.ListLevels[2].NumberStyle = NumberStyle.UppercaseRoman;
list.ListLevels[2].RestartAfterLevel = 1;

// Make labels of all list levels bold.
foreach (ListLevel level in list.ListLevels)
    level.Font.Bold = true;

// Apply list formatting to the current paragraph.
builder.ListFormat.List = list;

// Exercise the 3 levels we created two times.
for (int n = 0; n < 2; n++)
{
    for (int i = 0; i < 3; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }
}

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateListRestartAfterHigher.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


NumberPosition Property

Aspose.Words

ListLevel.NumberPosition Property

Returns or sets the position (in points) of the number or bullet for the list level.

[Visual Basic]
Public Property NumberPosition As Double
[C#]
public double NumberPosition {get; set;}

Remarks

NumberPosition corresponds to LeftIndent plus FirstLineIndent of the paragraph.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace | TextPosition | TabPosition


NumberStyle Property

Aspose.Words

ListLevel.NumberStyle Property

Returns or sets the number style for this list level.

[Visual Basic]
Public Property NumberStyle As NumberStyle
[C#]
public NumberStyle NumberStyle {get; set;}

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");
Shows how to create a list with some advanced formatting.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Level 1 labels will be "Appendix A", continuous and linked to the Heading 1 paragraph style.
list.ListLevels[0].NumberFormat = "Appendix \x0000";
list.ListLevels[0].NumberStyle = NumberStyle.UppercaseLetter;
list.ListLevels[0].LinkedStyle = doc.Styles["Heading 1"];

// Level 2 labels will be "Section (1.01)" and restarting after Level 2 item appears.
list.ListLevels[1].NumberFormat = "Section (\x0000.\x0001)";
list.ListLevels[1].NumberStyle = NumberStyle.LeadingZero;
// Notice the higher level uses UppercaseLetter numbering, but we want arabic number
// of the higher levels to appear in this level, therefore set this property.
list.ListLevels[1].IsLegal = true;
list.ListLevels[1].RestartAfterLevel = 0;

// Level 3 labels will be "-I-" and restarting after Level 2 item appears.
list.ListLevels[2].NumberFormat = "-\x0002-";
list.ListLevels[2].NumberStyle = NumberStyle.UppercaseRoman;
list.ListLevels[2].RestartAfterLevel = 1;

// Make labels of all list levels bold.
foreach (ListLevel level in list.ListLevels)
    level.Font.Bold = true;

// Apply list formatting to the current paragraph.
builder.ListFormat.List = list;

// Exercise the 3 levels we created two times.
for (int n = 0; n < 2; n++)
{
    for (int i = 0; i < 3; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }
}

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateListRestartAfterHigher.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


RestartAfterLevel Property

Aspose.Words

ListLevel.RestartAfterLevel Property

Sets or returns the list level that must appear before the specified list level restarts numbering.

[Visual Basic]
Public Property RestartAfterLevel As Integer
[C#]
public int RestartAfterLevel {get; set;}

Remarks

The value of -1 means the numbering will continue.

Example

Shows how to create a list with some advanced formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Level 1 labels will be "Appendix A", continuous and linked to the Heading 1 paragraph style.
list.ListLevels[0].NumberFormat = "Appendix \x0000";
list.ListLevels[0].NumberStyle = NumberStyle.UppercaseLetter;
list.ListLevels[0].LinkedStyle = doc.Styles["Heading 1"];

// Level 2 labels will be "Section (1.01)" and restarting after Level 2 item appears.
list.ListLevels[1].NumberFormat = "Section (\x0000.\x0001)";
list.ListLevels[1].NumberStyle = NumberStyle.LeadingZero;
// Notice the higher level uses UppercaseLetter numbering, but we want arabic number
// of the higher levels to appear in this level, therefore set this property.
list.ListLevels[1].IsLegal = true;
list.ListLevels[1].RestartAfterLevel = 0;

// Level 3 labels will be "-I-" and restarting after Level 2 item appears.
list.ListLevels[2].NumberFormat = "-\x0002-";
list.ListLevels[2].NumberStyle = NumberStyle.UppercaseRoman;
list.ListLevels[2].RestartAfterLevel = 1;

// Make labels of all list levels bold.
foreach (ListLevel level in list.ListLevels)
    level.Font.Bold = true;

// Apply list formatting to the current paragraph.
builder.ListFormat.List = list;

// Exercise the 3 levels we created two times.
for (int n = 0; n < 2; n++)
{
    for (int i = 0; i < 3; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }
}

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateListRestartAfterHigher.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


StartAt Property

Aspose.Words

ListLevel.StartAt Property

Returns or sets the starting number for this list level.

[Visual Basic]
Public Property StartAt As Integer
[C#]
public int StartAt {get; set;}

Remarks

Default value is 1.

Example

Shows how to restart numbering in a list by copying a list.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");
Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.
[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


TabPosition Property

Aspose.Words

ListLevel.TabPosition Property

Returns or sets the tab position (in points) for the list level.

[Visual Basic]
Public Property TabPosition As Double
[C#]
public double TabPosition {get; set;}

Remarks

Has effect only when TrailingCharacter is a tab.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace | NumberPosition | TextPosition


TextPosition Property

Aspose.Words

ListLevel.TextPosition Property

Returns or sets the position (in points) for the second line of wrapping text for the list level.

[Visual Basic]
Public Property TextPosition As Double
[C#]
public double TextPosition {get; set;}

Remarks

TextPosition corresponds to LeftIndent of the paragraph.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace | NumberPosition | TabPosition


TrailingCharacter Property

Aspose.Words

ListLevel.TrailingCharacter Property

Returns or sets the character inserted after the number for the list level.

[Visual Basic]
Public Property TrailingCharacter As ListTrailingCharacter
[C#]
public ListTrailingCharacter TrailingCharacter {get; set;}

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

See Also

ListLevel Class | Aspose.Words.Lists Namespace


ListLevel Methods

The methods of the ListLevel class are listed below. For a complete list of ListLevel class members, see the ListLevel Members topic.

Public Instance Methods

CreatePictureBullet | Creates picture bullet shape for the current list level.
DeletePictureBullet | Deletes picture bullet for the current list level.

See Also

ListLevel Class | Aspose.Words.Lists Namespace


ListLevel.CreatePictureBullet Method

Creates picture bullet shape for the current list level.

[Visual Basic]
Public Sub CreatePictureBullet()
[C#]
public void CreatePictureBullet();

Remarks

Please note, NumberStyle will be set to Bullet and NumberFormat to "\xF0B7" to properly display picture bullet. Red cross image will be set as picture bullet image upon creating. To change it please use ImageData.

Example

Shows how to creating and deleting picture bullet with custom image

[C#]

Document doc = new Document();

// Create a list with template
List list = doc.Lists.Add(ListTemplate.BulletCircle);

// Create picture bullet for the current list level
list.ListLevels[0].CreatePictureBullet();

// Set your own picture bullet image through the ImageData
list.ListLevels[0].ImageData.SetImage(_image);

Assert.IsTrue(list.ListLevels[0].ImageData.HasImage);

// Delete picture bullet
list.ListLevels[0].DeletePictureBullet();

Assert.IsNull(list.ListLevels[0].ImageData);

See Also

ListLevel Class | Aspose.Words.Lists Namespace


ListLevel.DeletePictureBullet Method

Deletes picture bullet for the current list level.

[Visual Basic]
Public Sub DeletePictureBullet()
[C#]
public void DeletePictureBullet();

Remarks

Default bullet will be shown after deleting.

Example

Shows how to creating and deleting picture bullet with custom image

[C#]

Document doc = new Document();

// Create a list with template
List list = doc.Lists.Add(ListTemplate.BulletCircle);

// Create picture bullet for the current list level
list.ListLevels[0].CreatePictureBullet();

// Set your own picture bullet image through the ImageData
list.ListLevels[0].ImageData.SetImage(_image);

Assert.IsTrue(list.ListLevels[0].ImageData.HasImage);

// Delete picture bullet
list.ListLevels[0].DeletePictureBullet();

Assert.IsNull(list.ListLevels[0].ImageData);

See Also

ListLevel Class | Aspose.Words.Lists Namespace


ListLevelAlignment Enumeration

Specifies alignment for the list number or bullet.

[Visual Basic]
Public Enum ListLevelAlignment
[C#]
public enum ListLevelAlignment

Remarks

Used as a value for the Alignment property.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

Members

Member Name | Description | Value
Left | The list label is aligned to the left of the number position. | 0
Center | The list label is centered at the number position. | 1
Right | This list label is aligned to the right of the number position. | 2

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Lists Namespace


ListLevelCollection Class

A collection of list formatting for each level in a list.

For a list of all members of this type, see ListLevelCollection Members.

System.Object
Aspose.Words.Lists.ListLevelCollection

[Visual Basic]
Public Class ListLevelCollection
Implements IEnumerable`1([Aspose.Words.Lists.ListLevel, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class ListLevelCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");
Shows how to create a list style and use it in a document.
[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ListLevelCollection Members | Aspose.Words.Lists Namespace


ListLevelCollection Members

ListLevelCollection overview

Public Instance Properties

Count | Gets the number of levels in this list.
Item | Gets a list level by index.

Public Instance Methods

GetEnumerator Gets the enumerator object that will enumerate levels in this list.

See Also

ListLevelCollection Class | Aspose.Words.Lists Namespace


ListLevelCollection Properties

The properties of the ListLevelCollection class are listed below. For a complete list of ListLevelCollection class members, see the ListLevelCollection Members topic.

Public Instance Properties

Count | Gets the number of levels in this list.
Item | Gets a list level by index.

See Also

ListLevelCollection Class | Aspose.Words.Lists Namespace


Count Property

Aspose.Words

ListLevelCollection.Count Property

Gets the number of levels in this list.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Remarks

There could be 1 or 9 levels in a list.

Example

Shows how to create a list style and use it in a document.

[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

ListLevelCollection Class | Aspose.Words.Lists Namespace


Item Property

Aspose.Words

ListLevelCollection.Item Property

Gets a list level by index.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As ListLevel
[C#]
public ListLevel this[
int index
] {get; set;}

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");
Shows how to create a list style and use it in a document.
[C#]

Document doc = new Document();

// Create a new list style.
// List formatting associated with this list style is default numbered.
Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle");

// This list defines the formatting of the list style.
// Note this list can not be used directly to apply formatting to paragraphs (see below).
List list1 = listStyle.List;

// Check some basic rules about the list that defines a list style.
Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference);
Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel);
Console.WriteLine("List style has been set: " + (listStyle == list1.Style));

// Modify formatting of the list style to our liking.
for (int i = 0; i < list1.ListLevels.Count; i++)
{
    ListLevel level = list1.ListLevels[i];
    level.Font.Name = "Verdana";
    level.Font.Color = Color.Blue;
    level.Font.Bold = true;
}

// Add some text to our document and use the list style.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Using list style first time:");

// This creates a list based on the list style.
List list2 = doc.Lists.Add(listStyle);

// Check some basic rules about the list that references a list style.
Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition);
Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference);
Console.WriteLine("List Style has been set: " + (listStyle == list2.Style));

// Apply the list that references the list style.
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Writeln("Using list style second time:");

// Create and apply another list based on the list style.
List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateAndUseListStyle.doc");

See Also

ListLevelCollection Class | Aspose.Words.Lists Namespace


ListLevelCollection Methods

The methods of the ListLevelCollection class are listed below. For a complete list of ListLevelCollection class members, see the ListLevelCollection Members topic.

Public Instance Methods

GetEnumerator Gets the enumerator object that will enumerate levels in this list.

See Also

ListLevelCollection Class | Aspose.Words.Lists Namespace


ListLevelCollection.GetEnumerator Method

Gets the enumerator object that will enumerate levels in this list.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of ListLevel) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<ListLevel> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to create a list with some advanced formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Level 1 labels will be "Appendix A", continuous and linked to the Heading 1 paragraph style.
list.ListLevels[0].NumberFormat = "Appendix \x0000";
list.ListLevels[0].NumberStyle = NumberStyle.UppercaseLetter;
list.ListLevels[0].LinkedStyle = doc.Styles["Heading 1"];

// Level 2 labels will be "Section (1.01)" and restarting after Level 2 item appears.
list.ListLevels[1].NumberFormat = "Section (\x0000.\x0001)";
list.ListLevels[1].NumberStyle = NumberStyle.LeadingZero;
// Notice the higher level uses UppercaseLetter numbering, but we want arabic number
// of the higher levels to appear in this level, therefore set this property.
list.ListLevels[1].IsLegal = true;
list.ListLevels[1].RestartAfterLevel = 0;

// Level 3 labels will be "-I-" and restarting after Level 2 item appears.
list.ListLevels[2].NumberFormat = "-\x0002-";
list.ListLevels[2].NumberStyle = NumberStyle.UppercaseRoman;
list.ListLevels[2].RestartAfterLevel = 1;

// Make labels of all list levels bold.
foreach (ListLevel level in list.ListLevels)
    level.Font.Bold = true;

// Apply list formatting to the current paragraph.
builder.ListFormat.List = list;

// Exercise the 3 levels we created two times.
for (int n = 0; n < 2; n++)
{
    for (int i = 0; i < 3; i++)
    {
        builder.ListFormat.ListLevelNumber = i;
        builder.Writeln("Level " + i);
    }
}

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateListRestartAfterHigher.doc");

See Also

ListLevelCollection Class | Aspose.Words.Lists Namespace


ListTemplate Enumeration

Specifies one of the predefined list formats available in Microsoft Word.

[Visual Basic]
Public Enum ListTemplate
[C#]
public enum ListTemplate

Remarks

A list template value is used as a parameter into the Add method.

Aspose.Words list templates correspond to the 21 list templates available in the Bullets and Numbering dialog box in Microsoft Word 2003.

Example

Shows how to specify list level number when building a list using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.NumberArabicDot);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder.ListFormat.List = doc.Lists.Add(ListTemplate.BulletDiamonds);

// There are 9 levels in this list, lets try them all.
for (int i = 0; i < 9; i++)
{
    builder.ListFormat.ListLevelNumber = i;
    builder.Writeln("Level " + i);
}

// This is a way to stop list formatting.
builder.ListFormat.List = null;

builder.Document.Save(ArtifactsDir + "Lists.SpecifyListLevel.doc");
Shows how to restart numbering in a list by copying a list.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list based on a template.
List list1 = doc.Lists.Add(ListTemplate.NumberArabicParenthesis);
// Modify the formatting of the list.
list1.ListLevels[0].Font.Color = Color.Red;
list1.ListLevels[0].Alignment = ListLevelAlignment.Right;

builder.Writeln("List 1 starts below:");
// Use the first list in the document for a while.
builder.ListFormat.List = list1;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
List list2 = doc.Lists.AddCopy(list1);

// We can modify the new list in any way. Including setting new start number.
list2.ListLevels[0].StartAt = 10;

// Use the second list in the document.
builder.Writeln("List 2 starts below:");
builder.ListFormat.List = list2;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.RestartNumberingUsingListCopy.doc");
Creates a sample document that exercises all outline headings list templates.
[C#]

public void OutlineHeadingTemplates()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    List list = doc.Lists.Add(ListTemplate.OutlineHeadingsArticleSection);
    AddOutlineHeadingParagraphs(builder, list, "Aspose.Words Outline 1");

    list = doc.Lists.Add(ListTemplate.OutlineHeadingsLegal);
    AddOutlineHeadingParagraphs(builder, list, "Aspose.Words Outline 2");

    builder.InsertBreak(BreakType.PageBreak);

    list = doc.Lists.Add(ListTemplate.OutlineHeadingsNumbers);
    AddOutlineHeadingParagraphs(builder, list, "Aspose.Words Outline 3");

    list = doc.Lists.Add(ListTemplate.OutlineHeadingsChapter);
    AddOutlineHeadingParagraphs(builder, list, "Aspose.Words Outline 4");

    builder.Document.Save(ArtifactsDir + "Lists.OutlineHeadingTemplates.doc");
}

private static void AddOutlineHeadingParagraphs(DocumentBuilder builder, List list, String title)
{
    builder.ParagraphFormat.ClearFormatting();
    builder.Writeln(title);

    for (int i = 0; i < 9; i++)
    {
        builder.ListFormat.List = list;
        builder.ListFormat.ListLevelNumber = i;

        String styleName = "Heading " + (i + 1).ToString();
        builder.ParagraphFormat.StyleName = styleName;
        builder.Writeln(styleName);
    }

    builder.ListFormat.RemoveNumbers();
}

Members

Member Name Description Value
BulletDefault

Default bulleted list with 9 levels. Bullet of the first level is a disc, bullet of the second level is a circle, bullet of the third level is a square. Then formatting repeats for the remaining levels.

Each level is indented to the right by 0.25" relative to the previous level.

Corresponds to the 1st bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

0
BulletDisk

Same as BulletDefault.

Corresponds to the 1st bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

0
BulletCircle

The bullet of the first level is a circle. The remaining levels are same as in BulletDefault.

Corresponds to the 2nd bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

1
BulletSquare

The bullet of the first level is a square. The remaining levels are same as in BulletDefault.

Corresponds to the 3rd bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

2
BulletDiamonds

The bullet of the first level is a 4-diamond Wingding character. The remaining levels are same as in BulletDefault.

Corresponds to the 5th bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

3
BulletArrowHead

The bullet of the first level is an arrow head Wingding character. The remaining levels are same as in BulletDefault.

Corresponds to the 6th bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

4
BulletTick

The bullet of the first level is a tick Wingding character. The remaining levels are same as in BulletDefault.

Corresponds to the 7th bulleted list template in the Bullets and Numbering dialog box in Microsoft Word.

5
NumberDefault

Default numbered list with 9 levels. Arabic numbering (1., 2., 3., ...) for the first level, lowecase letter numbering (a., b., c., ...) for the second level, lowercase roman numbering (i., ii., iii., ...) for the third level. Then formatting repeats for the remaining levels.

Each level is indented to the right by 0.25" relative to the previous level.

Corresponds to the 1st numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

6
NumberArabicDot

Same as NumberDefault.

Corresponds to the 1st numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

6
NumberArabicParenthesis

The number of the first level is "1)". The remaining levels are same as in NumberDefault.

Corresponds to the 2nd numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

7
NumberUppercaseRomanDot

The number of the first level is "I.". The remaining levels are same as in NumberDefault.

Corresponds to the 3rd numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

8
NumberUppercaseLetterDot

The number of the first level is "A.". The remaining levels are same as in NumberDefault.

Corresponds to the 4th numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

9
NumberLowercaseLetterParenthesis

The number of the first level is "a)". The remaining levels are same as in NumberDefault.

Corresponds to the 5th numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

10
NumberLowercaseLetterDot

The number of the first level is "a.". The remaining levels are same as in NumberDefault.

Corresponds to the 6th numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

11
NumberLowercaseRomanDot

The number of the first level is "i.". The remaining levels are same as in NumberDefault.

Corresponds to the 7th numbered list template in the Bullets and Numbering dialog box in Microsoft Word.

12
OutlineNumbers

An outline list with levels numbered "1), a), i), (1), (a), (i), 1., a., i.".

Corresponds to the 1st outline list template in the Bullets and Numbering dialog box in Microsoft Word.

13
OutlineLegal

An outline list with levels are numbered "1., 1.1., 1.1.1, ...".

Corresponds to the 2nd outline list template in the Bullets and Numbering dialog box in Microsoft Word.

14
OutlineBullets

An outline lists with various bullets for different levels.

Corresponds to the 3rd outline list template in the Bullets and Numbering dialog box in Microsoft Word.

15
OutlineHeadingsArticleSection

An outline list with levels linked to Heading styles.

Corresponds to the 4th outline list template in the Bullets and Numbering dialog box in Microsoft Word.

16
OutlineHeadingsLegal

An outline list with levels linked to Heading styles.

Corresponds to the 5th outline list template in the Bullets and Numbering dialog box in Microsoft Word.

17
OutlineHeadingsNumbers

An outline list with levels linked to Heading styles.

Corresponds to the 6th outline list template in the Bullets and Numbering dialog box in Microsoft Word.

18
OutlineHeadingsChapter

An outline list with levels linked to Heading styles.

Corresponds to the 7th outline list template in the Bullets and Numbering dialog box in Microsoft Word.

19

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Lists Namespace


ListTrailingCharacter Enumeration

Specifies the character that separates the list label from the text of the paragraph.

[Visual Basic]
Public Enum ListTrailingCharacter
[C#]
public enum ListTrailingCharacter

Remarks

Used as a value for the TrailingCharacter property.

Example

Shows how to apply custom list formatting to paragraphs when using DocumentBuilder.

[C#]

Document doc = new Document();

// Create a list based on one of the Microsoft Word list templates.
List list = doc.Lists.Add(ListTemplate.NumberDefault);

// Completely customize one list level.
ListLevel level1 = list.ListLevels[0];
level1.Font.Color = Color.Red;
level1.Font.Size = 24;
level1.NumberStyle = NumberStyle.OrdinalText;
level1.StartAt = 21;
level1.NumberFormat = "\x0000";

level1.NumberPosition = -36;
level1.TextPosition = 144;
level1.TabPosition = 144;

// Completely customize yet another list level.
ListLevel level2 = list.ListLevels[1];
level2.Alignment = ListLevelAlignment.Right;
level2.NumberStyle = NumberStyle.Bullet;
level2.Font.Name = "Wingdings";
level2.Font.Color = Color.Blue;
level2.Font.Size = 24;
level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star.
level2.TrailingCharacter = ListTrailingCharacter.Space;
level2.NumberPosition = 144;

// Now add some text that uses the list that we created.
// It does not matter when to customize the list - before or after adding the paragraphs.
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.List = list;
builder.Writeln("The quick brown fox...");
builder.Writeln("The quick brown fox...");

builder.ListFormat.ListIndent();
builder.Writeln("jumped over the lazy dog.");
builder.Writeln("jumped over the lazy dog.");

builder.ListFormat.ListOutdent();
builder.Writeln("The quick brown fox...");

builder.ListFormat.RemoveNumbers();

builder.Document.Save(ArtifactsDir + "Lists.CreateCustomList.doc");

Members

Member Name | Description | Value
Tab | A tab character is placed between the list label and text of the paragraph. | 0
Space | A space character is placed between the list label and text of the paragraph. | 1
Nothing | There is no separator character between the list label and text of the paragraph. | 2

Requirements

Namespace: Aspose.Words.Lists

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Lists Namespace


Aspose.Words.Loading

Aspose.Words

Aspose.Words.Loading Namespace

The Aspose.Words.Loading namespace provides classes and enumerations that allow to specify additional options when loading documents.

Namespace hierarchy

Classes

Class | Description
ResourceLoadingArgs | Provides data for the ResourceLoading method.

Interfaces

Interface | Description
IResourceLoadingCallback | Implement this interface if you want to control how Aspose.Words loads external resource when importing a document from HTML or MHTML.

Enumerations

Enumeration | Description
ResourceLoadingAction | Specifies the mode of resource loading.
ResourceType | Type of loaded resource.


IResourceLoadingCallback Interface

Implement this interface if you want to control how Aspose.Words loads external resource when importing a document from HTML or MHTML.

For a list of all members of this type, see IResourceLoadingCallback Members.

[Visual Basic]
Public Interface IResourceLoadingCallback
[C#]
public interface IResourceLoadingCallback

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

Requirements

Namespace: Aspose.Words.Loading

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IResourceLoadingCallback Members | Aspose.Words.Loading Namespace


IResourceLoadingCallback Members

IResourceLoadingCallback overview

Public Instance Methods

ResourceLoading Called when Aspose.Words loads any external resource.

See Also

IResourceLoadingCallback Interface | Aspose.Words.Loading Namespace


IResourceLoadingCallback Methods

The methods of the IResourceLoadingCallback interface are listed below. For a complete list of IResourceLoadingCallback interface members, see the IResourceLoadingCallback Members topic.

Public Instance Methods

ResourceLoading Called when Aspose.Words loads any external resource.

See Also

IResourceLoadingCallback Interface | Aspose.Words.Loading Namespace


IResourceLoadingCallback.ResourceLoading Method

Called when Aspose.Words loads any external resource.

[Visual Basic]
Function ResourceLoading( _
ByVal args As ResourceLoadingArgs _
) As ResourceLoadingAction
[C#]
ResourceLoadingAction ResourceLoading(
ResourceLoadingArgs args
);

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

See Also

IResourceLoadingCallback Interface | Aspose.Words.Loading Namespace


ResourceLoadingAction Enumeration

Specifies the mode of resource loading.

[Visual Basic]
Public Enum ResourceLoadingAction
[C#]
public enum ResourceLoadingAction

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

Members

Member Name | Description | Value
Default | Aspose.Words will load this resource as usual. | 0
Skip | Aspose.Words will skip loading of this resource. Only link without data will be stored for an image. Css style sheet will be ignored. | 1
UserProvided | Aspose.Words will use byte array provided by user in SetData as resource data. | 2

Requirements

Namespace: Aspose.Words.Loading

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Loading Namespace


ResourceLoadingArgs Class

Provides data for the ResourceLoading method.

For a list of all members of this type, see ResourceLoadingArgs Members.

System.Object
Aspose.Words.Loading.ResourceLoadingArgs

[Visual Basic]
Public Class ResourceLoadingArgs
[C#]
public class ResourceLoadingArgs

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

Requirements

Namespace: Aspose.Words.Loading

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ResourceLoadingArgs Members | Aspose.Words.Loading Namespace


ResourceLoadingArgs Members

ResourceLoadingArgs overview

Public Instance Properties

OriginalUri | Original URI of the resource as specified in imported document.
ResourceType | Type of resource.
Uri | URI of the resource which is used for downloading if ResourceLoading returns Default. Initially it's set to absolute URI of the resource, but user can redefine it to any value.

Public Instance Methods

SetData Sets user provided data of the resource which is used if ResourceLoading returns UserProvided.

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


ResourceLoadingArgs Properties

The properties of the ResourceLoadingArgs class are listed below. For a complete list of ResourceLoadingArgs class members, see the ResourceLoadingArgs Members topic.

Public Instance Properties

OriginalUri | Original URI of the resource as specified in imported document.
ResourceType | Type of resource.
Uri | URI of the resource which is used for downloading if ResourceLoading returns Default. Initially it's set to absolute URI of the resource, but user can redefine it to any value.

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


OriginalUri Property

Aspose.Words

ResourceLoadingArgs.OriginalUri Property

Original URI of the resource as specified in imported document.

[Visual Basic]
Public ReadOnly Property OriginalUri As String
[C#]
public string OriginalUri {get;}

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


ResourceType Property

Aspose.Words

ResourceLoadingArgs.ResourceType Property

Type of resource.

[Visual Basic]
Public ReadOnly Property ResourceType As ResourceType
[C#]
public ResourceType ResourceType {get;}

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


Uri Property

Aspose.Words

ResourceLoadingArgs.Uri Property

URI of the resource which is used for downloading if ResourceLoading returns Default.

Initially it's set to absolute URI of the resource, but user can redefine it to any value.

[Visual Basic]
Public Property Uri As String
[C#]
public string Uri {get; set;}

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


ResourceLoadingArgs Methods

The methods of the ResourceLoadingArgs class are listed below. For a complete list of ResourceLoadingArgs class members, see the ResourceLoadingArgs Members topic.

Public Instance Methods

SetData Sets user provided data of the resource which is used if ResourceLoading returns UserProvided.

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


ResourceLoadingArgs.SetData Method

Sets user provided data of the resource which is used if ResourceLoading returns UserProvided.

[Visual Basic]
Public Sub SetData( _
ByVal data As Byte() _
)
[C#]
public void SetData(
byte[] data
);

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


ResourceType Enumeration

Type of loaded resource.

[Visual Basic]
Public Enum ResourceType
[C#]
public enum ResourceType

Example

Shows how to process inserted resources differently.

[C#]

public void ResourceLoadingCallback()
{
    Document doc = new Document();

    // Images belong to NodeType.Shape
    // There are none in a blank document
    Assert.AreEqual(0, doc.GetChildNodes(NodeType.Shape, true).Count);

    // Enable our custom image loading
    doc.ResourceLoadingCallback = new ImageNameHandler();

    DocumentBuilder builder = new DocumentBuilder(doc);

    // We usually insert images as a uri or byte array, but there are many other possibilities with ResourceLoadingCallback
    // In this case we are referencing images with simple names and keep the image fetching logic somewhere else
    builder.InsertImage("Google Logo");
    builder.InsertImage("Aspose Logo");
    builder.InsertImage("My Watermark");

    Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

    doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
}

private class ImageNameHandler : IResourceLoadingCallback
{
    public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
    {
        if (args.ResourceType == ResourceType.Image)
        {
            // builder.InsertImage expects a uri so inputs like "Google Logo" would normally trigger a FileNotFoundException
            // We can still process those inputs and find an image any way we like, as long as an image byte array is passed to args.SetData()
            if (args.OriginalUri == "Google Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes =
                        webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
                    args.SetData(imageBytes);
                    // We need this return statement any time a resource is loaded in a custom manner
                    return ResourceLoadingAction.UserProvided;
                }
            }

            if (args.OriginalUri == "Aspose Logo")
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = webClient.DownloadData(AsposeLogoUrl);
                    args.SetData(imageBytes);
                    return ResourceLoadingAction.UserProvided;
                }
            }

            // We can find and add an image any way we like, as long as args.SetData() is called with some image byte array as a parameter
            if (args.OriginalUri == "My Watermark")
            {
                System.Drawing.Image watermark = System.Drawing.Image.FromFile(MyDir + "Images/Watermark.png");

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                byte[] imageBytes = (byte[]) converter.ConvertTo(watermark, typeof(byte[]));
                args.SetData(imageBytes);

                return ResourceLoadingAction.UserProvided;
            }
        }

        // All other resources such as documents, CSS stylesheets and images passed as uris are handled as they were normally
        return ResourceLoadingAction.Default;
    }
}

Members

Member Name | Description | Value
Image | Image. | 0
CssStyleSheet | Css style sheet. | 1
Document | Document. | 2

Requirements

Namespace: Aspose.Words.Loading

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Loading Namespace


Aspose.Words.MailMerging

Aspose.Words

Aspose.Words.MailMerging Namespace

The Aspose.Words.MailMerging namespace contains classes of the "original" mail merge reporting engine.

This reporting engine requires the document to be marked up with Microsoft Word mail merge fields, but supports more functionality than Microsoft Word's mail merge.

The engine allows to quickly and easily populate a report template with data from various sources such as DataTable, DataSet, DataView, IDataReader or an array of values.

The MailMerge object which provides access to the reporting functionality is available via the Document.MailMerge property.

For the newer and more advanced reporting engine based on the LINQ method syntax see Aspose.Words.Reporting.

Namespace hierarchy

Classes

Class | Description
FieldMergingArgs | Provides data for the MergeField event.
FieldMergingArgsBase | Base class for FieldMergingArgs and ImageFieldMergingArgs.
ImageFieldMergingArgs | Provides data for the ImageFieldMerging event.
MailMerge | Represents the mail merge functionality.
MailMergeRegionInfo | Contains information about a mail merge region.
MappedDataFieldCollection | Allows to automatically map between names of fields in your data source and names of mail merge fields in the document.

Interfaces

Interface | Description
IFieldMergingCallback | Implement this interface if you want to control how data is inserted into merge fields during a mail merge operation.
IMailMergeCallback | Implement this interface if you want to receive notifications while mail merge is performed.
IMailMergeDataSource | Implement this interface to allow mail merge from a custom data source, such as a list of objects. Master-detail data is also supported.
IMailMergeDataSourceRoot | Implement this interface to allow mail merge from a custom data source with master-detail data.

Enumerations

Enumeration | Description
MailMergeCleanupOptions | Specifies options that determine what items are removed during mail merge.
MailMergeRtlCleanupMode | Specifies how to handle Right-To-Left attributes of mail merge result text runs.


FieldMergingArgs Class

Provides data for the MergeField event.

For a list of all members of this type, see FieldMergingArgs Members.

System.Object
Aspose.Words.MailMerging.FieldMergingArgsBase
Aspose.Words.MailMerging.FieldMergingArgs

[Visual Basic]
Public Class FieldMergingArgs
Inherits FieldMergingArgsBase
[C#]
public class FieldMergingArgs : FieldMergingArgsBase

Remarks

The MergeField event occurs during mail merge when a simple mail merge field is encountered in the document. You can respond to this event to return text for the mail merge engine to insert into the document.

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMergingArgs Members | Aspose.Words.MailMerging Namespace | IFieldMergingCallback


FieldMergingArgs Members

FieldMergingArgs overview

Public Instance Properties

Document (inherited from FieldMergingArgsBase) | Returns the Document object for which the mail merge is performed.
DocumentFieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field as specified in the document.
Field (inherited from FieldMergingArgsBase) | Gets the object that represents the current merge field.
FieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field in the data source.
FieldValue (inherited from FieldMergingArgsBase) | Gets the value of the field from the data source.
RecordIndex (inherited from FieldMergingArgsBase) | Gets the zero based index of the record that is being merged.
TableName (inherited from FieldMergingArgsBase) | Gets the name of the data table for the current merge operation or empty string if the name is not available.
Text | Gets or sets the text that will be inserted into the document for the current merge field.

See Also

FieldMergingArgs Class | Aspose.Words.MailMerging Namespace | IFieldMergingCallback


FieldMergingArgs Properties

The properties of the FieldMergingArgs class are listed below. For a complete list of FieldMergingArgs class members, see the FieldMergingArgs Members topic.

Public Instance Properties

Document (inherited from FieldMergingArgsBase) | Returns the Document object for which the mail merge is performed.
DocumentFieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field as specified in the document.
Field (inherited from FieldMergingArgsBase) | Gets the object that represents the current merge field.
FieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field in the data source.
FieldValue (inherited from FieldMergingArgsBase) | Gets the value of the field from the data source.
RecordIndex (inherited from FieldMergingArgsBase) | Gets the zero based index of the record that is being merged.
TableName (inherited from FieldMergingArgsBase) | Gets the name of the data table for the current merge operation or empty string if the name is not available.
Text | Gets or sets the text that will be inserted into the document for the current merge field.

See Also

FieldMergingArgs Class | Aspose.Words.MailMerging Namespace | IFieldMergingCallback


Text Property

Aspose.Words

FieldMergingArgs.Text Property

Gets or sets the text that will be inserted into the document for the current merge field.

[Visual Basic]
Public Property Text As String
[C#]
public string Text {get; set;}

Remarks

When your event handler is called, this property is set to null.

If you leave Text as null, the mail merge engine will insert FieldValue in place of the merge field.

If you set Text to any string (including empty), the string will be inserted into the document in place of the merge field.

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

FieldMergingArgs Class | Aspose.Words.MailMerging Namespace


FieldMergingArgsBase Class

Base class for FieldMergingArgs and ImageFieldMergingArgs.

For a list of all members of this type, see FieldMergingArgsBase Members.

System.Object
Aspose.Words.MailMerging.FieldMergingArgsBase
Aspose.Words.MailMerging.FieldMergingArgs
Aspose.Words.MailMerging.ImageFieldMergingArgs

[Visual Basic]
MustInherit Public Class FieldMergingArgsBase
[C#]
public abstract class FieldMergingArgsBase

Remarks

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FieldMergingArgsBase Members | Aspose.Words.MailMerging Namespace | FieldMergingArgs | ImageFieldMergingArgs


FieldMergingArgsBase Members

FieldMergingArgsBase overview

Public Instance Properties

Document | Returns the Document object for which the mail merge is performed.
DocumentFieldName | Gets the name of the merge field as specified in the document.
Field | Gets the object that represents the current merge field.
FieldName | Gets the name of the merge field in the data source.
FieldValue | Gets the value of the field from the data source.
RecordIndex | Gets the zero based index of the record that is being merged.
TableName | Gets the name of the data table for the current merge operation or empty string if the name is not available.

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace | FieldMergingArgs | ImageFieldMergingArgs


FieldMergingArgsBase Properties

The properties of the FieldMergingArgsBase class are listed below. For a complete list of FieldMergingArgsBase class members, see the FieldMergingArgsBase Members topic.

Public Instance Properties

Document | Returns the Document object for which the mail merge is performed.
DocumentFieldName | Gets the name of the merge field as specified in the document.
Field | Gets the object that represents the current merge field.
FieldName | Gets the name of the merge field in the data source.
FieldValue | Gets the value of the field from the data source.
RecordIndex | Gets the zero based index of the record that is being merged.
TableName | Gets the name of the data table for the current merge operation or empty string if the name is not available.

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace | FieldMergingArgs | ImageFieldMergingArgs


Document Property

Aspose.Words

FieldMergingArgsBase.Document Property

Returns the Document object for which the mail merge is performed.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


DocumentFieldName Property

Aspose.Words

FieldMergingArgsBase.DocumentFieldName Property

Gets the name of the merge field as specified in the document.

[Visual Basic]
Public ReadOnly Property DocumentFieldName As String
[C#]
public string DocumentFieldName {get;}

Remarks

If you have a mapping from a document field name to a different data source field name, then this is the original field name as specified in the document.

If you specified a field name prefix, for example "Image:MyFieldName" in the document, then DocumentFieldName returns field name without the prefix, that is "MyFieldName".

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


Field Property

Aspose.Words

FieldMergingArgsBase.Field Property

Gets the object that represents the current merge field.

[Visual Basic]
Public ReadOnly Property Field As FieldMergeField
[C#]
public FieldMergeField Field {get;}

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


FieldName Property

Aspose.Words

FieldMergingArgsBase.FieldName Property

Gets the name of the merge field in the data source.

[Visual Basic]
Public ReadOnly Property FieldName As String
[C#]
public string FieldName {get;}

Remarks

If you have a mapping from a document field name to a different data source field name, then this is the mapped field name.

If you specified a field name prefix, for example "Image:MyFieldName" in the document, then FieldName returns field name without the prefix, that is "MyFieldName".

Example

Shows how to insert checkbox form fields into a document during mail merge.

[C#]

// File 'MailMerge.InsertCheckBox.doc' is a template
    // containing the table with the following fields in it:
    // <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
    Document doc = new Document(MyDir + "MailMerge.InsertCheckBox.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertCheckBox();

    // Execute mail merge with regions.
    DataTable dataTable = GetStudentCourseDataTable();
    doc.MailMerge.ExecuteWithRegions(dataTable);

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertCheckBox.doc");
}

private class HandleMergeFieldInsertCheckBox : IFieldMergingCallback
{
    /// <summary>
    /// This is called for each merge field in the document
    /// when Document.MailMerge.ExecuteWithRegions is called.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        if (args.DocumentFieldName.Equals("CourseName"))
        {
            // The name of the table that we are merging can be found here
            Assert.AreEqual("StudentCourse", args.TableName);

            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.FieldName);
            builder.InsertCheckBox(args.DocumentFieldName + mCheckBoxCount, false, 0);

            // Get the actual value of the field
            string fieldValue = args.FieldValue.ToString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.AreEqual(Char.GetNumericValue(fieldValue[7]), args.RecordIndex);

            builder.Write(fieldValue);
            mCheckBoxCount++;
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// Counter for CheckBox name generation
    /// </summary>
    private int mCheckBoxCount;
}

/// <summary>
/// Create DataTable and fill it with data.
/// In real life this DataTable should be filled from a database.
/// </summary>
private static DataTable GetStudentCourseDataTable()
{
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.Columns.Add("CourseName");
    for (int i = 0; i < 10; i++)
    {
        DataRow datarow = dataTable.NewRow();
        dataTable.Rows.Add(datarow);
        datarow[0] = "Course " + i;
    }

    return dataTable;
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


FieldValue Property

Aspose.Words

FieldMergingArgsBase.FieldValue Property

Gets the value of the field from the data source.

[Visual Basic]
Public ReadOnly Property FieldValue As Object
[C#]
public object FieldValue {get;}

Remarks

This property contains a value that has just been selected from your data source for this field by the mail merge engine.

Example

Shows how to mail merge HTML data into a document.

[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


RecordIndex Property

Aspose.Words

FieldMergingArgsBase.RecordIndex Property

Gets the zero based index of the record that is being merged.

[Visual Basic]
Public ReadOnly Property RecordIndex As Integer
[C#]
public int RecordIndex {get;}

Example

Shows how to insert checkbox form fields into a document during mail merge.

[C#]

// File 'MailMerge.InsertCheckBox.doc' is a template
    // containing the table with the following fields in it:
    // <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
    Document doc = new Document(MyDir + "MailMerge.InsertCheckBox.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertCheckBox();

    // Execute mail merge with regions.
    DataTable dataTable = GetStudentCourseDataTable();
    doc.MailMerge.ExecuteWithRegions(dataTable);

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertCheckBox.doc");
}

private class HandleMergeFieldInsertCheckBox : IFieldMergingCallback
{
    /// <summary>
    /// This is called for each merge field in the document
    /// when Document.MailMerge.ExecuteWithRegions is called.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        if (args.DocumentFieldName.Equals("CourseName"))
        {
            // The name of the table that we are merging can be found here
            Assert.AreEqual("StudentCourse", args.TableName);

            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.FieldName);
            builder.InsertCheckBox(args.DocumentFieldName + mCheckBoxCount, false, 0);

            // Get the actual value of the field
            string fieldValue = args.FieldValue.ToString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.AreEqual(Char.GetNumericValue(fieldValue[7]), args.RecordIndex);

            builder.Write(fieldValue);
            mCheckBoxCount++;
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// Counter for CheckBox name generation
    /// </summary>
    private int mCheckBoxCount;
}

/// <summary>
/// Create DataTable and fill it with data.
/// In real life this DataTable should be filled from a database.
/// </summary>
private static DataTable GetStudentCourseDataTable()
{
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.Columns.Add("CourseName");
    for (int i = 0; i < 10; i++)
    {
        DataRow datarow = dataTable.NewRow();
        dataTable.Rows.Add(datarow);
        datarow[0] = "Course " + i;
    }

    return dataTable;
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


TableName Property

Aspose.Words

FieldMergingArgsBase.TableName Property

Gets the name of the data table for the current merge operation or empty string if the name is not available.

[Visual Basic]
Public ReadOnly Property TableName As String
[C#]
public string TableName {get;}

Example

Shows how to insert checkbox form fields into a document during mail merge.

[C#]

// File 'MailMerge.InsertCheckBox.doc' is a template
    // containing the table with the following fields in it:
    // <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
    Document doc = new Document(MyDir + "MailMerge.InsertCheckBox.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertCheckBox();

    // Execute mail merge with regions.
    DataTable dataTable = GetStudentCourseDataTable();
    doc.MailMerge.ExecuteWithRegions(dataTable);

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertCheckBox.doc");
}

private class HandleMergeFieldInsertCheckBox : IFieldMergingCallback
{
    /// <summary>
    /// This is called for each merge field in the document
    /// when Document.MailMerge.ExecuteWithRegions is called.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        if (args.DocumentFieldName.Equals("CourseName"))
        {
            // The name of the table that we are merging can be found here
            Assert.AreEqual("StudentCourse", args.TableName);

            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.FieldName);
            builder.InsertCheckBox(args.DocumentFieldName + mCheckBoxCount, false, 0);

            // Get the actual value of the field
            string fieldValue = args.FieldValue.ToString();

            // In this case, for every record index 'n', the corresponding field value is "Course n"
            Assert.AreEqual(Char.GetNumericValue(fieldValue[7]), args.RecordIndex);

            builder.Write(fieldValue);
            mCheckBoxCount++;
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// Counter for CheckBox name generation
    /// </summary>
    private int mCheckBoxCount;
}

/// <summary>
/// Create DataTable and fill it with data.
/// In real life this DataTable should be filled from a database.
/// </summary>
private static DataTable GetStudentCourseDataTable()
{
    DataTable dataTable = new DataTable("StudentCourse");
    dataTable.Columns.Add("CourseName");
    for (int i = 0; i < 10; i++)
    {
        DataRow datarow = dataTable.NewRow();
        dataTable.Rows.Add(datarow);
        datarow[0] = "Course " + i;
    }

    return dataTable;
}

See Also

FieldMergingArgsBase Class | Aspose.Words.MailMerging Namespace


IFieldMergingCallback Interface

Implement this interface if you want to control how data is inserted into merge fields during a mail merge operation.

For a list of all members of this type, see IFieldMergingCallback Members.

[Visual Basic]
Public Interface IFieldMergingCallback
[C#]
public interface IFieldMergingCallback

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}
Shows how to mail merge HTML data into a document.
[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IFieldMergingCallback Members | Aspose.Words.MailMerging Namespace


IFieldMergingCallback Members

IFieldMergingCallback overview

Public Instance Methods

FieldMerging | Called when the Aspose.Words mail merge engine is about to insert data into a merge field in the document.
ImageFieldMerging | Called when the Aspose.Words mail merge engine is about to insert an image into a merge field.

See Also

IFieldMergingCallback Interface | Aspose.Words.MailMerging Namespace


IFieldMergingCallback Methods

The methods of the IFieldMergingCallback interface are listed below. For a complete list of IFieldMergingCallback interface members, see the IFieldMergingCallback Members topic.

Public Instance Methods

FieldMerging | Called when the Aspose.Words mail merge engine is about to insert data into a merge field in the document.
ImageFieldMerging | Called when the Aspose.Words mail merge engine is about to insert an image into a merge field.

See Also

IFieldMergingCallback Interface | Aspose.Words.MailMerging Namespace


IFieldMergingCallback.FieldMerging Method

Called when the Aspose.Words mail merge engine is about to insert data into a merge field in the document.

[Visual Basic]
Sub FieldMerging( _
ByVal args As FieldMergingArgs _
)
[C#]
void FieldMerging(
FieldMergingArgs args
);

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}
Shows how to mail merge HTML data into a document.
[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

IFieldMergingCallback Interface | Aspose.Words.MailMerging Namespace


IFieldMergingCallback.ImageFieldMerging Method

Called when the Aspose.Words mail merge engine is about to insert an image into a merge field.

[Visual Basic]
Sub ImageFieldMerging( _
ByVal args As ImageFieldMergingArgs _
)
[C#]
void ImageFieldMerging(
ImageFieldMergingArgs args
);

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}

See Also

IFieldMergingCallback Interface | Aspose.Words.MailMerging Namespace


ImageFieldMergingArgs Class

Provides data for the ImageFieldMerging event.

For a list of all members of this type, see ImageFieldMergingArgs Members.

System.Object
Aspose.Words.MailMerging.FieldMergingArgsBase
Aspose.Words.MailMerging.ImageFieldMergingArgs

[Visual Basic]
Public Class ImageFieldMergingArgs
Inherits FieldMergingArgsBase
[C#]
public class ImageFieldMergingArgs : FieldMergingArgsBase

Remarks

This event occurs during mail merge when an image mail merge field is encountered in the document. You can respond to this event to return a file name, stream, or an Image object to the mail merge engine so it is inserted into the document.

There are three properties available ImageFileName, ImageStream and Image to specify where the image must be taken from. Set only one of these properties.

To insert an image mail merge field into a document in Word, select Insert/Field command, then select MergeField and type Image:MyFieldName.

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}
Shows how to set the dimensions of merged images.
[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ImageFieldMergingArgs Members | Aspose.Words.MailMerging Namespace | IFieldMergingCallback


ImageFieldMergingArgs Members

ImageFieldMergingArgs overview

Public Instance Properties

Document (inherited from FieldMergingArgsBase) | Returns the Document object for which the mail merge is performed.
DocumentFieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field as specified in the document.
Field (inherited from FieldMergingArgsBase) | Gets the object that represents the current merge field.
FieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field in the data source.
FieldValue (inherited from FieldMergingArgsBase) | Gets the value of the field from the data source.
Image | Specifies the image that the mail merge engine must insert into the document.
ImageFileName | Sets the file name of the image that the mail merge engine must insert into the document.
ImageHeight | Specifies the image height for the image to insert into the document.
ImageStream | Specifies the stream for the mail merge engine to read an image from.
ImageWidth | Specifies the image width for the image to insert into the document.
RecordIndex (inherited from FieldMergingArgsBase) | Gets the zero based index of the record that is being merged.
TableName (inherited from FieldMergingArgsBase) | Gets the name of the data table for the current merge operation or empty string if the name is not available.

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace | IFieldMergingCallback


ImageFieldMergingArgs Properties

The properties of the ImageFieldMergingArgs class are listed below. For a complete list of ImageFieldMergingArgs class members, see the ImageFieldMergingArgs Members topic.

Public Instance Properties

Document (inherited from FieldMergingArgsBase) | Returns the Document object for which the mail merge is performed.
DocumentFieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field as specified in the document.
Field (inherited from FieldMergingArgsBase) | Gets the object that represents the current merge field.
FieldName (inherited from FieldMergingArgsBase) | Gets the name of the merge field in the data source.
FieldValue (inherited from FieldMergingArgsBase) | Gets the value of the field from the data source.
Image | Specifies the image that the mail merge engine must insert into the document.
ImageFileName | Sets the file name of the image that the mail merge engine must insert into the document.
ImageHeight | Specifies the image height for the image to insert into the document.
ImageStream | Specifies the stream for the mail merge engine to read an image from.
ImageWidth | Specifies the image width for the image to insert into the document.
RecordIndex (inherited from FieldMergingArgsBase) | Gets the zero based index of the record that is being merged.
TableName (inherited from FieldMergingArgsBase) | Gets the name of the data table for the current merge operation or empty string if the name is not available.

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace | IFieldMergingCallback


Image Property

Aspose.Words

ImageFieldMergingArgs.Image Property

Specifies the image that the mail merge engine must insert into the document.

[Visual Basic]
Public Property Image As Image
[C#]
public Image Image {get; set;}

Example

Shows how to set which images to merge during the mail merge.

[C#]

public void MergeFieldImages()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // When we merge images, our data table will normally have the full e. of the images we wish to merge
    // If this is cumbersome, we can move image filename logic to another place and populate the data table with just shorthands for images
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            "Aspose logo",
            ".Net logo",
            "Watermark"
        });

    // A custom merging callback will contain filenames that our shorthands will refer to
    doc.MailMerge.FieldMergingCallback = new ImageFilenameCallback();
    doc.MailMerge.Execute(dataTable);

    doc.Save(ArtifactsDir + "Field.MergeFieldImages.docx");
}

/// <summary>
/// Image merging callback that pairs image shorthand names with filenames
/// </summary>
private class ImageFilenameCallback : IFieldMergingCallback
{
    public ImageFilenameCallback()
    {
        imageFilenames = new Dictionary<string, string>();
        imageFilenames.Add("Aspose logo", ImageDir + "Aspose.Words.gif");
        imageFilenames.Add(".Net logo", ImageDir + "dotnet-logo.png");
        imageFilenames.Add("Watermark", ImageDir + "Watermark.png");
    }

    void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        if (imageFilenames.ContainsKey(e.FieldValue.ToString()))
        {
            #if !(NETSTANDARD2_0 || __MOBILE__ || MAC)
            e.Image = Image.FromFile(imageFilenames[e.FieldValue.ToString()]);
            #else
            e.Image = SKBitmap.Decode(imageFilenames[e.FieldValue.ToString()]);
            e.ImageFileName = imageFilenames[e.FieldValue.ToString()];
            #endif
        }

        Assert.NotNull(e.Image);
    }

    private readonly Dictionary<string, string> imageFilenames;
}

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace


ImageFileName Property

Aspose.Words

ImageFieldMergingArgs.ImageFileName Property

Sets the file name of the image that the mail merge engine must insert into the document.

[Visual Basic]
Public Property ImageFileName As String
[C#]
public string ImageFileName {get; set;}

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace


ImageHeight Property

Aspose.Words

ImageFieldMergingArgs.ImageHeight Property

Specifies the image height for the image to insert into the document.

[Visual Basic]
Public Property ImageHeight As MergeFieldImageDimension
[C#]
public MergeFieldImageDimension ImageHeight {get; set;}

Remarks

The value of this property initially comes from the corresponding MERGEFIELD's code, contained in the template document. To override the initial value, you should assign an instance of MergeFieldImageDimension class to this property or set the properties for the instance of MergeFieldImageDimension class, returned by this property.

To indicate that the original value of the image height should be applied, you should assign the null value to this property or set the Value property for the instance of MergeFieldImageDimension class, returned by this property, to a negative value.

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace | MergeFieldImageDimension | MergeFieldImageDimensionUnit


ImageStream Property

Aspose.Words

ImageFieldMergingArgs.ImageStream Property

Specifies the stream for the mail merge engine to read an image from.

[Visual Basic]
Public Property ImageStream As Stream
[C#]
public Stream ImageStream {get; set;}

Remarks

Aspose.Words closes this stream after it merges the image into the document.

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace


ImageWidth Property

Aspose.Words

ImageFieldMergingArgs.ImageWidth Property

Specifies the image width for the image to insert into the document.

[Visual Basic]
Public Property ImageWidth As MergeFieldImageDimension
[C#]
public MergeFieldImageDimension ImageWidth {get; set;}

Remarks

The value of this property initially comes from the corresponding MERGEFIELD's code, contained in the template document. To override the initial value, you should assign an instance of MergeFieldImageDimension class to this property or set the properties for the instance of MergeFieldImageDimension class, returned by this property.

To indicate that the original value of the image width should be applied, you should assign the null value to this property or set the Value property for the instance of MergeFieldImageDimension class, returned by this property, to a negative value.

Example

Shows how to set the dimensions of merged images.

[C#]

public void MergeFieldImageDimension()
{
    Document doc = new Document();

    // Insert a merge field where images will be placed during the mail merge
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.InsertField("MERGEFIELD Image:ImageColumn");

    // Create a data table for the mail merge
    // The name of the column that contains our image filenames needs to match the name of our merge field
    System.Data.DataTable dataTable = CreateDataTable("Images", "ImageColumn",
        new string[]
        {
            ImageDir + "Aspose.Words.gif",
            ImageDir + "Watermark.png",
            ImageDir + "dotnet-logo.png"
        });

    doc.MailMerge.FieldMergingCallback = new MergedImageResizer(450, 200, MergeFieldImageDimensionUnit.Point);
    doc.MailMerge.Execute(dataTable);

    doc.UpdateFields();
    doc.Save(ArtifactsDir + "Field.MergeFieldImageDimension.docx");
}

/// <summary>
/// Creates a data table with a single column
/// </summary>
private System.Data.DataTable CreateDataTable(string tableName, string columnName, string[] columnContents)
{
    System.Data.DataTable dataTable = new System.Data.DataTable(tableName);
    dataTable.Columns.Add(new System.Data.DataColumn(columnName));

    foreach (string s in columnContents)
    {
        System.Data.DataRow dataRow = dataTable.NewRow();
        dataRow[0] = s;
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

/// <summary>
/// Sets the size of all mail merged images to one defined width and height
/// </summary>
private class MergedImageResizer : IFieldMergingCallback
{
    public MergedImageResizer(double imageWidth, double imageHeight, MergeFieldImageDimensionUnit unit)
    {
        mImageWidth = imageWidth;
        mImageHeight = imageHeight;
        mUnit = unit;
    }

    public void FieldMerging(FieldMergingArgs e)
    {
        throw new NotImplementedException();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        args.ImageFileName = args.FieldValue.ToString();
        args.ImageWidth = new MergeFieldImageDimension(mImageWidth, mUnit);
        args.ImageHeight = new MergeFieldImageDimension(mImageHeight, mUnit);

        Assert.AreEqual(mImageWidth, args.ImageWidth.Value);
        Assert.AreEqual(mUnit, args.ImageWidth.Unit);
        Assert.AreEqual(mImageHeight, args.ImageHeight.Value);
        Assert.AreEqual(mUnit, args.ImageHeight.Unit);
    }

    private readonly double mImageWidth;
    private readonly double mImageHeight;
    private readonly MergeFieldImageDimensionUnit mUnit;
}

See Also

ImageFieldMergingArgs Class | Aspose.Words.MailMerging Namespace | MergeFieldImageDimension | MergeFieldImageDimensionUnit


IMailMergeCallback Interface

Implement this interface if you want to receive notifications while mail merge is performed.

For a list of all members of this type, see IMailMergeCallback Members.

[Visual Basic]
Public Interface IMailMergeCallback
[C#]
public interface IMailMergeCallback

Example

Shows how to define custom logic for handling events during mail merge.

[C#]

Document document = new Document();
    document.MailMerge.UseNonMergeFields = true;

    MailMergeCallbackStub mailMergeCallbackStub = new MailMergeCallbackStub();
    document.MailMerge.MailMergeCallback = mailMergeCallbackStub;

    document.MailMerge.Execute(new String[0], new object[0]);

    Assert.AreEqual(1, mailMergeCallbackStub.TagsReplacedCounter);
}

private class MailMergeCallbackStub : IMailMergeCallback
{
    public void TagsReplaced()
    {
        TagsReplacedCounter++;
    }

    public int TagsReplacedCounter { get; private set; }
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IMailMergeCallback Members | Aspose.Words.MailMerging Namespace


IMailMergeCallback Members

IMailMergeCallback overview

Public Instance Methods

TagsReplaced Called when "mustache" text tags are replaced with MERGEFIELD fields.

See Also

IMailMergeCallback Interface | Aspose.Words.MailMerging Namespace


IMailMergeCallback Methods

The methods of the IMailMergeCallback interface are listed below. For a complete list of IMailMergeCallback interface members, see the IMailMergeCallback Members topic.

Public Instance Methods

TagsReplaced Called when "mustache" text tags are replaced with MERGEFIELD fields.

See Also

IMailMergeCallback Interface | Aspose.Words.MailMerging Namespace


IMailMergeCallback.TagsReplaced Method

Called when "mustache" text tags are replaced with MERGEFIELD fields.

[Visual Basic]
Sub TagsReplaced()
[C#]
void TagsReplaced();

Example

Shows how to define custom logic for handling events during mail merge.

[C#]

Document document = new Document();
    document.MailMerge.UseNonMergeFields = true;

    MailMergeCallbackStub mailMergeCallbackStub = new MailMergeCallbackStub();
    document.MailMerge.MailMergeCallback = mailMergeCallbackStub;

    document.MailMerge.Execute(new String[0], new object[0]);

    Assert.AreEqual(1, mailMergeCallbackStub.TagsReplacedCounter);
}

private class MailMergeCallbackStub : IMailMergeCallback
{
    public void TagsReplaced()
    {
        TagsReplacedCounter++;
    }

    public int TagsReplacedCounter { get; private set; }
}

See Also

IMailMergeCallback Interface | Aspose.Words.MailMerging Namespace | UseNonMergeFields


IMailMergeDataSource Interface

Implement this interface to allow mail merge from a custom data source, such as a list of objects. Master-detail data is also supported.

For a list of all members of this type, see IMailMergeDataSource Members.

[Visual Basic]
Public Interface IMailMergeDataSource
[C#]
public interface IMailMergeDataSource

Remarks

When a data source is created, it should be initialized to point to BOF (before the first record). The Aspose.Words mail merge engine will invoke MoveNext to advance to next record and then invoke GetValue for every merge field it encounters in the document or the current mail merge region.

Example

Performs mail merge from a custom data source.

[C#]

public void MailMergeCustomDataSource()
{
    // Create some data that we will use in the mail merge.
    CustomerList customers = new CustomerList();
    customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
    customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));

    // Open the template document.
    Document doc = new Document(MyDir + "MailMerge.CustomDataSource.doc");

    // To be able to mail merge from your own data source, it must be wrapped
    // into an object that implements the IMailMergeDataSource interface.
    CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);

    // Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource);

    doc.Save(ArtifactsDir + "MailMerge.CustomDataSource.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        FullName = aFullName;
        Address = anAddress;
    }

    public string FullName { get; set; }
    public string Address { get; set; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
public class CustomerList : ArrayList
{
    public new Customer this[int index]
    {
        get { return (Customer) base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// A custom mail merge data source that you implement to allow Aspose.Words
/// to mail merge data from your Customer objects into Microsoft Word documents.
/// </summary>
public class CustomerMailMergeDataSource : IMailMergeDataSource
{
    public CustomerMailMergeDataSource(CustomerList customers)
    {
        mCustomers = customers;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Customer"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mCustomers[mRecordIndex].FullName;
                return true;
            case "Address":
                fieldValue = mCustomers[mRecordIndex].Address;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        return null;
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mCustomers.Count); }
    }

    private readonly CustomerList mCustomers;
    private int mRecordIndex;
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IMailMergeDataSource Members | Aspose.Words.MailMerging Namespace | MailMerge


IMailMergeDataSource Members

IMailMergeDataSource overview

Public Instance Properties

TableName Returns the name of the data source.

Public Instance Methods

GetChildDataSource | The Aspose.Words mail merge engine invokes this method when it encounters a beginning of a nested mail merge region.
GetValue |
MoveNext | Advances to the next record in the data source.

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace | MailMerge


IMailMergeDataSource Properties

The properties of the IMailMergeDataSource interface are listed below. For a complete list of IMailMergeDataSource interface members, see the IMailMergeDataSource Members topic.

Public Instance Properties

TableName Returns the name of the data source.

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace | MailMerge


TableName Property

Aspose.Words

IMailMergeDataSource.TableName Property

Returns the name of the data source.

[Visual Basic]
Property TableName As String
[C#]
string TableName {get;}

Remarks

If you are implementing IMailMergeDataSource, return the name of the data source from this property.

Aspose.Words uses this name to match against the mail merge region name specified in the template document. The comparison between the data source name and the mail merge region name is not case sensitive.

Example

Performs mail merge from a custom data source.

[C#]

public void MailMergeCustomDataSource()
{
    // Create some data that we will use in the mail merge.
    CustomerList customers = new CustomerList();
    customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
    customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));

    // Open the template document.
    Document doc = new Document(MyDir + "MailMerge.CustomDataSource.doc");

    // To be able to mail merge from your own data source, it must be wrapped
    // into an object that implements the IMailMergeDataSource interface.
    CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);

    // Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource);

    doc.Save(ArtifactsDir + "MailMerge.CustomDataSource.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        FullName = aFullName;
        Address = anAddress;
    }

    public string FullName { get; set; }
    public string Address { get; set; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
public class CustomerList : ArrayList
{
    public new Customer this[int index]
    {
        get { return (Customer) base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// A custom mail merge data source that you implement to allow Aspose.Words
/// to mail merge data from your Customer objects into Microsoft Word documents.
/// </summary>
public class CustomerMailMergeDataSource : IMailMergeDataSource
{
    public CustomerMailMergeDataSource(CustomerList customers)
    {
        mCustomers = customers;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Customer"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mCustomers[mRecordIndex].FullName;
                return true;
            case "Address":
                fieldValue = mCustomers[mRecordIndex].Address;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        return null;
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mCustomers.Count); }
    }

    private readonly CustomerList mCustomers;
    private int mRecordIndex;
}

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace


IMailMergeDataSource Methods

The methods of the IMailMergeDataSource interface are listed below. For a complete list of IMailMergeDataSource interface members, see the IMailMergeDataSource Members topic.

Public Instance Methods

GetChildDataSource | The Aspose.Words mail merge engine invokes this method when it encounters a beginning of a nested mail merge region.
GetValue |
MoveNext | Advances to the next record in the data source.

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace | MailMerge


IMailMergeDataSource.GetChildDataSource Method

The Aspose.Words mail merge engine invokes this method when it encounters a beginning of a nested mail merge region.

[Visual Basic]
Function GetChildDataSource( _
ByVal tableName As String _
) As IMailMergeDataSource
[C#]
IMailMergeDataSource GetChildDataSource(
string tableName
);

Parameters

tableName
The name of the mail merge region as specified in the template document. Case-insensitive.

Return Value

A data source object that will provide access to the data records of the specified table.

Remarks

When the Aspose.Words mail merge engines populates a mail merge region with data and encounters the beginning of a nested mail merge region in the form of MERGEFIELD TableStart:TableName, it invokes GetChildDataSource on the current data source object. Your implementation needs to return a new data source object that will provide access to the child records of the current parent record. Aspose.Words will use the returned data source to populate the nested mail merge region.

Below are the rules that the implementation of GetChildDataSource must follow.

If the table that is represented by this data source object has a related child (detail) table with the specified name, then your implementation needs to return a new IMailMergeDataSource object that will provide access to the child records of the current record. An example of this is Orders / OrderDetails relationship. Let's assume that the current IMailMergeDataSource object represents the Orders table and it has a current order record. Next, Aspose.Words encounters "MERGEFIELD TableStart:OrderDetails" in the document and invokes GetChildDataSource. You need to create and return a IMailMergeDataSource object that will allow Aspose.Words to access the OrderDetails record for the current order.

If this data source object does not have a relation to the table with the specified name, then you need to return a IMailMergeDataSource object that will provide access to all records of the specified table.

If a table with the specified name does not exist, your implementation should return null.

Example

Performs mail merge from a custom data source.

[C#]

public void MailMergeCustomDataSource()
{
    // Create some data that we will use in the mail merge.
    CustomerList customers = new CustomerList();
    customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
    customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));

    // Open the template document.
    Document doc = new Document(MyDir + "MailMerge.CustomDataSource.doc");

    // To be able to mail merge from your own data source, it must be wrapped
    // into an object that implements the IMailMergeDataSource interface.
    CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);

    // Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource);

    doc.Save(ArtifactsDir + "MailMerge.CustomDataSource.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        FullName = aFullName;
        Address = anAddress;
    }

    public string FullName { get; set; }
    public string Address { get; set; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
public class CustomerList : ArrayList
{
    public new Customer this[int index]
    {
        get { return (Customer) base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// A custom mail merge data source that you implement to allow Aspose.Words
/// to mail merge data from your Customer objects into Microsoft Word documents.
/// </summary>
public class CustomerMailMergeDataSource : IMailMergeDataSource
{
    public CustomerMailMergeDataSource(CustomerList customers)
    {
        mCustomers = customers;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Customer"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mCustomers[mRecordIndex].FullName;
                return true;
            case "Address":
                fieldValue = mCustomers[mRecordIndex].Address;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        return null;
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mCustomers.Count); }
    }

    private readonly CustomerList mCustomers;
    private int mRecordIndex;
}

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace


IMailMergeDataSource.GetValue Method

[Visual Basic]
Function GetValue( _
ByVal fieldName As String, _
ByRef fieldValue As Object _
) As Boolean
[C#]
bool GetValue(
string fieldName,
out object fieldValue
);

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace


IMailMergeDataSource.MoveNext Method

Advances to the next record in the data source.

[Visual Basic]
Function MoveNext() As Boolean
[C#]
bool MoveNext();

Return Value

True if moved to next record successfully. False if reached end of the data source.

Example

Performs mail merge from a custom data source.

[C#]

public void MailMergeCustomDataSource()
{
    // Create some data that we will use in the mail merge.
    CustomerList customers = new CustomerList();
    customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
    customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));

    // Open the template document.
    Document doc = new Document(MyDir + "MailMerge.CustomDataSource.doc");

    // To be able to mail merge from your own data source, it must be wrapped
    // into an object that implements the IMailMergeDataSource interface.
    CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);

    // Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource);

    doc.Save(ArtifactsDir + "MailMerge.CustomDataSource.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        FullName = aFullName;
        Address = anAddress;
    }

    public string FullName { get; set; }
    public string Address { get; set; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
public class CustomerList : ArrayList
{
    public new Customer this[int index]
    {
        get { return (Customer) base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// A custom mail merge data source that you implement to allow Aspose.Words
/// to mail merge data from your Customer objects into Microsoft Word documents.
/// </summary>
public class CustomerMailMergeDataSource : IMailMergeDataSource
{
    public CustomerMailMergeDataSource(CustomerList customers)
    {
        mCustomers = customers;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Customer"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mCustomers[mRecordIndex].FullName;
                return true;
            case "Address":
                fieldValue = mCustomers[mRecordIndex].Address;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        return null;
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mCustomers.Count); }
    }

    private readonly CustomerList mCustomers;
    private int mRecordIndex;
}

See Also

IMailMergeDataSource Interface | Aspose.Words.MailMerging Namespace


IMailMergeDataSourceRoot Interface

Implement this interface to allow mail merge from a custom data source with master-detail data.

For a list of all members of this type, see IMailMergeDataSourceRoot Members.

[Visual Basic]
Public Interface IMailMergeDataSourceRoot
[C#]
public interface IMailMergeDataSourceRoot

Example

Performs mail merge from a custom data source with master-detail data.

[C#]

public void MailMergeCustomDataSourceRoot()
{
    // Create a document with two mail merge regions named "Washington" and "Seattle"
    Document doc = CreateSourceDocumentWithMailMergeRegions(new string[] { "Washington", "Seattle" });

    // Create two data sources
    EmployeeList employeesWashingtonBranch = new EmployeeList();
    employeesWashingtonBranch.Add(new Employee("John Doe", "Sales"));
    employeesWashingtonBranch.Add(new Employee("Jane Doe", "Management"));

    EmployeeList employeesSeattleBranch = new EmployeeList();
    employeesSeattleBranch.Add(new Employee("John Cardholder", "Management"));
    employeesSeattleBranch.Add(new Employee("Joe Bloggs", "Sales"));

    // Register our data sources by name in a data source root
    DataSourceRoot sourceRoot = new DataSourceRoot();
    sourceRoot.RegisterSource("Washington", new EmployeeListMailMergeSource(employeesWashingtonBranch));
    sourceRoot.RegisterSource("Seattle", new EmployeeListMailMergeSource(employeesSeattleBranch));

    // Since we have consecutive mail merge regions, we would normally have to perform two mail merges
    // However, one mail merge source data root call every relevant data source and merge automatically
    doc.MailMerge.ExecuteWithRegions(sourceRoot);

    doc.Save(ArtifactsDir + "MailMerge.MailMergeCustomDataSourceRoot.docx");
}

/// <summary>
/// Create document that contains consecutive mail merge regions, with names designated by the input array, for a data table of employees
/// </summary>
private Document CreateSourceDocumentWithMailMergeRegions(string[] regions)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    foreach (string s in regions)
    {
        builder.Writeln("\n" + s + " branch: ");
        builder.InsertField(" MERGEFIELD TableStart:" + s);
        builder.InsertField(" MERGEFIELD FullName");
        builder.Write(", ");
        builder.InsertField(" MERGEFIELD Department");
        builder.InsertField(" MERGEFIELD TableEnd:" + s);
    }

    return doc;
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
private class Employee
{
    public Employee(string aFullName, string aDepartment)
    {
        FullName = aFullName;
        Department = aDepartment;
    }

    public string FullName { get; }
    public string Department { get; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
private class EmployeeList : ArrayList
{
    public new Employee this[int index]
    {
        get { return (Employee)base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// Data source root that can be passed directly into a mail merge which can register and contain many child data sources
/// These sources must all implement IMailMergeDataSource, and are registered and differentiated by a name
/// which corresponds to a mail merge region that will read the respective data
/// </summary>
private class DataSourceRoot : IMailMergeDataSourceRoot
{
    Dictionary<string, EmployeeListMailMergeSource> sources = new Dictionary<string, EmployeeListMailMergeSource>();

    public IMailMergeDataSource GetDataSource(string tableName)
    {
        EmployeeListMailMergeSource source = sources[tableName];
        source.Reset();
        return sources[tableName];
    }

    public void RegisterSource(string sourceName, EmployeeListMailMergeSource source)
    {
        sources.Add(sourceName, source);
    }
}

/// <summary>
/// Custom mail merge data source
/// </summary>
private class EmployeeListMailMergeSource : IMailMergeDataSource
{
    public EmployeeListMailMergeSource(EmployeeList employees)
    {
        mEmployees = employees;
        mRecordIndex = -1;
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mEmployees.Count); }
    }

    public void Reset()
    {
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Employees"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mEmployees[mRecordIndex].FullName;
                return true;
            case "Department":
                fieldValue = mEmployees[mRecordIndex].Department;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// Child data sources are for nested mail merges
    /// </summary>
    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        throw new System.NotImplementedException();
    }

    private readonly EmployeeList mEmployees;
    private int mRecordIndex;
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IMailMergeDataSourceRoot Members | Aspose.Words.MailMerging Namespace


IMailMergeDataSourceRoot Members

IMailMergeDataSourceRoot overview

Public Instance Methods

GetDataSource The Aspose.Words mail merge engine invokes this method when it encounters a beginning of a top-level mail merge region.

See Also

IMailMergeDataSourceRoot Interface | Aspose.Words.MailMerging Namespace


IMailMergeDataSourceRoot Methods

The methods of the IMailMergeDataSourceRoot interface are listed below. For a complete list of IMailMergeDataSourceRoot interface members, see the IMailMergeDataSourceRoot Members topic.

Public Instance Methods

GetDataSource The Aspose.Words mail merge engine invokes this method when it encounters a beginning of a top-level mail merge region.

See Also

IMailMergeDataSourceRoot Interface | Aspose.Words.MailMerging Namespace


IMailMergeDataSourceRoot.GetDataSource Method

The Aspose.Words mail merge engine invokes this method when it encounters a beginning of a top-level mail merge region.

[Visual Basic]
Function GetDataSource( _
ByVal tableName As String _
) As IMailMergeDataSource
[C#]
IMailMergeDataSource GetDataSource(
string tableName
);

Parameters

tableName
The name of the mail merge region as specified in the template document. Case-insensitive.

Return Value

A data source object that will provide access to the data records of the specified table.

Remarks

When the Aspose.Words mail merge engines populates a document with data and encounters MERGEFIELD TableStart:TableName, it invokes GetDataSource on this object. Your implementation needs to return a new data source object. Aspose.Words will use the returned data source to populate the mail merge region.

If a data source (table) with the specified name does not exist, your implementation should return null.

Example

Performs mail merge from a custom data source with master-detail data.

[C#]

public void MailMergeCustomDataSourceRoot()
{
    // Create a document with two mail merge regions named "Washington" and "Seattle"
    Document doc = CreateSourceDocumentWithMailMergeRegions(new string[] { "Washington", "Seattle" });

    // Create two data sources
    EmployeeList employeesWashingtonBranch = new EmployeeList();
    employeesWashingtonBranch.Add(new Employee("John Doe", "Sales"));
    employeesWashingtonBranch.Add(new Employee("Jane Doe", "Management"));

    EmployeeList employeesSeattleBranch = new EmployeeList();
    employeesSeattleBranch.Add(new Employee("John Cardholder", "Management"));
    employeesSeattleBranch.Add(new Employee("Joe Bloggs", "Sales"));

    // Register our data sources by name in a data source root
    DataSourceRoot sourceRoot = new DataSourceRoot();
    sourceRoot.RegisterSource("Washington", new EmployeeListMailMergeSource(employeesWashingtonBranch));
    sourceRoot.RegisterSource("Seattle", new EmployeeListMailMergeSource(employeesSeattleBranch));

    // Since we have consecutive mail merge regions, we would normally have to perform two mail merges
    // However, one mail merge source data root call every relevant data source and merge automatically
    doc.MailMerge.ExecuteWithRegions(sourceRoot);

    doc.Save(ArtifactsDir + "MailMerge.MailMergeCustomDataSourceRoot.docx");
}

/// <summary>
/// Create document that contains consecutive mail merge regions, with names designated by the input array, for a data table of employees
/// </summary>
private Document CreateSourceDocumentWithMailMergeRegions(string[] regions)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    foreach (string s in regions)
    {
        builder.Writeln("\n" + s + " branch: ");
        builder.InsertField(" MERGEFIELD TableStart:" + s);
        builder.InsertField(" MERGEFIELD FullName");
        builder.Write(", ");
        builder.InsertField(" MERGEFIELD Department");
        builder.InsertField(" MERGEFIELD TableEnd:" + s);
    }

    return doc;
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
private class Employee
{
    public Employee(string aFullName, string aDepartment)
    {
        FullName = aFullName;
        Department = aDepartment;
    }

    public string FullName { get; }
    public string Department { get; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
private class EmployeeList : ArrayList
{
    public new Employee this[int index]
    {
        get { return (Employee)base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// Data source root that can be passed directly into a mail merge which can register and contain many child data sources
/// These sources must all implement IMailMergeDataSource, and are registered and differentiated by a name
/// which corresponds to a mail merge region that will read the respective data
/// </summary>
private class DataSourceRoot : IMailMergeDataSourceRoot
{
    Dictionary<string, EmployeeListMailMergeSource> sources = new Dictionary<string, EmployeeListMailMergeSource>();

    public IMailMergeDataSource GetDataSource(string tableName)
    {
        EmployeeListMailMergeSource source = sources[tableName];
        source.Reset();
        return sources[tableName];
    }

    public void RegisterSource(string sourceName, EmployeeListMailMergeSource source)
    {
        sources.Add(sourceName, source);
    }
}

/// <summary>
/// Custom mail merge data source
/// </summary>
private class EmployeeListMailMergeSource : IMailMergeDataSource
{
    public EmployeeListMailMergeSource(EmployeeList employees)
    {
        mEmployees = employees;
        mRecordIndex = -1;
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mEmployees.Count); }
    }

    public void Reset()
    {
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Employees"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mEmployees[mRecordIndex].FullName;
                return true;
            case "Department":
                fieldValue = mEmployees[mRecordIndex].Department;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// Child data sources are for nested mail merges
    /// </summary>
    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        throw new System.NotImplementedException();
    }

    private readonly EmployeeList mEmployees;
    private int mRecordIndex;
}

See Also

IMailMergeDataSourceRoot Interface | Aspose.Words.MailMerging Namespace


MailMerge Class

Represents the mail merge functionality.

For a list of all members of this type, see MailMerge Members.

System.Object
Aspose.Words.MailMerging.MailMerge

[Visual Basic]
Public Class MailMerge
[C#]
public class MailMerge

Remarks

For mail merge operation to work, the document should contain Word MERGEFIELD and optionally NEXT fields. During mail merge operation, merge fields in the document are replaced with values from your data source.

There are two distinct ways to use mail merge: with mail merge regions and without.

The simplest mail merge is without regions and it is very similar to how mail merge works in Word. Use Execute methods to merge information from some data source such as DataTable, DataSet, DataView, IDataReader or an array of objects into your document. The MailMerge object processes all records of the data source and copies and appends content of the whole document for each record.

Note that when MailMerge object encounters a NEXT field, it selects next record in the data source and continues merging without copying any content.

Use ExecuteWithRegions methods to merge information into a document with mail merge regions defined. You can use DataSet, DataTable, DataView or IDataReader as data sources for this operation.

You need to use mail merge regions if you want to dynamically grow portions inside the document. Without mail merge regions whole document will be repeated for every record of the data source.

Example

Executes mail merge from an ADO.NET DataTable.

[C#]

Document doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
DataTable table = new DataTable("Test");
table.Columns.Add("CustomerName");
table.Columns.Add("Address");
table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.MailMerge.Execute(table);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.doc");

// Open a fresh copy of our document to perform another mail merge.
doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// We can also source values for a mail merge from a single row in the table
doc.MailMerge.Execute(table.Rows[1]);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.doc");

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MailMerge Members | Aspose.Words.MailMerging Namespace | Document | MailMerge


MailMerge Members

MailMerge overview

Public Instance Properties

CleanupOptions | Gets or sets a set of flags that specify what items should be removed during mail merge.
CleanupParagraphsWithPunctuationMarks | Gets or sets a value indicating whether paragraphs with punctuation marks are considered as empty and should be removed if the RemoveEmptyParagraphs option is specified.
FieldMergingCallback | Occurs during mail merge when a mail merge field is encountered in the document.
MailMergeCallback | Allows to handle particular events during mail merge.
MappedDataFields | Returns a collection that represents mapped data fields for the mail merge operation.
MergeDuplicateRegions | Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one.
MergeWholeDocument | Gets or sets a value indicating whether fields in whole document is updated while executing of a mail merge with regions.
PreserveUnusedTags | Gets or sets a value indicating whether the unused "mustache" tags should be preserved.
RegionEndTag | Gets or sets a mail merge region end tag.
RegionStartTag | Gets or sets a mail merge region start tag.
TrimWhitespaces | Gets or sets a value indicating whether trailing and leading whitespaces are trimmed from mail merge values.
UnconditionalMergeFieldsAndRegions | Gets or sets a value indicating whether merge fields and merge regions are merged regardless of the parent IF field's condition.
UseNonMergeFields | When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.
UseWholeParagraphAsRegion | Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region.

Public Instance Methods

DeleteFields | Removes mail merge related fields from the document.
Execute | Overloaded. Performs a mail merge operation.
ExecuteADO | Performs mail merge from an ADO Recordset object into the document.
ExecuteWithRegions | Overloaded. Performs a mail merge operation into a document with mail merge regions. Supports parent-child (master-detail) data sources and nested mail merge regions.
ExecuteWithRegionsADO | Performs mail merge from an ADO Recordset object into the document with mail merge regions.
GetFieldNames | Returns a collection of mail merge field names available in the document.
GetFieldNamesForRegion | Overloaded. Get mail merge field names from the region.
GetRegionsByName | Returns a collection of mail merge regions with the specified name.
GetRegionsHierarchy | Returns a full hierarchy of regions (with fields) available in the document.

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | Document | MailMerge


MailMerge Properties

The properties of the MailMerge class are listed below. For a complete list of MailMerge class members, see the MailMerge Members topic.

Public Instance Properties

CleanupOptions | Gets or sets a set of flags that specify what items should be removed during mail merge.
CleanupParagraphsWithPunctuationMarks | Gets or sets a value indicating whether paragraphs with punctuation marks are considered as empty and should be removed if the RemoveEmptyParagraphs option is specified.
FieldMergingCallback | Occurs during mail merge when a mail merge field is encountered in the document.
MailMergeCallback | Allows to handle particular events during mail merge.
MappedDataFields | Returns a collection that represents mapped data fields for the mail merge operation.
MergeDuplicateRegions | Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one.
MergeWholeDocument | Gets or sets a value indicating whether fields in whole document is updated while executing of a mail merge with regions.
PreserveUnusedTags | Gets or sets a value indicating whether the unused "mustache" tags should be preserved.
RegionEndTag | Gets or sets a mail merge region end tag.
RegionStartTag | Gets or sets a mail merge region start tag.
TrimWhitespaces | Gets or sets a value indicating whether trailing and leading whitespaces are trimmed from mail merge values.
UnconditionalMergeFieldsAndRegions | Gets or sets a value indicating whether merge fields and merge regions are merged regardless of the parent IF field's condition.
UseNonMergeFields | When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.
UseWholeParagraphAsRegion | Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region.

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | Document | MailMerge


CleanupOptions Property

Aspose.Words

MailMerge.CleanupOptions Property

Gets or sets a set of flags that specify what items should be removed during mail merge.

[Visual Basic]
Public Property CleanupOptions As MailMergeCleanupOptions
[C#]
public MailMergeCleanupOptions CleanupOptions {get; set;}

Example

Shows how to automatically remove unmerged merge fields during mail merge.

[C#]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedFields;
Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document.
[C#]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
Shows how to instruct the mail merge engine to remove any containing fields from around a merge field during mail merge.
[C#]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


CleanupParagraphsWithPunctuationMarks Property

Aspose.Words

MailMerge.CleanupParagraphsWithPunctuationMarks Property

Gets or sets a value indicating whether paragraphs with punctuation marks are considered as empty and should be removed if the RemoveEmptyParagraphs option is specified.

[Visual Basic]
Public Property CleanupParagraphsWithPunctuationMarks As Boolean
[C#]
public bool CleanupParagraphsWithPunctuationMarks {get; set;}

Remarks

The default value is true. Here is the complete list of cleanable punctuation marks:

  • !
  • ,
  • .
  • :
  • ;
  • ?
  • ¡
  • ¿

Example

Shows how to remove paragraphs with punctuation marks after mail merge operation.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

FieldMergeField mergeFieldOption1 = (FieldMergeField) builder.InsertField("MERGEFIELD", "Option_1");
mergeFieldOption1.FieldName = "Option_1";

// Here is the complete list of cleanable punctuation marks:
// !
// ,
// .
// :
// ;
// ?
// ¡
// ¿
builder.Write(punctuationMark);

FieldMergeField mergeFieldOption2 = (FieldMergeField) builder.InsertField("MERGEFIELD", "Option_2");
mergeFieldOption2.FieldName = "Option_2";

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
// The default value of the option is true which means that the behaviour was changed to mimic MS Word
// If you rely on the old behavior are able to revert it by setting the option to false
doc.MailMerge.CleanupParagraphsWithPunctuationMarks = isCleanupParagraphsWithPunctuationMarks;

doc.MailMerge.Execute(new[] { "Option_1", "Option_2" }, new object[] { null, null });

doc.Save(ArtifactsDir + "RemoveColonBetweenEmptyMergeFields.docx");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


FieldMergingCallback Property

Aspose.Words

MailMerge.FieldMergingCallback Property

Occurs during mail merge when a mail merge field is encountered in the document.

[Visual Basic]
Public Property FieldMergingCallback As IFieldMergingCallback
[C#]
public IFieldMergingCallback FieldMergingCallback {get; set;}

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}
Shows how to mail merge HTML data into a document.
[C#]

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
    // File 'MailMerge.HtmlData.html' contains some valid HTML data.
    // The same approach can be used when merging HTML data from database.
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

    // Load some HTML from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();

    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new object[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(ArtifactsDir + "MailMerge.InsertHtml.doc");
}

private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (args.DocumentFieldName.StartsWith("html") && args.Field.GetFieldCode().Contains("\\b"))
        {
            FieldMergeField field = args.Field;

            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.DocumentFieldName);
            builder.Write(field.TextBefore);
            builder.InsertHtml((string) args.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            args.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMergeCallback Property

Aspose.Words

MailMerge.MailMergeCallback Property

Allows to handle particular events during mail merge.

[Visual Basic]
Public Property MailMergeCallback As IMailMergeCallback
[C#]
public IMailMergeCallback MailMergeCallback {get; set;}

Example

Shows how to define custom logic for handling events during mail merge.

[C#]

Document document = new Document();
    document.MailMerge.UseNonMergeFields = true;

    MailMergeCallbackStub mailMergeCallbackStub = new MailMergeCallbackStub();
    document.MailMerge.MailMergeCallback = mailMergeCallbackStub;

    document.MailMerge.Execute(new String[0], new object[0]);

    Assert.AreEqual(1, mailMergeCallbackStub.TagsReplacedCounter);
}

private class MailMergeCallbackStub : IMailMergeCallback
{
    public void TagsReplaced()
    {
        TagsReplacedCounter++;
    }

    public int TagsReplacedCounter { get; private set; }
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MappedDataFields Property

Aspose.Words

MailMerge.MappedDataFields Property

Returns a collection that represents mapped data fields for the mail merge operation.

[Visual Basic]
Public ReadOnly Property MappedDataFields As MappedDataFieldCollection
[C#]
public MappedDataFieldCollection MappedDataFields {get;}

Remarks

Mapped data fields allow to automatically map between names of fields in your data source and names of mail merge fields in the document.

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MergeDuplicateRegions Property

Aspose.Words

MailMerge.MergeDuplicateRegions Property

Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one.

[Visual Basic]
Public Property MergeDuplicateRegions As Boolean
[C#]
public bool MergeDuplicateRegions {get; set;}

Remarks

The default value is false.

Example

Shows how to work with duplicate mail merge regions.

[C#]

public void MergeDuplicateRegions(bool isMergeDuplicateRegions)
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMergeDuplicateRegions();
    DataTable dataTable = CreateSourceTableMergeDuplicateRegions();

    // If this property is false, the first region will be merged
    // while the MERGEFIELDs of the second one will be left in the pre-merge state
    // To get both regions merged we would have to execute the mail merge twice, on a table of the same name
    // If this is set to true, both regions will be affected by the merge
    doc.MailMerge.MergeDuplicateRegions = isMergeDuplicateRegions;

    doc.MailMerge.ExecuteWithRegions(dataTable);
    doc.Save(ArtifactsDir + "MailMerge.MergeDuplicateRegions.docx");
}

/// <summary>
/// Return a document that contains two duplicate mail merge regions (sharing the same name in the "TableStart/End" tags)
/// </summary>
private Document CreateSourceDocMergeDuplicateRegions()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.InsertField(" MERGEFIELD TableStart:MergeRegion");
    builder.InsertField(" MERGEFIELD Column1");
    builder.InsertField(" MERGEFIELD TableEnd:MergeRegion");
    builder.InsertParagraph();

    builder.InsertField(" MERGEFIELD TableStart:MergeRegion");
    builder.InsertField(" MERGEFIELD Column2");
    builder.InsertField(" MERGEFIELD TableEnd:MergeRegion");

    return doc;
}

/// <summary>
/// Create a data table with one row and two columns
/// </summary>
private DataTable CreateSourceTableMergeDuplicateRegions()
{
    DataTable dataTable = new DataTable("MergeRegion");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value 1", "Value 2" });

    return dataTable;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MergeWholeDocument Property

Aspose.Words

MailMerge.MergeWholeDocument Property

Gets or sets a value indicating whether fields in whole document is updated while executing of a mail merge with regions.

[Visual Basic]
Public Property MergeWholeDocument As Boolean
[C#]
public bool MergeWholeDocument {get; set;}

Remarks

The default value is false.

Example

Shows the relationship between mail merges with regions and field updating.

[C#]

public void MergeWholeDocument(bool isMergeWholeDocument)
{
    // Create a document and data table that will both be merged
    Document doc = CreateSourceDocMergeWholeDocument();
    DataTable dataTable = CreateSourceTableMergeWholeDocument();

    // A regular mail merge will update all fields in the document as part of the procedure,
    // which will happen if this property is set to true
    // Otherwise, a mail merge with regions will only update fields inside of the designated mail merge region
    doc.MailMerge.MergeWholeDocument = isMergeWholeDocument;
    doc.MailMerge.ExecuteWithRegions(dataTable);

    // If true, all fields in the document will be updated upon merging
    // In this case that property is false, so the first QUOTE field will not be updated and will not show a value,
    // but the second one inside the region designated by the data table name will show the correct value
    doc.Save(ArtifactsDir + "MailMerge.MergeWholeDocument.docx");
}

/// <summary>
/// Create a document with a QUOTE field outside and one more inside a mail merge region called "MyTable"
/// </summary>
private Document CreateSourceDocMergeWholeDocument()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert QUOTE field outside of any mail merge regions
    FieldQuote field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
    field.Text = "This QUOTE field is outside of the \"MyTable\" merge region.";

    // Start "MyTable" merge region
    builder.InsertParagraph();
    builder.InsertField(" MERGEFIELD TableStart:MyTable");

    // Insert QUOTE field inside "MyTable" merge region
    field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
    field.Text = "This QUOTE field is inside the \"MyTable\" merge region.";
    builder.InsertParagraph();

    // Add a MERGEFIELD for a column in the data table, end the "MyTable" region and return the document
    builder.InsertField(" MERGEFIELD MyColumn");
    builder.InsertField(" MERGEFIELD TableEnd:MyTable");

    return doc;
}

/// <summary>
/// Create a simple data table that will be used in a mail merge
/// </summary>
private DataTable CreateSourceTableMergeWholeDocument()
{
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("MyColumn");
    dataTable.Rows.Add(new object[] { "MyValue" });

    return dataTable;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


PreserveUnusedTags Property

Aspose.Words

MailMerge.PreserveUnusedTags Property

Gets or sets a value indicating whether the unused "mustache" tags should be preserved.

[Visual Basic]
Public Property PreserveUnusedTags As Boolean
[C#]
public bool PreserveUnusedTags {get; set;}

Remarks

The default value is false.

Example

Shows how to preserve the appearance of alternative mail merge tags that go unused during a mail merge.

[C#]

public void PreserveUnusedTags(bool preserveUnusedTags)
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocWithAlternativeMergeFields();
    DataTable dataTable = CreateSourceTablePreserveUnusedTags();

    // By default, alternative merge tags that can't receive data because the data source has no columns with their name
    // are converted to and left on display as MERGEFIELDs after the mail merge
    // We can preserve their original appearance setting this attribute to true
    doc.MailMerge.PreserveUnusedTags = preserveUnusedTags;
    doc.MailMerge.Execute(dataTable);

    doc.Save(ArtifactsDir + "MailMerge.PreserveUnusedTags.docx");
}

/// <summary>
/// Create a document and add two tags that can accept mail merge data that are not the traditional MERGEFIELDs
/// </summary>
private Document CreateSourceDocWithAlternativeMergeFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("{{ Column1 }}");
    builder.Writeln("{{ Column2 }}");

    // Our tags will only register as destinations for mail merge data if we set this to true
    doc.MailMerge.UseNonMergeFields = true;

    return doc;
}

/// <summary>
/// Create a simple data table with one column
/// </summary>
private DataTable CreateSourceTablePreserveUnusedTags()
{
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Rows.Add(new object[] { "Value1" });

    return dataTable;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | UseNonMergeFields


RegionEndTag Property

Aspose.Words

MailMerge.RegionEndTag Property

Gets or sets a mail merge region end tag.

[Visual Basic]
Public Property RegionEndTag As String
[C#]
public string RegionEndTag {get; set;}

Example

Shows how to create, list and read mail merge regions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// These tags, which go inside MERGEFIELDs, denote the strings that signify the starts and ends of mail merge regions
Assert.AreEqual("TableStart", doc.MailMerge.RegionStartTag);
Assert.AreEqual("TableEnd", doc.MailMerge.RegionEndTag);

// By using these tags, we will start and end a "MailMergeRegion1", which will contain MERGEFIELDs for two columns
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column1");
builder.Write(", ");
builder.InsertField(" MERGEFIELD Column2");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// We can keep track of merge regions and their columns by looking at these collections
IList<MailMergeRegionInfo> regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(1, regions.Count);
Assert.AreEqual("MailMergeRegion1", regions[0].Name);

string[] mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1");
Assert.AreEqual("Column1", mergeFieldNames[0]);
Assert.AreEqual("Column2", mergeFieldNames[1]);

// Insert a region with the same name as an existing region, which will make it a duplicate
builder.InsertParagraph(); // A single row/paragraph cannot be shared by multiple regions
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column3");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// Regions that share the same name are still accounted for and can be accessed by index
regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(2, regions.Count);

mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1", 1);
Assert.AreEqual("Column3", mergeFieldNames[0]);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


RegionStartTag Property

Aspose.Words

MailMerge.RegionStartTag Property

Gets or sets a mail merge region start tag.

[Visual Basic]
Public Property RegionStartTag As String
[C#]
public string RegionStartTag {get; set;}

Example

Shows how to create, list and read mail merge regions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// These tags, which go inside MERGEFIELDs, denote the strings that signify the starts and ends of mail merge regions
Assert.AreEqual("TableStart", doc.MailMerge.RegionStartTag);
Assert.AreEqual("TableEnd", doc.MailMerge.RegionEndTag);

// By using these tags, we will start and end a "MailMergeRegion1", which will contain MERGEFIELDs for two columns
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column1");
builder.Write(", ");
builder.InsertField(" MERGEFIELD Column2");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// We can keep track of merge regions and their columns by looking at these collections
IList<MailMergeRegionInfo> regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(1, regions.Count);
Assert.AreEqual("MailMergeRegion1", regions[0].Name);

string[] mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1");
Assert.AreEqual("Column1", mergeFieldNames[0]);
Assert.AreEqual("Column2", mergeFieldNames[1]);

// Insert a region with the same name as an existing region, which will make it a duplicate
builder.InsertParagraph(); // A single row/paragraph cannot be shared by multiple regions
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column3");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// Regions that share the same name are still accounted for and can be accessed by index
regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(2, regions.Count);

mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1", 1);
Assert.AreEqual("Column3", mergeFieldNames[0]);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


TrimWhitespaces Property

Aspose.Words

MailMerge.TrimWhitespaces Property

Gets or sets a value indicating whether trailing and leading whitespaces are trimmed from mail merge values.

[Visual Basic]
Public Property TrimWhitespaces As Boolean
[C#]
public bool TrimWhitespaces {get; set;}

Remarks

The default value is true.

Example

Shows how to trimmed whitespaces from mail merge values.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertField("MERGEFIELD field", null);

doc.MailMerge.TrimWhitespaces = true;
doc.MailMerge.Execute(new[] { "field" }, new object[] { " first line\rsecond line\rthird line " });

Assert.AreEqual("first line\rsecond line\rthird line\f", doc.GetText());

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


UnconditionalMergeFieldsAndRegions Property

Aspose.Words

MailMerge.UnconditionalMergeFieldsAndRegions Property

Gets or sets a value indicating whether merge fields and merge regions are merged regardless of the parent IF field's condition.

[Visual Basic]
Public Property UnconditionalMergeFieldsAndRegions As Boolean
[C#]
public bool UnconditionalMergeFieldsAndRegions {get; set;}

Remarks

The default value is false.

Example

Shows how to merge fields or regions regardless of the parent IF field's condition.

[C#]

Document doc = new Document(MyDir + "MailMerge.UnconditionalMergeFieldsAndRegions.docx");

// Merge fields and merge regions are merged regardless of the parent IF field's condition.
doc.MailMerge.UnconditionalMergeFieldsAndRegions = true;

// Fill the fields in the document with user data.
doc.MailMerge.Execute(
    new string[] { "FullName" },
    new object[] { "James Bond" });

doc.Save(ArtifactsDir + "MailMerge.UnconditionalMergeFieldsAndRegions.docx");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


UseNonMergeFields Property

Aspose.Words

MailMerge.UseNonMergeFields Property

When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.

[Visual Basic]
Public Property UseNonMergeFields As Boolean
[C#]
public bool UseNonMergeFields {get; set;}

Remarks

Normally, mail merge is only performed into MERGEFIELD fields, but several customers had their reporting built using other fields and had many documents created this way. To simplify migration (and because this approach was independently used by several customers) the ability to mail merge into other fields was introduced.

When UseNonMergeFields is set to true, Aspose.Words will perform mail merge into the following fields:

MERGEFIELD FieldName

MACROBUTTON NOMACRO FieldName

IF 0 = 0 "{FieldName}" ""

Also, when UserNonMergeFields is set to true, Aspose.Words will perform mail merge into text tags "{{fieldName}}". These are not fields, but just text tags.

Example

Shows how to perform mail merge into merge fields and into additional fields types.

[C#]

doc.MailMerge.UseNonMergeFields = true;

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


UseWholeParagraphAsRegion Property

Aspose.Words

MailMerge.UseWholeParagraphAsRegion Property

Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region.

[Visual Basic]
Public Property UseWholeParagraphAsRegion As Boolean
[C#]
public bool UseWholeParagraphAsRegion {get; set;}

Remarks

The default value is true.

Example

Shows the relationship between mail merge regions and paragraphs.

[C#]

public void UseWholeParagraphAsRegion()
{
    // Create a document with 2 mail merge regions in one paragraph and a table to which can fill one of the regions during a mail merge
    Document doc = CreateSourceDocWithNestedMergeRegions();
    DataTable dataTable = CreateSourceTableDataTableForOneRegion();

    // By default, a paragraph can belong to no more than one mail merge region
    // Our document breaks this rule so executing a mail merge with regions now will cause an exception to be thrown
    Assert.True(doc.MailMerge.UseWholeParagraphAsRegion);

    // If we set this variable to false, paragraphs and mail merge regions are independent so we can safely run our mail merge
    doc.MailMerge.UseWholeParagraphAsRegion = false;
    doc.MailMerge.ExecuteWithRegions(dataTable);

    // Our first region is populated, while our second is safely displayed as unused all across one paragraph
    doc.Save(ArtifactsDir + "MailMerge.UseWholeParagraphAsRegion.docx");
}

/// <summary>
/// Create a document with two mail merge regions sharing one paragraph
/// </summary>
private Document CreateSourceDocWithNestedMergeRegions()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Write("Region 1: ");
    builder.InsertField(" MERGEFIELD TableStart:MyTable");
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column2");
    builder.InsertField(" MERGEFIELD TableEnd:MyTable");

    builder.Write(", Region 2: ");
    builder.InsertField(" MERGEFIELD TableStart:MyOtherTable");
    builder.InsertField(" MERGEFIELD TableEnd:MyOtherTable");

    return doc;
}

/// <summary>
/// Create a data table that can populate one region during a mail merge
/// </summary>
private DataTable CreateSourceTableDataTableForOneRegion()
{
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value 1", "Value 2" });

    return dataTable;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMerge Methods

The methods of the MailMerge class are listed below. For a complete list of MailMerge class members, see the MailMerge Members topic.

Public Instance Methods

DeleteFields | Removes mail merge related fields from the document.
Execute | Overloaded. Performs a mail merge operation.
ExecuteADO | Performs mail merge from an ADO Recordset object into the document.
ExecuteWithRegions | Overloaded. Performs a mail merge operation into a document with mail merge regions. Supports parent-child (master-detail) data sources and nested mail merge regions.
ExecuteWithRegionsADO | Performs mail merge from an ADO Recordset object into the document with mail merge regions.
GetFieldNames | Returns a collection of mail merge field names available in the document.
GetFieldNamesForRegion | Overloaded. Get mail merge field names from the region.
GetRegionsByName | Returns a collection of mail merge regions with the specified name.
GetRegionsHierarchy | Returns a full hierarchy of regions (with fields) available in the document.

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | Document | MailMerge


MailMerge.DeleteFields Method

Removes mail merge related fields from the document.

[Visual Basic]
Public Sub DeleteFields()
[C#]
public void DeleteFields();

Remarks

This method removes MERGEFIELD and NEXT fields from the document.

This method could be useful if your mail merge operation does not always need to populate all fields in the document. Use this method to remove all remaining mail merge fields.

Example

Shows how to delete all merge fields from a document without executing mail merge.

[C#]

doc.MailMerge.DeleteFields();

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


Execute Method

Aspose.Words

MailMerge.Execute Method

Performs a mail merge operation.

Overload List

Performs a mail merge from a custom data source.

public void Execute(IMailMergeDataSource);

Performs mail merge from a DataRow into the document.

public void Execute(DataRow);

Performs mail merge from a DataTable into the document.

public void Execute(DataTable);

Performs mail merge from a DataView into the document.

public void Execute(DataView);

Performs mail merge from IDataReader into the document.

public void Execute(IDataReader);

Performs a mail merge operation for a single record.

public void Execute(string[],object[]);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMerge.Execute Method (IMailMergeDataSource)

Performs a mail merge from a custom data source.

[Visual Basic]
Overloads Public Sub Execute( _
ByVal dataSource As IMailMergeDataSource _
)
[C#]
public void Execute(
IMailMergeDataSource dataSource
);

Parameters

dataSource
An object that implements the custom mail merge data source interface.

Remarks

Use this method to fill mail merge fields in the document with values from any data source such as a list or hashtable or objects. You need to write your own class that implements the IMailMergeDataSource interface.

You can use this method only when IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

This method ignores the RemoveUnusedRegions option.

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.Execute Overload List


MailMerge.Execute Method (DataRow)

Performs mail merge from a DataRow into the document.

[Visual Basic]
Overloads Public Sub Execute( _
ByVal row As DataRow _
)
[C#]
public void Execute(
DataRow row
);

Parameters

row
Row that contains data to be inserted into mail merge fields. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.

Remarks

Use this method to fill mail merge fields in the document with values from a DataRow.

This method ignores the RemoveUnusedRegions option.

Example

Executes mail merge from an ADO.NET DataTable.

[C#]

Document doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
DataTable table = new DataTable("Test");
table.Columns.Add("CustomerName");
table.Columns.Add("Address");
table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.MailMerge.Execute(table);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.doc");

// Open a fresh copy of our document to perform another mail merge.
doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// We can also source values for a mail merge from a single row in the table
doc.MailMerge.Execute(table.Rows[1]);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.doc");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.Execute Overload List


MailMerge.Execute Method (DataTable)

Performs mail merge from a DataTable into the document.

[Visual Basic]
Overloads Public Sub Execute( _
ByVal table As DataTable _
)
[C#]
public void Execute(
DataTable table
);

Parameters

table
Table that contains data to be inserted into mail merge fields. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.

Remarks

Use this method to fill mail merge fields in the document with values from a DataTable.

All records from the table are merged into the document.

You can use NEXT field in the Word document to cause MailMerge object to select next record from the DataTable and continue merging. This can be used when creating documents such as mailing labels.

When MailMerge object reaches end of the main document and there are still more rows in the DataTable, it copies entire content of the main document and appends it to the end of the destination document using a section break as a separator.

This method ignores the RemoveUnusedRegions option.

Example

Executes mail merge from an ADO.NET DataTable.

[C#]

Document doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
DataTable table = new DataTable("Test");
table.Columns.Add("CustomerName");
table.Columns.Add("Address");
table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.MailMerge.Execute(table);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.doc");

// Open a fresh copy of our document to perform another mail merge.
doc = new Document(MyDir + "MailMerge.ExecuteDataTable.doc");

// We can also source values for a mail merge from a single row in the table
doc.MailMerge.Execute(table.Rows[1]);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.doc");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.Execute Overload List


MailMerge.Execute Method (DataView)

Performs mail merge from a DataView into the document.

[Visual Basic]
Overloads Public Sub Execute( _
ByVal dataView As DataView _
)
[C#]
public void Execute(
DataView dataView
);

Parameters

dataView
Data source for the mail merge operation.

Remarks

This method is useful if you retrieve data into a DataTable but then need to apply a filter or sort before the mail merge.

Note this method does not use mail merge regions and for multiple records the document will grow by repeating the whole document.

This method ignores the RemoveUnusedRegions option.

Example

Shows how to process a DataTable's data with a DataView before using it in a mail merge.

[C#]

// Create a new document and populate it with merge fields
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Congratulations ");
builder.InsertField(" MERGEFIELD Name");
builder.Write(" for passing with a grade of ");
builder.InsertField(" MERGEFIELD Grade");

// Create a data table that merge data will be sourced from
DataTable table = new DataTable("ExamResults");
table.Columns.Add("Name");
table.Columns.Add("Grade");
table.Rows.Add(new object[] { "John Doe", "67" });
table.Rows.Add(new object[] { "Jane Doe", "81" });
table.Rows.Add(new object[] { "John Cardholder", "47" });
table.Rows.Add(new object[] { "Joe Bloggs", "75" });

// If we execute the mail merge on the table, a page will be created for each row in the order that it appears in the table
// If we want to sort/filter rows without changing the table, we can use a data view
DataView view = new DataView(table);
view.Sort = "Grade DESC";
view.RowFilter = "Grade >= 50";

// This mail merge will be executed on a view where the rows are sorted by the "Grade" column
// and rows where the Grade values are below 50 are filtered out
doc.MailMerge.Execute(view);

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataView.docx");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.Execute Overload List


MailMerge.Execute Method (IDataReader)

Performs mail merge from IDataReader into the document.

[Visual Basic]
Overloads Public Sub Execute( _
ByVal dataReader As IDataReader _
)
[C#]
public void Execute(
IDataReader dataReader
);

Parameters

dataReader
Data source for the mail merge operation.

Remarks

You can pass SqlDataReader or OleDbDataReader object into this method as a parameter because they both implemented IDataReader interface.

Note this method does not use mail merge regions and for multiple records the document will grow by repeating the whole document.

This method ignores the RemoveUnusedRegions option.

Example

Shows how to run a mail merge using data from a data reader.

[C#]

// Create a new document and populate it with merge fields
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Product:\t");
builder.InsertField(" MERGEFIELD ProductName");
builder.Write("\nSupplier:\t");
builder.InsertField(" MERGEFIELD CompanyName");
builder.Writeln();
builder.InsertField(" MERGEFIELD QuantityPerUnit");
builder.Write(" for $");
builder.InsertField(" MERGEFIELD UnitPrice");

// Create a connection string which points to the "Northwind" database file in our local file system and open a connection
string connectionString = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=" + DatabaseDir + "Northwind.mdb";

using (OdbcConnection connection = new OdbcConnection())
{
    connection.ConnectionString = connectionString;
    connection.Open();

    // Create an SQL command that will source data for our mail merge
    // The command has to comply to the driver we are using, which in this case is "ODBC"
    // The names of the columns returned by this SELECT statement should correspond to the merge fields we placed above
    OdbcCommand command = connection.CreateCommand();
    command.CommandText = @"SELECT Products.ProductName, Suppliers.CompanyName, Products.QuantityPerUnit, {fn ROUND(Products.UnitPrice,2)} as UnitPrice
                            FROM Products
                            INNER JOIN Suppliers
                            ON Products.SupplierID = Suppliers.SupplierID";

    // This will run the command and store the data in the reader
    OdbcDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

    // Now we can take the data from the reader and use it in the mail merge
    doc.MailMerge.Execute(reader);
}

doc.Save(ArtifactsDir + "MailMerge.ExecuteDataReader.docx");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.Execute Overload List


MailMerge.Execute Method (String[], Object[])

Performs a mail merge operation for a single record.

[Visual Basic]
Overloads Public Sub Execute( _
ByVal fieldNames As String(), _
ByVal values As Object() _
)
[C#]
public void Execute(
string[] fieldNames,
object[] values
);

Parameters

fieldNames
Array of merge field names. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.
values
Array of values to be inserted into the merge fields. Number of elements in this array must be the same as the number of elements in fieldNames.

Remarks

Use this method to fill mail merge fields in the document with values from an array of objects.

This method merges data for one record only. The array of field names and the array of values represent the data of a single record.

This method does not use mail merge regions.

This method ignores the RemoveUnusedRegions option.

Example

Demonstrates how to merge an image from a web address using an Image field.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImageSimple.doc");

// Pass a URL which points to the image to merge into the document.
doc.MailMerge.Execute(new string[] { "Logo" },
    new object[] { AsposeLogoUrl });

doc.Save(ArtifactsDir + "MailMerge.MergeImageFromUrl.doc");
Performs a simple insertion of data into merge fields and sends the document to the browser inline.
[C#]

// Open an existing document.
Document doc = new Document(MyDir + "MailMerge.ExecuteArray.doc");

// Fill the fields in the document with user data.
doc.MailMerge.Execute(new String[] { "FullName", "Company", "Address", "Address2", "City" },
    new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });

// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
Assert.That(() => doc.Save(Response, "Artifacts/MailMerge.ExecuteArray.doc", ContentDisposition.Inline, null), Throws.TypeOf<ArgumentNullException>()); //Thrown because HttpResponse is null in the test.

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.Execute Overload List


MailMerge.ExecuteADO Method

Performs mail merge from an ADO Recordset object into the document.

[Visual Basic]
Public Sub ExecuteADO( _
ByVal recordset As Object _
)
[C#]
public void ExecuteADO(
object recordset
);

Parameters

recordset
ADO Recordset or Record object.

Remarks

This method is useful when you intend to use Aspose.Words classes as COM objects from unmanaged code such as an application built using ASP or Visual Basic 6.0.

This method ignores the RemoveUnusedRegions option.

For more information see description of MailMerge.Execute(DataTable).

Example

[VBScript]

 Dim RS
 Set RS = CreateObject("ADODB.Recordset")
 RS.Open _
     "SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName", _
     "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"

 Dim License
 Set License = CreateObject("Aspose.Words.License")
 License.SetLicense "C:\MyPath\MyLicense.lic"

 Dim Helper
 Set Helper = CreateObject("Aspose.Words.ComHelper")
 Dim Doc
 Set Doc = Helper.Open("CustomerLabels.doc")

 Doc.MailMerge.ExecuteADO RS
 Doc.Save "C:\MyPath\CustomerLabels Out VBScript.doc"
Shows how to run a mail merge with data from an ADO dataset.
[C#]

public void ExecuteADO()
{
    // Create a document that will be merged
    Document doc = CreateSourceDocADOMailMerge();

    // To work with ADO DataSets, we need to add a reference to the Microsoft ActiveX Data Objects library,
    // which is included in the .NET distribution and stored in "adodb.dll", then create a connection
    ADODB.Connection connection = new ADODB.Connection();

    // Create a connection string which points to the "Northwind" database file in our local file system and open a connection
    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    connection.Open(connectionString);

    // Create a record set
    ADODB.Recordset recordset = new ADODB.Recordset();

    // Run an SQL command on the database we are connected to to populate our dataset
    // The names of the columns returned here correspond to the values of the MERGEFIELDS that will accomodate our data
    string command = @"SELECT ProductName, QuantityPerUnit, UnitPrice FROM Products";
    recordset.Open(command, connection);

    // Execute the mail merge and save the document
    doc.MailMerge.ExecuteADO(recordset);
    doc.Save(ArtifactsDir + "MailMerge.ExecuteADO.docx");
}

/// <summary>
/// Create a blank document and populate it with MERGEFIELDS that will accept data when a mail merge is executed
/// </summary>
private Document CreateSourceDocADOMailMerge()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Write("Product:\t");
    builder.InsertField(" MERGEFIELD ProductName");
    builder.Writeln();
    builder.InsertField(" MERGEFIELD QuantityPerUnit");
    builder.Write(" for $");
    builder.InsertField(" MERGEFIELD UnitPrice");

    return doc;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


ExecuteWithRegions Method

Aspose.Words

MailMerge.ExecuteWithRegions Method

Performs a mail merge operation into a document with mail merge regions. Supports parent-child (master-detail) data sources and nested mail merge regions.

Overload List

Performs a mail merge from a custom data source with mail merge regions.

public void ExecuteWithRegions(IMailMergeDataSource);

Performs a mail merge from a custom data source with mail merge regions.

public void ExecuteWithRegions(IMailMergeDataSourceRoot);

Performs mail merge from a DataSet into a document with mail merge regions.

public void ExecuteWithRegions(DataSet);

Performs mail merge from a DataTable into the document with mail merge regions.

public void ExecuteWithRegions(DataTable);

Performs mail merge from a DataView into the document with mail merge regions.

public void ExecuteWithRegions(DataView);

Performs mail merge from IDataReader into the document with mail merge regions.

public void ExecuteWithRegions(IDataReader,string);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMerge.ExecuteWithRegions Method (IMailMergeDataSource)

Performs a mail merge from a custom data source with mail merge regions.

[Visual Basic]
Overloads Public Sub ExecuteWithRegions( _
ByVal dataSource As IMailMergeDataSource _
)
[C#]
public void ExecuteWithRegions(
IMailMergeDataSource dataSource
);

Parameters

dataSource
An object that implements the custom mail merge data source interface.

Remarks

Use this method to fill mail merge fields in the document with values from any custom data source such as an XML file or collections of business objects. You need to write your own class that implements the IMailMergeDataSource interface.

You can use this method only when IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

Example

Performs mail merge with regions from a custom data source.

[C#]

public void MailMergeCustomDataSource()
{
    // Create some data that we will use in the mail merge.
    CustomerList customers = new CustomerList();
    customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
    customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));

    // Create some data for nesting in the mail merge.
    customers[0].Orders.Add(new Order("Rugby World Cup Cap", 2));
    customers[0].Orders.Add(new Order("Rugby World Cup Ball", 1));
    customers[1].Orders.Add(new Order("Rugby World Cup Guide", 1));

    // Open the template document.
    Document doc = new Document(MyDir + "NestedMailMerge.CustomDataSource.doc");

    // To be able to mail merge from your own data source, it must be wrapped
    // into an object that implements the IMailMergeDataSource interface.
    CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);

    // Now you can pass your data source into Aspose.Words.
    doc.MailMerge.ExecuteWithRegions(customersDataSource);

    doc.Save(ArtifactsDir + "NestedMailMerge.CustomDataSource.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        FullName = aFullName;
        Address = anAddress;
        Orders = new OrderList();
    }

    public string FullName { get; set; }
    public string Address { get; set; }
    public OrderList Orders { get; set; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
public class CustomerList : ArrayList
{
    public new Customer this[int index]
    {
        get { return (Customer) base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// An example of a child "data entity" class in your application.
/// </summary>
public class Order
{
    public Order(string oName, int oQuantity)
    {
        Name = oName;
        Quantity = oQuantity;
    }

    public string Name { get; set; }
    public int Quantity { get; set; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
public class OrderList : ArrayList
{
    public new Order this[int index]
    {
        get { return (Order) base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// A custom mail merge data source that you implement to allow Aspose.Words
/// to mail merge data from your Customer objects into Microsoft Word documents.
/// </summary>
public class CustomerMailMergeDataSource : IMailMergeDataSource
{
    public CustomerMailMergeDataSource(CustomerList customers)
    {
        mCustomers = customers;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Customer"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mCustomers[mRecordIndex].FullName;
                return true;
            case "Address":
                fieldValue = mCustomers[mRecordIndex].Address;
                return true;
            case "Order":
                fieldValue = mCustomers[mRecordIndex].Orders;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        switch (tableName)
        {
            // Get the child collection to merge it with the region provided with tableName variable.
            case "Order":
                return new OrderMailMergeDataSource(mCustomers[mRecordIndex].Orders);
            default:
                return null;
        }
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mCustomers.Count); }
    }

    private readonly CustomerList mCustomers;
    private int mRecordIndex;
}

public class OrderMailMergeDataSource : IMailMergeDataSource
{
    public OrderMailMergeDataSource(OrderList orders)
    {
        mOrders = orders;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Order"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "Name":
                fieldValue = mOrders[mRecordIndex].Name;
                return true;
            case "Quantity":
                fieldValue = mOrders[mRecordIndex].Quantity;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    // Return null because we haven't any child elements for this sort of object.
    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        return null;
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mOrders.Count); }
    }

    private readonly OrderList mOrders;
    private int mRecordIndex;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.ExecuteWithRegions Overload List


MailMerge.ExecuteWithRegions Method (IMailMergeDataSourceRoot)

Performs a mail merge from a custom data source with mail merge regions.

[Visual Basic]
Overloads Public Sub ExecuteWithRegions( _
ByVal dataSourceRoot As IMailMergeDataSourceRoot _
)
[C#]
public void ExecuteWithRegions(
IMailMergeDataSourceRoot dataSourceRoot
);

Parameters

dataSourceRoot
An object that implements the custom mail merge data source root interface.

Remarks

Use this method to fill mail merge fields in the document with values from any custom data source such as an XML file or collections of business objects. You need to write your own classes that implement the IMailMergeDataSourceRoot and IMailMergeDataSource interfaces.

You can use this method only when IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

Example

Performs mail merge from a custom data source with master-detail data.

[C#]

public void MailMergeCustomDataSourceRoot()
{
    // Create a document with two mail merge regions named "Washington" and "Seattle"
    Document doc = CreateSourceDocumentWithMailMergeRegions(new string[] { "Washington", "Seattle" });

    // Create two data sources
    EmployeeList employeesWashingtonBranch = new EmployeeList();
    employeesWashingtonBranch.Add(new Employee("John Doe", "Sales"));
    employeesWashingtonBranch.Add(new Employee("Jane Doe", "Management"));

    EmployeeList employeesSeattleBranch = new EmployeeList();
    employeesSeattleBranch.Add(new Employee("John Cardholder", "Management"));
    employeesSeattleBranch.Add(new Employee("Joe Bloggs", "Sales"));

    // Register our data sources by name in a data source root
    DataSourceRoot sourceRoot = new DataSourceRoot();
    sourceRoot.RegisterSource("Washington", new EmployeeListMailMergeSource(employeesWashingtonBranch));
    sourceRoot.RegisterSource("Seattle", new EmployeeListMailMergeSource(employeesSeattleBranch));

    // Since we have consecutive mail merge regions, we would normally have to perform two mail merges
    // However, one mail merge source data root call every relevant data source and merge automatically
    doc.MailMerge.ExecuteWithRegions(sourceRoot);

    doc.Save(ArtifactsDir + "MailMerge.MailMergeCustomDataSourceRoot.docx");
}

/// <summary>
/// Create document that contains consecutive mail merge regions, with names designated by the input array, for a data table of employees
/// </summary>
private Document CreateSourceDocumentWithMailMergeRegions(string[] regions)
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    foreach (string s in regions)
    {
        builder.Writeln("\n" + s + " branch: ");
        builder.InsertField(" MERGEFIELD TableStart:" + s);
        builder.InsertField(" MERGEFIELD FullName");
        builder.Write(", ");
        builder.InsertField(" MERGEFIELD Department");
        builder.InsertField(" MERGEFIELD TableEnd:" + s);
    }

    return doc;
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
private class Employee
{
    public Employee(string aFullName, string aDepartment)
    {
        FullName = aFullName;
        Department = aDepartment;
    }

    public string FullName { get; }
    public string Department { get; }
}

/// <summary>
/// An example of a typed collection that contains your "data" objects.
/// </summary>
private class EmployeeList : ArrayList
{
    public new Employee this[int index]
    {
        get { return (Employee)base[index]; }
        set { base[index] = value; }
    }
}

/// <summary>
/// Data source root that can be passed directly into a mail merge which can register and contain many child data sources
/// These sources must all implement IMailMergeDataSource, and are registered and differentiated by a name
/// which corresponds to a mail merge region that will read the respective data
/// </summary>
private class DataSourceRoot : IMailMergeDataSourceRoot
{
    Dictionary<string, EmployeeListMailMergeSource> sources = new Dictionary<string, EmployeeListMailMergeSource>();

    public IMailMergeDataSource GetDataSource(string tableName)
    {
        EmployeeListMailMergeSource source = sources[tableName];
        source.Reset();
        return sources[tableName];
    }

    public void RegisterSource(string sourceName, EmployeeListMailMergeSource source)
    {
        sources.Add(sourceName, source);
    }
}

/// <summary>
/// Custom mail merge data source
/// </summary>
private class EmployeeListMailMergeSource : IMailMergeDataSource
{
    public EmployeeListMailMergeSource(EmployeeList employees)
    {
        mEmployees = employees;
        mRecordIndex = -1;
    }

    /// <summary>
    /// A standard implementation for moving to a next record in a collection.
    /// </summary>
    public bool MoveNext()
    {
        if (!IsEof)
            mRecordIndex++;

        return (!IsEof);
    }

    private bool IsEof
    {
        get { return (mRecordIndex >= mEmployees.Count); }
    }

    public void Reset()
    {
        mRecordIndex = -1;
    }

    /// <summary>
    /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    /// </summary>
    public string TableName
    {
        get { return "Employees"; }
    }

    /// <summary>
    /// Aspose.Words calls this method to get a value for every data field.
    /// </summary>
    public bool GetValue(string fieldName, out object fieldValue)
    {
        switch (fieldName)
        {
            case "FullName":
                fieldValue = mEmployees[mRecordIndex].FullName;
                return true;
            case "Department":
                fieldValue = mEmployees[mRecordIndex].Department;
                return true;
            default:
                // A field with this name was not found,
                // return false to the Aspose.Words mail merge engine.
                fieldValue = null;
                return false;
        }
    }

    /// <summary>
    /// Child data sources are for nested mail merges
    /// </summary>
    public IMailMergeDataSource GetChildDataSource(string tableName)
    {
        throw new System.NotImplementedException();
    }

    private readonly EmployeeList mEmployees;
    private int mRecordIndex;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.ExecuteWithRegions Overload List


MailMerge.ExecuteWithRegions Method (DataSet)

Performs mail merge from a DataSet into a document with mail merge regions.

[Visual Basic]
Overloads Public Sub ExecuteWithRegions( _
ByVal dataSet As DataSet _
)
[C#]
public void ExecuteWithRegions(
DataSet dataSet
);

Parameters

dataSet
DataSet that contains data to be inserted into mail merge fields.

Remarks

Use this method to perform mail merge from one or more tables into repeatable mail merge regions in the document. The mail merge regions inside the document will dynamically grow to accommodate records in the corresponding tables.

Every table in the DataSet must have a name.

The document must have mail merge regions defined with names that refer to the tables in the DataSet.

To specify a mail merge region in the document you need to insert two mail merge fields to mark beginning and end of the mail merge region.

All document content that is included inside a mail merge region will be automatically repeated for every record in the DataTable.

To mark beginning of a mail merge region insert a MERGEFIELD with name TableStart:MyTable, where MyTable corresponds to one of the table names in your DataSet.

To mark the end of the mail merge region insert another MERGEFIELD with name TableEnd:MyTable.

To insert a MERGEFIELD in Word use Insert/Field command and select MergeField then type the name of the field.

The TableStart and TableEnd fields must be inside the same section in your document.

If used inside a table, TableStart and TableEnd must be inside the same row in the table.

Mail merge regions in a document should be well formed (there always needs to be a pair of matching TableStart and TableEnd merge fields with the same table name).

Example

Shows how to create a nested mail merge with regions with data from a data set with two related tables.

[C#]

[Test]
public void ExecuteWithRegionsNested()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Create a MERGEFIELD with a value of "TableStart:Customers"
    // Normally, MERGEFIELDs specify the name of the column that they take row data from
    // "TableStart:Customers" however means that we are starting a mail merge region which belongs to a table called "Customers"
    // This will start the outer region and an "TableEnd:Customers" MERGEFIELD will signify its end
    builder.InsertField(" MERGEFIELD TableStart:Customers");

    // Data from rows of the "CustomerName" column of the "Customers" table will go in this MERGEFIELD
    builder.Write("Orders for ");
    builder.InsertField(" MERGEFIELD CustomerName");
    builder.Write(":");

    // Create column headers for a table which will contain values from the second inner region
    builder.StartTable();
    builder.InsertCell();
    builder.Write("Item");
    builder.InsertCell();
    builder.Write("Quantity");
    builder.EndRow();

    // We have a second data table called "Orders", which has a many-to-one relationship with "Customers", related by a "CustomerID" column
    // We will start this inner mail merge region over which the "Orders" table will preside,
    // which will iterate over the "Orders" table once for each merge of the outer "Customers" region, picking up rows with the same CustomerID value
    builder.InsertCell();
    builder.InsertField(" MERGEFIELD TableStart:Orders");
    builder.InsertField(" MERGEFIELD ItemName");
    builder.InsertCell();
    builder.InsertField(" MERGEFIELD Quantity");

    // End the inner region
    // One stipulation of using regions and tables is that the opening and closing of a mail merge region must only happen over one row of a document's table
    builder.InsertField(" MERGEFIELD TableEnd:Orders");
    builder.EndTable();

    // End the outer region
    builder.InsertField(" MERGEFIELD TableEnd:Customers");

    DataSet customersAndOrders = CreateDataSet();
    doc.MailMerge.ExecuteWithRegions(customersAndOrders);

    doc.Save(ArtifactsDir + "MailMerge.ExecuteWithRegionsNested.docx");
}

/// <summary>
/// Generates a data set which has two data tables named "Customers" and "Orders",
/// with a one-to-many relationship between the former and latter on the "CustomerID" column
/// </summary>
private DataSet CreateDataSet()
{
    // Create the outer mail merge
    DataTable tableCustomers = new DataTable("Customers");
    tableCustomers.Columns.Add("CustomerID");
    tableCustomers.Columns.Add("CustomerName");
    tableCustomers.Rows.Add(new object[] { 1, "John Doe" });
    tableCustomers.Rows.Add(new object[] { 2, "Jane Doe" });

    // Create the table for the inner merge
    DataTable tableOrders = new DataTable("Orders");
    tableOrders.Columns.Add("CustomerID");
    tableOrders.Columns.Add("ItemName");
    tableOrders.Columns.Add("Quantity");
    tableOrders.Rows.Add(new object[] { 1, "Hawaiian", 2 });
    tableOrders.Rows.Add(new object[] { 2, "Pepperoni", 1 });
    tableOrders.Rows.Add(new object[] { 2, "Chicago", 1 });

    // Add both tables to a data set
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(tableCustomers);
    dataSet.Tables.Add(tableOrders);

    // The "CustomerID" column, also the primary key of the customers table is the foreign key for the Orders table
    dataSet.Relations.Add(tableCustomers.Columns["CustomerID"], tableOrders.Columns["CustomerID"]);

    return dataSet;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.ExecuteWithRegions Overload List


MailMerge.ExecuteWithRegions Method (DataTable)

Performs mail merge from a DataTable into the document with mail merge regions.

[Visual Basic]
Overloads Public Sub ExecuteWithRegions( _
ByVal dataTable As DataTable _
)
[C#]
public void ExecuteWithRegions(
DataTable dataTable
);

Parameters

dataTable
Data source for the mail merge operation. The table must have its TableName property set.

Remarks

The document must have a mail merge region defined with name that matches DataTable.TableName.

If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.

Example

Shows how to use regions to execute two separate mail merges in one document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// If we want to perform two consecutive mail merges on one document while taking data from two tables
// that are related to each other in any way, we can separate the mail merges with regions
// A mail merge region starts and ends with "TableStart:[RegionName]" and "TableEnd:[RegionName]" MERGEFIELDs
// These regions are separate for unrelated data, while they can be nested for hierarchical data
builder.Writeln("\tCities: ");
builder.InsertField(" MERGEFIELD TableStart:Cities");
builder.InsertField(" MERGEFIELD Name");
builder.InsertField(" MERGEFIELD TableEnd:Cities");
builder.InsertParagraph();

// Both MERGEFIELDs refer to a same column name, but values for each will come from different data tables
builder.Writeln("\tFruit: ");
builder.InsertField(" MERGEFIELD TableStart:Fruit");
builder.InsertField(" MERGEFIELD Name");
builder.InsertField(" MERGEFIELD TableEnd:Fruit");

// Create two data tables that aren't linked or related in any way which we still want in the same document
DataTable tableCities = new DataTable("Cities");
tableCities.Columns.Add("Name");
tableCities.Rows.Add(new object[] { "Washington" });
tableCities.Rows.Add(new object[] { "London" });
tableCities.Rows.Add(new object[] { "New York" });

DataTable tableFruit = new DataTable("Fruit");
tableFruit.Columns.Add("Name");
tableFruit.Rows.Add(new object[] { "Cherry"});
tableFruit.Rows.Add(new object[] { "Apple" });
tableFruit.Rows.Add(new object[] { "Watermelon" });
tableFruit.Rows.Add(new object[] { "Banana" });

// We will need to run one mail merge per table
// This mail merge will populate the MERGEFIELDs in the "Cities" range, while leaving the fields in "Fruit" empty
doc.MailMerge.ExecuteWithRegions(tableCities);

// Run a second merge for the "Fruit" table
// We can use a DataView to sort or filter values of a DataTable before it is merged
DataView dv = new DataView(tableFruit);
dv.Sort = "Name ASC";
doc.MailMerge.ExecuteWithRegions(dv);

doc.Save(ArtifactsDir + "MailMerge.ExecuteWithRegionsConcurrent.docx");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.ExecuteWithRegions Overload List


MailMerge.ExecuteWithRegions Method (DataView)

Performs mail merge from a DataView into the document with mail merge regions.

[Visual Basic]
Overloads Public Sub ExecuteWithRegions( _
ByVal dataView As DataView _
)
[C#]
public void ExecuteWithRegions(
DataView dataView
);

Parameters

dataView
Data source for the mail merge operation. The source table of the DataView must have its TableName property set.

Remarks

This method is useful if you retrieve data into a DataTable but then need to apply a filter or sort before the mail merge.

The document must have a mail merge region defined with name that matches DataView.Table.TableName.

If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.

Example

Shows how to use regions to execute two separate mail merges in one document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// If we want to perform two consecutive mail merges on one document while taking data from two tables
// that are related to each other in any way, we can separate the mail merges with regions
// A mail merge region starts and ends with "TableStart:[RegionName]" and "TableEnd:[RegionName]" MERGEFIELDs
// These regions are separate for unrelated data, while they can be nested for hierarchical data
builder.Writeln("\tCities: ");
builder.InsertField(" MERGEFIELD TableStart:Cities");
builder.InsertField(" MERGEFIELD Name");
builder.InsertField(" MERGEFIELD TableEnd:Cities");
builder.InsertParagraph();

// Both MERGEFIELDs refer to a same column name, but values for each will come from different data tables
builder.Writeln("\tFruit: ");
builder.InsertField(" MERGEFIELD TableStart:Fruit");
builder.InsertField(" MERGEFIELD Name");
builder.InsertField(" MERGEFIELD TableEnd:Fruit");

// Create two data tables that aren't linked or related in any way which we still want in the same document
DataTable tableCities = new DataTable("Cities");
tableCities.Columns.Add("Name");
tableCities.Rows.Add(new object[] { "Washington" });
tableCities.Rows.Add(new object[] { "London" });
tableCities.Rows.Add(new object[] { "New York" });

DataTable tableFruit = new DataTable("Fruit");
tableFruit.Columns.Add("Name");
tableFruit.Rows.Add(new object[] { "Cherry"});
tableFruit.Rows.Add(new object[] { "Apple" });
tableFruit.Rows.Add(new object[] { "Watermelon" });
tableFruit.Rows.Add(new object[] { "Banana" });

// We will need to run one mail merge per table
// This mail merge will populate the MERGEFIELDs in the "Cities" range, while leaving the fields in "Fruit" empty
doc.MailMerge.ExecuteWithRegions(tableCities);

// Run a second merge for the "Fruit" table
// We can use a DataView to sort or filter values of a DataTable before it is merged
DataView dv = new DataView(tableFruit);
dv.Sort = "Name ASC";
doc.MailMerge.ExecuteWithRegions(dv);

doc.Save(ArtifactsDir + "MailMerge.ExecuteWithRegionsConcurrent.docx");

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.ExecuteWithRegions Overload List


MailMerge.ExecuteWithRegions Method (IDataReader, String)

Performs mail merge from IDataReader into the document with mail merge regions.

[Visual Basic]
Overloads Public Sub ExecuteWithRegions( _
ByVal dataReader As IDataReader, _
ByVal tableName As String _
)
[C#]
public void ExecuteWithRegions(
IDataReader dataReader,
string tableName
);

Parameters

dataReader
Source of the data records for mail merge such as OleDbDataReader or SqlDataReader.
tableName
Name of the mail merge region in the document to populate.

Remarks

You can pass SqlDataReader or OleDbDataReader object into this method as a parameter because they both implemented IDataReader interface.

Example

Shows how to insert images stored in a database BLOB field into a report.

[C#]

Document doc = new Document(MyDir + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();

    // Open a database connection.
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Open the data reader. It needs to be in the normal mode that reads all record at once.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
    IDataReader dataReader = cmd.ExecuteReader();

    // Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");

    // Close the database.
    conn.Close();

    doc.Save(ArtifactsDir + "MailMerge.MergeImage.doc");
}

private class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }

    /// <summary>
    /// This is called when mail merge engine encounters Image:XXX merge field in the document.
    /// You have a chance to return an Image object, file name or a stream that contains the image.
    /// </summary>
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // The field value is a byte array, just cast it and create a stream on it.
        MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
        // Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream;
    }
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.ExecuteWithRegions Overload List


MailMerge.ExecuteWithRegionsADO Method

Performs mail merge from an ADO Recordset object into the document with mail merge regions.

[Visual Basic]
Public Sub ExecuteWithRegionsADO( _
ByVal recordset As Object, _
ByVal tableName As String _
)
[C#]
public void ExecuteWithRegionsADO(
object recordset,
string tableName
);

Parameters

recordset
ADO Recordset or Record object.
tableName
Name of the mail merge region in the document to populate.

Remarks

This method is useful when you intend to use Aspose.Words classes as COM objects from unmanaged code such as an application built using ASP or Visual Basic 6.0.

For more information see description of MailMerge.ExecuteWithRegions(DataTable).

Example

[VBScript]

 Dim RS
 Set RS = CreateObject("ADODB.Recordset")
 RS.Open _
     "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = 10444 ORDER BY ProductID", _
     "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb"

 Dim Helper
 Set Helper = CreateObject("Aspose.Words.ComHelper")

 Dim Doc
 Set Doc = Helper.Open("Invoice.doc")

 Doc.MailMerge.ExecuteWithRegionsADO RS, "OrderDetails"
 Doc.Save "Invoice Out VBScript.doc"
Shows how to run a mail merge with regions, compiled with data from an ADO dataset.
[C#]

[Test]
public void ExecuteWithRegionsADO()
{
    // Create a document that will be merged
    Document doc = CreateSourceDocADOMailMergeWithRegions();

    // To work with ADO DataSets, we need to add a reference to the Microsoft ActiveX Data Objects library,
    // which is included in the .NET distribution and stored in "adodb.dll", then create a connection
    ADODB.Connection connection = new ADODB.Connection();

    // Create a connection string which points to the "Northwind" database file in our local file system and open a connection
    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DatabaseDir + "Northwind.mdb";
    connection.Open(connectionString);

    // Create a record set
    ADODB.Recordset recordset = new ADODB.Recordset();

    // Create an SQL query that fetches data with column names that are suitable for our first mail merge region, then populate our record set with the data
    string command = @"SELECT FirstName, LastName, City FROM Employees";
    recordset.Open(command, connection);

    // Run a mail merge on just the first region, filling its MERGEFIELDS with data from the ADO record set
    doc.MailMerge.ExecuteWithRegionsADO(recordset, "MergeRegion1");

    // Close the record set and reopen it with data from another SQL query
    recordset.Close();
    command = @"SELECT * FROM Customers";
    recordset.Open(command, connection);

    // Run a mail merge on the second region and save the document
    doc.MailMerge.ExecuteWithRegionsADO(recordset, "MergeRegion2");

    doc.Save(ArtifactsDir + "MailMerge.ExecuteWithRegionsADO.docx");
}

/// <summary>
/// Create a blank document and use MERGEFIELDS to create two sequential mail merge regions with TableStart/TableEnd tags
/// </summary>
private Document CreateSourceDocADOMailMergeWithRegions()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // First mail merge region
    builder.Writeln("\tEmployees: ");
    builder.InsertField(" MERGEFIELD TableStart:MergeRegion1");
    builder.InsertField(" MERGEFIELD FirstName");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD LastName");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD City");
    builder.InsertField(" MERGEFIELD TableEnd:MergeRegion1");
    builder.InsertParagraph();

    // Second mail merge region
    builder.Writeln("\tCustomers: ");
    builder.InsertField(" MERGEFIELD TableStart:MergeRegion2");
    builder.InsertField(" MERGEFIELD ContactName");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Address");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD City");
    builder.InsertField(" MERGEFIELD TableEnd:MergeRegion2");

    return doc;
}

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMerge.GetFieldNames Method

Returns a collection of mail merge field names available in the document.

[Visual Basic]
Public Function GetFieldNames() As String()
[C#]
public string[] GetFieldNames();

Remarks

Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

A new string[] array is created on every call.

Includes "mustache" field names if UseNonMergeFields is true.

Example

Shows how to get names of all merge fields in a document.

[C#]

String[] fieldNames = doc.MailMerge.GetFieldNames();

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


GetFieldNamesForRegion Method

Aspose.Words

MailMerge.GetFieldNamesForRegion Method

Get mail merge field names from the region.

Overload List

Returns a collection of mail merge field names available in the region.

public string[] GetFieldNamesForRegion(string);

Returns a collection of mail merge field names available in the region.

public string[] GetFieldNamesForRegion(string,int);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMerge.GetFieldNamesForRegion Method (String)

Returns a collection of mail merge field names available in the region.

[Visual Basic]
Overloads Public Function GetFieldNamesForRegion( _
ByVal regionName As String _
) As String()
[C#]
public string[] GetFieldNamesForRegion(
string regionName
);

Parameters

regionName
Region name (case-insensitive).

Remarks

Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

If document contains multiple regions with the same name the very first region is processed.

A new string array is created on every call.

Example

Shows how to create, list and read mail merge regions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// These tags, which go inside MERGEFIELDs, denote the strings that signify the starts and ends of mail merge regions
Assert.AreEqual("TableStart", doc.MailMerge.RegionStartTag);
Assert.AreEqual("TableEnd", doc.MailMerge.RegionEndTag);

// By using these tags, we will start and end a "MailMergeRegion1", which will contain MERGEFIELDs for two columns
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column1");
builder.Write(", ");
builder.InsertField(" MERGEFIELD Column2");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// We can keep track of merge regions and their columns by looking at these collections
IList<MailMergeRegionInfo> regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(1, regions.Count);
Assert.AreEqual("MailMergeRegion1", regions[0].Name);

string[] mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1");
Assert.AreEqual("Column1", mergeFieldNames[0]);
Assert.AreEqual("Column2", mergeFieldNames[1]);

// Insert a region with the same name as an existing region, which will make it a duplicate
builder.InsertParagraph(); // A single row/paragraph cannot be shared by multiple regions
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column3");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// Regions that share the same name are still accounted for and can be accessed by index
regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(2, regions.Count);

mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1", 1);
Assert.AreEqual("Column3", mergeFieldNames[0]);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.GetFieldNamesForRegion Overload List


MailMerge.GetFieldNamesForRegion Method (String, Int32)

Returns a collection of mail merge field names available in the region.

[Visual Basic]
Overloads Public Function GetFieldNamesForRegion( _
ByVal regionName As String, _
ByVal regionIndex As Integer _
) As String()
[C#]
public string[] GetFieldNamesForRegion(
string regionName,
int regionIndex
);

Parameters

regionName
Region name (case-insensitive).
regionIndex
Region index (zero-based).

Remarks

Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

If document contains multiple regions with the same name the Nth region (zero-based) is processed.

A new string array is created on every call.

Example

Shows how to create, list and read mail merge regions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// These tags, which go inside MERGEFIELDs, denote the strings that signify the starts and ends of mail merge regions
Assert.AreEqual("TableStart", doc.MailMerge.RegionStartTag);
Assert.AreEqual("TableEnd", doc.MailMerge.RegionEndTag);

// By using these tags, we will start and end a "MailMergeRegion1", which will contain MERGEFIELDs for two columns
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column1");
builder.Write(", ");
builder.InsertField(" MERGEFIELD Column2");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// We can keep track of merge regions and their columns by looking at these collections
IList<MailMergeRegionInfo> regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(1, regions.Count);
Assert.AreEqual("MailMergeRegion1", regions[0].Name);

string[] mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1");
Assert.AreEqual("Column1", mergeFieldNames[0]);
Assert.AreEqual("Column2", mergeFieldNames[1]);

// Insert a region with the same name as an existing region, which will make it a duplicate
builder.InsertParagraph(); // A single row/paragraph cannot be shared by multiple regions
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column3");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// Regions that share the same name are still accounted for and can be accessed by index
regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(2, regions.Count);

mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1", 1);
Assert.AreEqual("Column3", mergeFieldNames[0]);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace | MailMerge.GetFieldNamesForRegion Overload List


MailMerge.GetRegionsByName Method

Returns a collection of mail merge regions with the specified name.

[Visual Basic]
Public Function GetRegionsByName( _
ByVal regionName As String _
) As IList(Of MailMergeRegionInfo)
[C#]
public IList<MailMergeRegionInfo> GetRegionsByName(
string regionName
);

Parameters

regionName
Region name (case-insensitive).

Return Value

The list of regions.

Example

Shows how to create, list and read mail merge regions.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// These tags, which go inside MERGEFIELDs, denote the strings that signify the starts and ends of mail merge regions
Assert.AreEqual("TableStart", doc.MailMerge.RegionStartTag);
Assert.AreEqual("TableEnd", doc.MailMerge.RegionEndTag);

// By using these tags, we will start and end a "MailMergeRegion1", which will contain MERGEFIELDs for two columns
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column1");
builder.Write(", ");
builder.InsertField(" MERGEFIELD Column2");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// We can keep track of merge regions and their columns by looking at these collections
IList<MailMergeRegionInfo> regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(1, regions.Count);
Assert.AreEqual("MailMergeRegion1", regions[0].Name);

string[] mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1");
Assert.AreEqual("Column1", mergeFieldNames[0]);
Assert.AreEqual("Column2", mergeFieldNames[1]);

// Insert a region with the same name as an existing region, which will make it a duplicate
builder.InsertParagraph(); // A single row/paragraph cannot be shared by multiple regions
builder.InsertField(" MERGEFIELD TableStart:MailMergeRegion1");
builder.InsertField(" MERGEFIELD Column3");
builder.InsertField(" MERGEFIELD TableEnd:MailMergeRegion1");

// Regions that share the same name are still accounted for and can be accessed by index
regions = doc.MailMerge.GetRegionsByName("MailMergeRegion1");
Assert.AreEqual(2, regions.Count);

mergeFieldNames = doc.MailMerge.GetFieldNamesForRegion("MailMergeRegion1", 1);
Assert.AreEqual("Column3", mergeFieldNames[0]);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMerge.GetRegionsHierarchy Method

Returns a full hierarchy of regions (with fields) available in the document.

[Visual Basic]
Public Function GetRegionsHierarchy() As MailMergeRegionInfo
[C#]
public MailMergeRegionInfo GetRegionsHierarchy();

Return Value

Regions' hierarchy.

Remarks

Hierarchy is returned in the form of the MailMergeRegionInfo class.

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMerge Class | Aspose.Words.MailMerging Namespace


MailMergeCleanupOptions Enumeration

Specifies options that determine what items are removed during mail merge.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum MailMergeCleanupOptions
[C#]
public enum MailMergeCleanupOptions

Example

Shows how to automatically remove unmerged merge fields during mail merge.

[C#]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedFields;
Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document.
[C#]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
Shows how to instruct the mail merge engine to remove any containing fields from around a merge field during mail merge.
[C#]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;

Members

Member Name | Description | Value
None | Specifies a default value. | 0
RemoveEmptyParagraphs | Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document. When this option is set, paragraphs which contain region start and end merge fields which are otherwise empty are also removed. | 1
RemoveUnusedRegions | Specifies whether unused mail merge regions should be removed from the document. This option applies only to mail merge with regions. | 2
RemoveUnusedFields | Specifies whether unused merge fields should be removed from the document. | 4
RemoveContainingFields | Specifies whether fields that contain merge fields (for example, IFs) should be removed from the document if the nested merge fields are removed. | 8
RemoveStaticFields | Specifies whether static fields should be removed from the document. Static fields are fields, which results remain the same upon any document change. Fields, which do not store their results in a document and are calculated on the fly (like FieldListNum, FieldSymbol, etc.) are not considered to be static. | 16
RemoveEmptyTableRows | Specifies whether empty rows that contain mail merge regions should be removed from the document. | 32

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.MailMerging Namespace


MailMergeRegionInfo Class

Contains information about a mail merge region.

For a list of all members of this type, see MailMergeRegionInfo Members.

System.Object
Aspose.Words.MailMerging.MailMergeRegionInfo

[Visual Basic]
Public Class MailMergeRegionInfo
[C#]
public class MailMergeRegionInfo

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MailMergeRegionInfo Members | Aspose.Words.MailMerging Namespace


MailMergeRegionInfo Members

MailMergeRegionInfo overview

Public Instance Properties

EndField | Returns an end field for the region.
Fields | Returns a list of child fields.
Level | Returns the nesting level for the region.
Name | Returns the name of region.
Regions | Returns a list of child regions.
StartField | Returns a start field for the region.

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


MailMergeRegionInfo Properties

The properties of the MailMergeRegionInfo class are listed below. For a complete list of MailMergeRegionInfo class members, see the MailMergeRegionInfo Members topic.

Public Instance Properties

EndField | Returns an end field for the region.
Fields | Returns a list of child fields.
Level | Returns the nesting level for the region.
Name | Returns the name of region.
Regions | Returns a list of child regions.
StartField | Returns a start field for the region.

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


EndField Property

Aspose.Words

MailMergeRegionInfo.EndField Property

Returns an end field for the region.

[Visual Basic]
Public ReadOnly Property EndField As FieldMergeField
[C#]
public FieldMergeField EndField {get;}

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


Fields Property

Aspose.Words

MailMergeRegionInfo.Fields Property

Returns a list of child fields.

[Visual Basic]
Public ReadOnly Property Fields As Field}
[C#]
public Field} Fields {get;}

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


Level Property

Aspose.Words

MailMergeRegionInfo.Level Property

Returns the nesting level for the region.

[Visual Basic]
Public ReadOnly Property Level As Integer
[C#]
public int Level {get;}

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


Name Property

Aspose.Words

MailMergeRegionInfo.Name Property

Returns the name of region.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


Regions Property

Aspose.Words

MailMergeRegionInfo.Regions Property

Returns a list of child regions.

[Visual Basic]
Public ReadOnly Property Regions As MailMergeRegionInfo}
[C#]
public MailMergeRegionInfo} Regions {get;}

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


StartField Property

Aspose.Words

MailMergeRegionInfo.StartField Property

Returns a start field for the region.

[Visual Basic]
Public ReadOnly Property StartField As FieldMergeField
[C#]
public FieldMergeField StartField {get;}

Example

Shows how to get MailMergeRegionInfo and work with it

[C#]

Document doc = new Document(MyDir + "MailMerge.TestRegionsHierarchy.doc");

//Returns a full hierarchy of regions (with fields) available in the document.
MailMergeRegionInfo regionInfo = doc.MailMerge.GetRegionsHierarchy();

//Get top regions in the document
IList<MailMergeRegionInfo> topRegions = regionInfo.Regions;
Assert.AreEqual(2, topRegions.Count);
Assert.AreEqual("Region1", topRegions[0].Name);
Assert.AreEqual("Region2", topRegions[1].Name);
Assert.AreEqual(1, topRegions[0].Level);
Assert.AreEqual(1, topRegions[1].Level);

//Get nested region in first top region
IList<MailMergeRegionInfo> nestedRegions = topRegions[0].Regions;
Assert.AreEqual(2, nestedRegions.Count);
Assert.AreEqual("NestedRegion1", nestedRegions[0].Name);
Assert.AreEqual("NestedRegion2", nestedRegions[1].Name);
Assert.AreEqual(2, nestedRegions[0].Level);
Assert.AreEqual(2, nestedRegions[1].Level);

//Get field list in first top region
IList<Field> fieldList = topRegions[0].Fields;
Assert.AreEqual(4, fieldList.Count);

FieldMergeField startFieldMergeField = nestedRegions[0].StartField;
Assert.AreEqual("TableStart:NestedRegion1", startFieldMergeField.FieldName);

FieldMergeField endFieldMergeField = nestedRegions[0].EndField;
Assert.AreEqual("TableEnd:NestedRegion1", endFieldMergeField.FieldName);

See Also

MailMergeRegionInfo Class | Aspose.Words.MailMerging Namespace


MailMergeRtlCleanupMode Enumeration

Specifies how to handle Right-To-Left attributes of mail merge result text runs.

[Visual Basic]
Public Enum MailMergeRtlCleanupMode
[C#]
public enum MailMergeRtlCleanupMode

Members

Member Name | Description | Value
DontRemove | Preserves any Right-To-Left attributes of mail merge result text runs from being removed. This is the default Aspose.Word behavior, compatible with early versions. | 0
RemoveAll | Forces any Right-To-Left attributes of mail merge result text runs to be removed. This seems to be the default MS Word behavior. | 1
RemoveForLtrText | Forces Right-To-Left attributes of mail merge result text runs to be removed in case when text contents of these runs contain no Right-To-Left characters. | 2

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.MailMerging Namespace


MappedDataFieldCollection Class

Allows to automatically map between names of fields in your data source and names of mail merge fields in the document.

For a list of all members of this type, see MappedDataFieldCollection Members.

System.Object
Aspose.Words.MailMerging.MappedDataFieldCollection

[Visual Basic]
Public Class MappedDataFieldCollection
Implements IEnumerable`1([System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089),[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), IEnumerable
[C#]
public class MappedDataFieldCollection : 0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], IEnumerable

Remarks

This is implemented as a collection of string keys into string values. The keys are the names of mail merge fields in the document and the values are the names of fields in your data source.

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

Requirements

Namespace: Aspose.Words.MailMerging

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MappedDataFieldCollection Members | Aspose.Words.MailMerging Namespace | MailMerge | MappedDataFields


MappedDataFieldCollection Members

MappedDataFieldCollection overview

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets the name of the field in the data source associated with the specified mail merge field.

Public Instance Methods

Add | Adds a new field mapping.
Clear | Removes all elements from the collection.
ContainsKey | Determines whether a mapping from the specified field in the document exists in the collection.
ContainsValue | Determines whether a mapping from the specified field in the data source exists in the collection.
GetEnumerator | Returns a dictionary enumerator object that can be used to iterate over all items in the collection.
Remove | Removes a field mapping.

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace | MailMerge | MappedDataFields


MappedDataFieldCollection Properties

The properties of the MappedDataFieldCollection class are listed below. For a complete list of MappedDataFieldCollection class members, see the MappedDataFieldCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets the name of the field in the data source associated with the specified mail merge field.

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace | MailMerge | MappedDataFields


Count Property

Aspose.Words

MappedDataFieldCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


Item Property

Aspose.Words

MappedDataFieldCollection.Item Property

Gets or sets the name of the field in the data source associated with the specified mail merge field.

[Visual Basic]
Public Default Property Item( _
ByVal documentFieldName As String _
) As String
[C#]
public string this[
string documentFieldName
] {get; set;}

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


MappedDataFieldCollection Methods

The methods of the MappedDataFieldCollection class are listed below. For a complete list of MappedDataFieldCollection class members, see the MappedDataFieldCollection Members topic.

Public Instance Methods

Add | Adds a new field mapping.
Clear | Removes all elements from the collection.
ContainsKey | Determines whether a mapping from the specified field in the document exists in the collection.
ContainsValue | Determines whether a mapping from the specified field in the data source exists in the collection.
GetEnumerator | Returns a dictionary enumerator object that can be used to iterate over all items in the collection.
Remove | Removes a field mapping.

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace | MailMerge | MappedDataFields


MappedDataFieldCollection.Add Method

Adds a new field mapping.

[Visual Basic]
Public Sub Add( _
ByVal documentFieldName As String, _
ByVal dataSourceFieldName As String _
)
[C#]
public void Add(
string documentFieldName,
string dataSourceFieldName
);

Parameters

documentFieldName
Case-sensitive name of the mail merge field in the document.
dataSourceFieldName
Case-sensitive name of the field in the data source.

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


MappedDataFieldCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


MappedDataFieldCollection.ContainsKey Method

Determines whether a mapping from the specified field in the document exists in the collection.

[Visual Basic]
Public Function ContainsKey( _
ByVal documentFieldName As String _
) As Boolean
[C#]
public bool ContainsKey(
string documentFieldName
);

Parameters

documentFieldName
Case-sensitive name of the mail merge field in the document.

Return Value

True if item is found in the collection; otherwise, false.

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


MappedDataFieldCollection.ContainsValue Method

Determines whether a mapping from the specified field in the data source exists in the collection.

[Visual Basic]
Public Function ContainsValue( _
ByVal dataSourceFieldName As String _
) As Boolean
[C#]
public bool ContainsValue(
string dataSourceFieldName
);

Parameters

dataSourceFieldName
Case-sensitive name of the field in the data source.

Return Value

True if item is found in the collection; otherwise, false.

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


MappedDataFieldCollection.GetEnumerator Method

Returns a dictionary enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of KeyValuePair`2([System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089),[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089))) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


MappedDataFieldCollection.Remove Method

Removes a field mapping.

[Visual Basic]
Public Sub Remove( _
ByVal documentFieldName As String _
)
[C#]
public void Remove(
string documentFieldName
);

Parameters

documentFieldName
Case-sensitive name of the mail merge field in the document.

Example

Shows how to map data columns and MERGEFIELDs with different names so the data is transferred between them during a mail merge.

[C#]

public void MappedDataFieldCollection()
{
    // Create a document and table that we will merge
    Document doc = CreateSourceDocMappedDataFields();
    DataTable dataTable = CreateSourceTableMappedDataFields();

    // We have a column "Column2" in the data table that doesn't have a respective MERGEFIELD in the document
    // Also, we have a MERGEFIELD named "Column3" that does not exist as a column in the data source
    // If data from "Column2" is suitable for the "Column3" MERGEFIELD,
    // we can map that column name to the MERGEFIELD in the "MappedDataFields" key/value pair
    MappedDataFieldCollection mappedDataFields = doc.MailMerge.MappedDataFields;

    // A data source column name is linked to a MERGEFIELD name by adding an element like this
    mappedDataFields.Add("MergeFieldName", "DataSourceColumnName");

    // So, values from "Column2" will now go into MERGEFIELDs named "Column3" as well as "Column2", if there are any
    mappedDataFields.Add("Column3", "Column2");

    // The MERGEFIELD name is the "key" to the respective data source column name "value"
    Assert.AreEqual("DataSourceColumnName", mappedDataFields["MergeFieldName"]);
    Assert.True(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.True(mappedDataFields.ContainsValue("DataSourceColumnName"));

    // Now if we run this mail merge, the "Column3" MERGEFIELDs will take data from "Column2" of the table
    doc.MailMerge.Execute(dataTable);

    // We can count and iterate over the mapped columns/fields
    Assert.AreEqual(2, mappedDataFields.Count);

    using (IEnumerator<KeyValuePair<string, string>> enumerator = mappedDataFields.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            Console.WriteLine($"Column named {enumerator.Current.Value} is mapped to MERGEFIELDs named {enumerator.Current.Key}");
        }
    }

    // We can also remove some or all of the elements
    mappedDataFields.Remove("MergeFieldName");
    Assert.False(mappedDataFields.ContainsKey("MergeFieldName"));
    Assert.False(mappedDataFields.ContainsValue("DataSourceColumnName"));

    mappedDataFields.Clear();
    Assert.AreEqual(0, mappedDataFields.Count);

    // Removing the mapped key/value pairs has no effect on the document because the merge was already done with them in place
    doc.Save(ArtifactsDir + "MailMerge.MappedDataFieldCollection.docx");
}

/// <summary>
/// Create a document with 2 MERGEFIELDs, one of which does not have a corresponding column in the data table
/// </summary>
private Document CreateSourceDocMappedDataFields()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert two MERGEFIELDs that will accept data from that table
    builder.InsertField(" MERGEFIELD Column1");
    builder.Write(", ");
    builder.InsertField(" MERGEFIELD Column3");

    return doc;
}

/// <summary>
/// Create a data table with 2 columns, one of which does not have a corresponding MERGEFIELD in our source document
/// </summary>
private DataTable CreateSourceTableMappedDataFields()
{
    // Create a data table that will be used in a mail merge
    DataTable dataTable = new DataTable("MyTable");
    dataTable.Columns.Add("Column1");
    dataTable.Columns.Add("Column2");
    dataTable.Rows.Add(new object[] { "Value1", "Value2" });

    return dataTable;
}

See Also

MappedDataFieldCollection Class | Aspose.Words.MailMerging Namespace


Aspose.Words.Markup

Aspose.Words

Aspose.Words.Markup Namespace

The Aspose.Words.Markup namespace contains classes that represent customer defined semantics in a document: smart tags, custom XML and structured document tags (content controls).

Namespace hierarchy

Classes

Class | Description
CustomPart | Represents a custom (arbitrary content) part, that is not defined by the ISO/IEC 29500 standard.
CustomPartCollection | Represents a collection of CustomPart objects.
CustomXmlPart | Represents a Custom XML Data Storage Part (custom XML data within a package).
CustomXmlPartCollection | Represents a collection of Custom XML Parts. The items are CustomXmlPart objects.
CustomXmlProperty | Represents a single custom XML attribute or a smart tag property.
CustomXmlPropertyCollection | Represents a collection of custom XML attributes or smart tag properties.
CustomXmlSchemaCollection | A collection of strings that represent XML schemas that are associated with a custom XML part.
SdtListItem | This element specifies a single list item within a parent ComboBox or DropDownList structured document tag.
SdtListItemCollection | Provides access to SdtListItem elements of a structured document tag.
SmartTag | This element specifies the presence of a smart tag around one or more inline structures (runs, images, fields,etc.) within a paragraph.
StructuredDocumentTag | Represents a structured document tag (SDT or content control) in a document.
XmlMapping | Specifies the information that is used to establish a mapping between the parent structured document tag and an XML element stored within a custom XML data part in the document.

Enumerations

Enumeration | Description
MarkupLevel | Specifies the level in the document tree where a particular StructuredDocumentTag can occur.
SdtCalendarType | Specifies the possible types of calendars which can be used to specify CalendarType in an Office Open XML document.
SdtDateStorageFormat | Specifies how the date for a date SDT is stored/retrieved when the SDT is bound to an XML node in the document's data store.
SdtType | Specifies the type of a structured document tag (SDT) node.


CustomPart Class

Represents a custom (arbitrary content) part, that is not defined by the ISO/IEC 29500 standard.

For a list of all members of this type, see CustomPart Members.

System.Object
Aspose.Words.Markup.CustomPart

[Visual Basic]
Public Class CustomPart
[C#]
public class CustomPart

Remarks

This class represents an OOXML part that is a target of an "unknown relationship". All relationships not defined within ISO/IEC 29500 are considered "unknown relationships". Unknown relationships are permitted within an Office Open XML document provided that they conform to relationship markup guidelines.

Microsoft Word preserves custom parts during open/save cycles. Some additional info can be found here http://blogs.msdn.com/dmahugh/archive/2006/11/25/arbitrary-content-in-an-opc-package.aspx

Aspose.Words also roundtrips custom parts and in addition, allows to programmatically access such parts via the CustomPart and CustomPartCollection objects.

Do not confuse custom parts with Custom XML Data. Use CustomXmlPart if you need to access Custom XML Data.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomPart Members | Aspose.Words.Markup Namespace | CustomPartCollection | PackageCustomParts


CustomPart Members

CustomPart overview

Public Instance Constructors

CustomPart Constructor Initializes a new instance of the CustomPart class.

Public Instance Properties

ContentType | Specifies the content type of this custom part.
Data | Contains the data of this custom part.
IsExternal | False if this custom part is stored inside the OOXML package. True if this custom part is an external target.
Name | Gets or sets this part's absolute name within the OOXML package or the target URL.
RelationshipType | Gets or sets the relationship type from the parent part to this custom part.

Public Instance Methods

Clone Makes a "deep enough" copy of the object. Does not duplicate the bytes of the Data value.

See Also

CustomPart Class | Aspose.Words.Markup Namespace | CustomPartCollection | PackageCustomParts


CustomPart Constructor

Initializes a new instance of the CustomPart class.

[Visual Basic]
Public Sub New()
[C#]
public CustomPart();

See Also

CustomPart Class | Aspose.Words.Markup Namespace


CustomPart Properties

The properties of the CustomPart class are listed below. For a complete list of CustomPart class members, see the CustomPart Members topic.

Public Instance Properties

ContentType | Specifies the content type of this custom part.
Data | Contains the data of this custom part.
IsExternal | False if this custom part is stored inside the OOXML package. True if this custom part is an external target.
Name | Gets or sets this part's absolute name within the OOXML package or the target URL.
RelationshipType | Gets or sets the relationship type from the parent part to this custom part.

See Also

CustomPart Class | Aspose.Words.Markup Namespace | CustomPartCollection | PackageCustomParts


ContentType Property

Aspose.Words

CustomPart.ContentType Property

Specifies the content type of this custom part.

[Visual Basic]
Public Property ContentType As String
[C#]
public string ContentType {get; set;}

Remarks

This property is applicable only when IsExternal is false.

The default value is an empty string. A valid value must be a non-empty string.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPart Class | Aspose.Words.Markup Namespace


Data Property

Aspose.Words

CustomPart.Data Property

Contains the data of this custom part.

[Visual Basic]
Public Property Data As Byte()
[C#]
public byte[] Data {get; set;}

Remarks

This property is applicable only when IsExternal is false.

The default value is an empty byte array. The value cannot be null.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPart Class | Aspose.Words.Markup Namespace


IsExternal Property

Aspose.Words

CustomPart.IsExternal Property

False if this custom part is stored inside the OOXML package. True if this custom part is an external target.

[Visual Basic]
Public Property IsExternal As Boolean
[C#]
public bool IsExternal {get; set;}

Remarks

The default value is false.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPart Class | Aspose.Words.Markup Namespace | Name


Name Property

Aspose.Words

CustomPart.Name Property

Gets or sets this part's absolute name within the OOXML package or the target URL.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

Remarks

If the relationship target is internal, then this property is the absolute part name within the package. If the relationship target is external, then this property is the target URL.

The default value is an empty string. A valid value must be a non-empty string.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPart Class | Aspose.Words.Markup Namespace | IsExternal


RelationshipType Property

Aspose.Words

CustomPart.RelationshipType Property

Gets or sets the relationship type from the parent part to this custom part.

[Visual Basic]
Public Property RelationshipType As String
[C#]
public string RelationshipType {get; set;}

Remarks

The relationship type for a custom part must be "unknown" e.g. a custom relationship type, not one of the relationship types defined within ISO/IEC 29500.

The default value is an empty string. A valid value must be a non-empty string.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPart Class | Aspose.Words.Markup Namespace


CustomPart Methods

The methods of the CustomPart class are listed below. For a complete list of CustomPart class members, see the CustomPart Members topic.

Public Instance Methods

Clone Makes a "deep enough" copy of the object. Does not duplicate the bytes of the Data value.

See Also

CustomPart Class | Aspose.Words.Markup Namespace | CustomPartCollection | PackageCustomParts


CustomPart.Clone Method

Makes a "deep enough" copy of the object. Does not duplicate the bytes of the Data value.

[Visual Basic]
Public Function Clone() As CustomPart
[C#]
public CustomPart Clone();

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPart Class | Aspose.Words.Markup Namespace


CustomPartCollection Class

Represents a collection of CustomPart objects.

For a list of all members of this type, see CustomPartCollection Members.

System.Object
Aspose.Words.Markup.CustomPartCollection

[Visual Basic]
Public Class CustomPartCollection
Implements IEnumerable`1([Aspose.Words.Markup.CustomPart, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class CustomPartCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

You do not normally need to create instances of this class. You access custom parts related to the OOXML package via the PackageCustomParts property.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomPartCollection Members | Aspose.Words.Markup Namespace | CustomPart | PackageCustomParts


CustomPartCollection Members

CustomPartCollection overview

Public Instance Constructors

CustomPartCollection Constructor Initializes a new instance of the CustomPartCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item at the specified index.

Public Instance Methods

Add | Adds an item to the collection.
Clear | Removes all elements from the collection.
Clone | Makes a deep copy of this collection and its items.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes an item at the specified index.

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace | CustomPart | PackageCustomParts


CustomPartCollection Constructor

Initializes a new instance of the CustomPartCollection class.

[Visual Basic]
Public Sub New()
[C#]
public CustomPartCollection();

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomPartCollection Properties

The properties of the CustomPartCollection class are listed below. For a complete list of CustomPartCollection class members, see the CustomPartCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item at the specified index.

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace | CustomPart | PackageCustomParts


Count Property

Aspose.Words

CustomPartCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


Item Property

Aspose.Words

CustomPartCollection.Item Property

Gets or sets an item at the specified index.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As CustomPart
[C#]
public CustomPart this[
int index
] {get; set;}

Parameters

index
Zero-based index of the item.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomPartCollection Methods

The methods of the CustomPartCollection class are listed below. For a complete list of CustomPartCollection class members, see the CustomPartCollection Members topic.

Public Instance Methods

Add | Adds an item to the collection.
Clear | Removes all elements from the collection.
Clone | Makes a deep copy of this collection and its items.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes an item at the specified index.

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace | CustomPart | PackageCustomParts


CustomPartCollection.Add Method

Adds an item to the collection.

[Visual Basic]
Public Sub Add( _
ByVal part As CustomPart _
)
[C#]
public void Add(
CustomPart part
);

Parameters

part
The item to add.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomPartCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomPartCollection.Clone Method

Makes a deep copy of this collection and its items.

[Visual Basic]
Public Function Clone() As CustomPartCollection
[C#]
public CustomPartCollection Clone();

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomPartCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of CustomPart) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<CustomPart> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomPartCollection.RemoveAt Method

Removes an item at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to open a document with custom parts and access them.

[C#]

// Open a document that contains custom parts
// CustomParts are arbitrary content OOXML parts
// Not to be confused with Custom XML data which is represented by CustomXmlParts
// This part is internal, meaning it is contained inside the OOXML package
Document doc = new Document(MyDir + "Document.PackageCustomParts.docx");
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Clone the second part
CustomPart clonedPart = doc.PackageCustomParts[1].Clone();

// Add the clone to the collection
doc.PackageCustomParts.Add(clonedPart);

Assert.AreEqual(3, doc.PackageCustomParts.Count);

// Use an enumerator to print information about the contents of each part
using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Part index {index}:");
        Console.WriteLine($"\tName: {enumerator.Current.Name}");
        Console.WriteLine($"\tContentType: {enumerator.Current.ContentType}");
        Console.WriteLine($"\tRelationshipType: {enumerator.Current.RelationshipType}");
        if (enumerator.Current.IsExternal)
        {
            Console.WriteLine("\tSourced from outside the document");
        }
        else
        {
            Console.WriteLine($"\tSourced from within the document, length: {enumerator.Current.Data.Length} bytes");
        }
        index++;
    }
}

// Delete parts one at a time based on index
doc.PackageCustomParts.RemoveAt(2);
Assert.AreEqual(2, doc.PackageCustomParts.Count);

// Delete all parts
doc.PackageCustomParts.Clear();
Assert.AreEqual(0, doc.PackageCustomParts.Count);

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPart Class

Represents a Custom XML Data Storage Part (custom XML data within a package).

For a list of all members of this type, see CustomXmlPart Members.

System.Object
Aspose.Words.Markup.CustomXmlPart

[Visual Basic]
Public Class CustomXmlPart
[C#]
public class CustomXmlPart

Remarks

A DOCX or DOC document can contain one or more Custom XML Data Storage parts. Aspose.Words preserves and allows to create and extract Custom XML Data via the CustomXmlParts collection.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomXmlPart Members | Aspose.Words.Markup Namespace | CustomXmlParts | CustomXmlPartCollection


CustomXmlPart Members

CustomXmlPart overview

Public Instance Constructors

CustomXmlPart Constructor Initializes a new instance of the CustomXmlPart class.

Public Instance Properties

Data | Gets or sets the XML content of this Custom XML Data Storage Part.
Id | Gets or sets the string that identifies this custom XML part within an OOXML document.
Schemas | Specifies the set of XML schemas that are associated with this custom XML part.

Public Instance Methods

Clone Makes a "deep enough" copy of the object. Does not duplicate the bytes of the Data value.

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace | CustomXmlParts | CustomXmlPartCollection


CustomXmlPart Constructor

Initializes a new instance of the CustomXmlPart class.

[Visual Basic]
Public Sub New()
[C#]
public CustomXmlPart();

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace


CustomXmlPart Properties

The properties of the CustomXmlPart class are listed below. For a complete list of CustomXmlPart class members, see the CustomXmlPart Members topic.

Public Instance Properties

Data | Gets or sets the XML content of this Custom XML Data Storage Part.
Id | Gets or sets the string that identifies this custom XML part within an OOXML document.
Schemas | Specifies the set of XML schemas that are associated with this custom XML part.

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace | CustomXmlParts | CustomXmlPartCollection


Data Property

Aspose.Words

CustomXmlPart.Data Property

Gets or sets the XML content of this Custom XML Data Storage Part.

[Visual Basic]
Public Property Data As Byte()
[C#]
public byte[] Data {get; set;}

Remarks

The default value is an empty byte array. The value cannot be null.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace


Id Property

Aspose.Words

CustomXmlPart.Id Property

Gets or sets the string that identifies this custom XML part within an OOXML document.

[Visual Basic]
Public Property Id As String
[C#]
public string Id {get; set;}

Remarks

ISO/IEC 29500 specifies that this value is a GUID, but old versions of Microsoft Word allowed any string here. Aspose.Words does the same for ECMA-376 format. But note, that Microsoft Word Online fails to open a document created with a non-GUID value. So, a GUID is preferred value for this property.

A valid value must be an identifier that is unique among all custom XML data parts in this document.

The default value is an empty string. The value cannot be null.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace


Schemas Property

Aspose.Words

CustomXmlPart.Schemas Property

Specifies the set of XML schemas that are associated with this custom XML part.

[Visual Basic]
Public ReadOnly Property Schemas As CustomXmlSchemaCollection
[C#]
public CustomXmlSchemaCollection Schemas {get;}

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace


CustomXmlPart Methods

The methods of the CustomXmlPart class are listed below. For a complete list of CustomXmlPart class members, see the CustomXmlPart Members topic.

Public Instance Methods

Clone Makes a "deep enough" copy of the object. Does not duplicate the bytes of the Data value.

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace | CustomXmlParts | CustomXmlPartCollection


CustomXmlPart.Clone Method

Makes a "deep enough" copy of the object. Does not duplicate the bytes of the Data value.

[Visual Basic]
Public Function Clone() As CustomXmlPart
[C#]
public CustomXmlPart Clone();

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPart Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection Class

Represents a collection of Custom XML Parts. The items are CustomXmlPart objects.

For a list of all members of this type, see CustomXmlPartCollection Members.

System.Object
Aspose.Words.Markup.CustomXmlPartCollection

[Visual Basic]
Public Class CustomXmlPartCollection
Implements IEnumerable`1([Aspose.Words.Markup.CustomXmlPart, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class CustomXmlPartCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

You do not normally need to create instances of this class. You can access custom XML data stored in a document via the CustomXmlParts property.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomXmlPartCollection Members | Aspose.Words.Markup Namespace | CustomXmlPart | CustomXmlParts


CustomXmlPartCollection Members

CustomXmlPartCollection overview

Public Instance Constructors

CustomXmlPartCollection Constructor Initializes a new instance of the CustomXmlPartCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item at the specified index.

Public Instance Methods

Add | Overloaded. Adds an item to the collection.
Clear | Removes all elements from the collection.
Clone | Makes a deep copy of this collection and its items.
GetById | Finds and returns a custom XML part by its identifier.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes an item at the specified index.

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace | CustomXmlPart | CustomXmlParts


CustomXmlPartCollection Constructor

Initializes a new instance of the CustomXmlPartCollection class.

[Visual Basic]
Public Sub New()
[C#]
public CustomXmlPartCollection();

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection Properties

The properties of the CustomXmlPartCollection class are listed below. For a complete list of CustomXmlPartCollection class members, see the CustomXmlPartCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item at the specified index.

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace | CustomXmlPart | CustomXmlParts


Count Property

Aspose.Words

CustomXmlPartCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


Item Property

Aspose.Words

CustomXmlPartCollection.Item Property

Gets or sets an item at the specified index.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As CustomXmlPart
[C#]
public CustomXmlPart this[
int index
] {get; set;}

Parameters

index
Zero-based index of the item.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection Methods

The methods of the CustomXmlPartCollection class are listed below. For a complete list of CustomXmlPartCollection class members, see the CustomXmlPartCollection Members topic.

Public Instance Methods

Add | Overloaded. Adds an item to the collection.
Clear | Removes all elements from the collection.
Clone | Makes a deep copy of this collection and its items.
GetById | Finds and returns a custom XML part by its identifier.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes an item at the specified index.

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace | CustomXmlPart | CustomXmlParts


Add Method

Aspose.Words

CustomXmlPartCollection.Add Method

Adds an item to the collection.

Overload List

Adds an item to the collection.

public void Add(CustomXmlPart);

Creates a new XML part with the specified XML and adds it to the collection.

public CustomXmlPart Add(string,string);

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection.Add Method (CustomXmlPart)

Adds an item to the collection.

[Visual Basic]
Overloads Public Sub Add( _
ByVal part As CustomXmlPart _
)
[C#]
public void Add(
CustomXmlPart part
);

Parameters

part
The custom XML part to add.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace | CustomXmlPartCollection.Add Overload List


CustomXmlPartCollection.Add Method (String, String)

Creates a new XML part with the specified XML and adds it to the collection.

[Visual Basic]
Overloads Public Function Add( _
ByVal id As String, _
ByVal xml As String _
) As CustomXmlPart
[C#]
public CustomXmlPart Add(
string id,
string xml
);

Parameters

id
Identifier of a new custom XML part.
xml
XML data of the part.

Return Value

Created custom XML part.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace | CustomXmlPartCollection.Add Overload List


CustomXmlPartCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection.Clone Method

Makes a deep copy of this collection and its items.

[Visual Basic]
Public Function Clone() As CustomXmlPartCollection
[C#]
public CustomXmlPartCollection Clone();

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection.GetById Method

Finds and returns a custom XML part by its identifier.

[Visual Basic]
Public Function GetById( _
ByVal id As String _
) As CustomXmlPart
[C#]
public CustomXmlPart GetById(
string id
);

Parameters

id
Case-sensitive string that identifies the custom XML part.

Return Value

Returns null if a custom XML part with the specified identifier is not found.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of CustomXmlPart) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<CustomXmlPart> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection.RemoveAt Method

Removes an item at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlProperty Class

Represents a single custom XML attribute or a smart tag property.

For a list of all members of this type, see CustomXmlProperty Members.

System.Object
Aspose.Words.Markup.CustomXmlProperty

[Visual Basic]
Public Class CustomXmlProperty
[C#]
public class CustomXmlProperty

Remarks

Used as an item of a CustomXmlPropertyCollection collection.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomXmlProperty Members | Aspose.Words.Markup Namespace


CustomXmlProperty Members

CustomXmlProperty overview

Public Instance Constructors

CustomXmlProperty Constructor Initializes a new instance of this class.

Public Instance Properties

Name | Specifies the name of the custom XML attribute or smart tag property.
Uri | Gets or sets the namespace URI of the custom XML attribute or smart tag property.
Value | Gets or sets the value of the custom XML attribute or smart tag property.

See Also

CustomXmlProperty Class | Aspose.Words.Markup Namespace


CustomXmlProperty Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal name As String, _
ByVal uri As String, _
ByVal value As String _
)
[C#]
public CustomXmlProperty(
string name,
string uri,
string value
);

Parameters

name
The name of the property. Cannot be null.
uri
The namespace URI of the property. Cannot be null.
value
The value of the property. Cannot be null.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

CustomXmlProperty Class | Aspose.Words.Markup Namespace


CustomXmlProperty Properties

The properties of the CustomXmlProperty class are listed below. For a complete list of CustomXmlProperty class members, see the CustomXmlProperty Members topic.

Public Instance Properties

Name | Specifies the name of the custom XML attribute or smart tag property.
Uri | Gets or sets the namespace URI of the custom XML attribute or smart tag property.
Value | Gets or sets the value of the custom XML attribute or smart tag property.

See Also

CustomXmlProperty Class | Aspose.Words.Markup Namespace


Name Property

Aspose.Words

CustomXmlProperty.Name Property

Specifies the name of the custom XML attribute or smart tag property.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

CustomXmlProperty Class | Aspose.Words.Markup Namespace


Uri Property

Aspose.Words

CustomXmlProperty.Uri Property

Gets or sets the namespace URI of the custom XML attribute or smart tag property.

[Visual Basic]
Public Property Uri As String
[C#]
public string Uri {get; set;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlProperty Class | Aspose.Words.Markup Namespace


Value Property

Aspose.Words

CustomXmlProperty.Value Property

Gets or sets the value of the custom XML attribute or smart tag property.

[Visual Basic]
Public Property Value As String
[C#]
public string Value {get; set;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

CustomXmlProperty Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection Class

Represents a collection of custom XML attributes or smart tag properties.

For a list of all members of this type, see CustomXmlPropertyCollection Members.

System.Object
Aspose.Words.Markup.CustomXmlPropertyCollection

[Visual Basic]
Public Class CustomXmlPropertyCollection
Implements IEnumerable`1([Aspose.Words.Markup.CustomXmlProperty, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class CustomXmlPropertyCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

Items are CustomXmlProperty objects.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomXmlPropertyCollection Members | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection Members

CustomXmlPropertyCollection overview

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Overloaded. Provides access to the collection items.

Public Instance Methods

Add | Adds a property to the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains a property with the given name.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOfKey | Returns the zero-based index of the specified property in the collection.
Remove | Removes a property with the specified name from the collection.
RemoveAt | Removes a property at the specified index.

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection Properties

The properties of the CustomXmlPropertyCollection class are listed below. For a complete list of CustomXmlPropertyCollection class members, see the CustomXmlPropertyCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Overloaded. Provides access to the collection items.

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


Count Property

Aspose.Words

CustomXmlPropertyCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


Item Property

Aspose.Words

CustomXmlPropertyCollection.Item Property

Provides access to the collection items.

Overload List

Gets a property at the specified index.

public CustomXmlProperty this[int] {get;}

Gets a property with the specified name.

public CustomXmlProperty this[string] {get;}

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


Item Property (Int32)

Aspose.Words

CustomXmlPropertyCollection.Item Property (Int32)

Gets a property at the specified index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As CustomXmlProperty
[C#]
public CustomXmlProperty this[
int index
] {get;}

Parameters

index
Zero-based index of the property.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace | CustomXmlPropertyCollection.Item Overload List


Item Property (String)

Aspose.Words

CustomXmlPropertyCollection.Item Property (String)

Gets a property with the specified name.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal name As String _
) As CustomXmlProperty
[C#]
public CustomXmlProperty this[
string name
] {get;}

Parameters

name
Case-sensitive name of the property to locate.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace | CustomXmlPropertyCollection.Item Overload List


CustomXmlPropertyCollection Methods

The methods of the CustomXmlPropertyCollection class are listed below. For a complete list of CustomXmlPropertyCollection class members, see the CustomXmlPropertyCollection Members topic.

Public Instance Methods

Add | Adds a property to the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains a property with the given name.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOfKey | Returns the zero-based index of the specified property in the collection.
Remove | Removes a property with the specified name from the collection.
RemoveAt | Removes a property at the specified index.

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.Add Method

Adds a property to the collection.

[Visual Basic]
Public Sub Add( _
ByVal property As CustomXmlProperty _
)
[C#]
public void Add(
CustomXmlProperty property
);

Parameters

property
The property to add.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.Contains Method

Determines whether the collection contains a property with the given name.

[Visual Basic]
Public Function Contains( _
ByVal name As String _
) As Boolean
[C#]
public bool Contains(
string name
);

Parameters

name
Case-sensitive name of the property to locate.

Return Value

True if the item is found in the collection; otherwise, false.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of CustomXmlProperty) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<CustomXmlProperty> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.IndexOfKey Method

Returns the zero-based index of the specified property in the collection.

[Visual Basic]
Public Function IndexOfKey( _
ByVal name As String _
) As Integer
[C#]
public int IndexOfKey(
string name
);

Parameters

name
The case-sensitive name of the property.

Return Value

The zero based index. Negative value if not found.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.Remove Method

Removes a property with the specified name from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal name As String _
)
[C#]
public void Remove(
string name
);

Parameters

name
The case-sensitive name of the property.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlPropertyCollection.RemoveAt Method

Removes a property at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to work with smart tag properties to get in depth information about smart tags.

[C#]

// Open a document that contains smart tags and their collection
Document doc = new Document(MyDir + "SmartTags.doc");

// Smart tags are an older Microsoft Word feature that can automatically detect and tag
// any parts of the text that it registers as commonly used information objects such as names, addresses, stock tickers, dates etc
// In Word 2003, smart tags can be turned on in Tools > AutoCorrect options... > SmartTags tab
// In our input document there are three objects that were registered as smart tags, but since they can be nested, we have 8 in this collection
NodeCollection smartTags = doc.GetChildNodes(NodeType.SmartTag, true);
Assert.AreEqual(8, smartTags.Count);

// The last smart tag is of the "Date" type, which we will retrieve here
SmartTag smartTag = (SmartTag)smartTags[7];

// The Properties attribute, for some smart tags, elaborates on the text object that Word picked up as a smart tag
// In the case of our "Date" smart tag, its properties will let us know the year, month and day within the smart tag
CustomXmlPropertyCollection properties = smartTag.Properties;

// We can enumerate over the collection and print the aforementioned properties to the console
Assert.AreEqual(4, properties.Count);

using (IEnumerator<CustomXmlProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Property name: {enumerator.Current.Name}, value: {enumerator.Current.Value}");
        Assert.AreEqual("", enumerator.Current.Uri);
    }
}

// We can also access the elements in various ways, including as a key-value pair
Assert.True(properties.Contains("Day"));
Assert.AreEqual("22", properties["Day"].Value);
Assert.AreEqual("2003", properties[2].Value);
Assert.AreEqual(1, properties.IndexOfKey("Month"));

// We can also remove elements by name, index or clear the collection entirely
properties.RemoveAt(3);
properties.Remove("Year");
Assert.AreEqual(2, (properties.Count));

properties.Clear();
Assert.AreEqual(0, (properties.Count));

// We can remove the entire smart tag like this
smartTag.Remove();

See Also

CustomXmlPropertyCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection Class

A collection of strings that represent XML schemas that are associated with a custom XML part.

For a list of all members of this type, see CustomXmlSchemaCollection Members.

System.Object
Aspose.Words.Markup.CustomXmlSchemaCollection

[Visual Basic]
Public Class CustomXmlSchemaCollection
Implements IEnumerable`1([System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), IEnumerable
[C#]
public class CustomXmlSchemaCollection : 0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], IEnumerable

Remarks

You do not create instances of this class. You access the collection of XML schemas of a custom XML part via the Schemas property.

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomXmlSchemaCollection Members | Aspose.Words.Markup Namespace | CustomXmlPart | Schemas


CustomXmlSchemaCollection Members

CustomXmlSchemaCollection overview

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets the element at the specified index.

Public Instance Methods

Add | Adds an item to the collection.
Clear | Removes all elements from the collection.
Clone | Makes a deep clone of this object.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf | Returns the zero-based index of the specified value in the collection.
Remove | Removes the specified value from the collection.
RemoveAt | Removes a value at the specified index.

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace | CustomXmlPart | Schemas


CustomXmlSchemaCollection Properties

The properties of the CustomXmlSchemaCollection class are listed below. For a complete list of CustomXmlSchemaCollection class members, see the CustomXmlSchemaCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets the element at the specified index.

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace | CustomXmlPart | Schemas


Count Property

Aspose.Words

CustomXmlSchemaCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


Item Property

Aspose.Words

CustomXmlSchemaCollection.Item Property

Gets or sets the element at the specified index.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As String
[C#]
public string this[
int index
] {get; set;}

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection Methods

The methods of the CustomXmlSchemaCollection class are listed below. For a complete list of CustomXmlSchemaCollection class members, see the CustomXmlSchemaCollection Members topic.

Public Instance Methods

Add | Adds an item to the collection.
Clear | Removes all elements from the collection.
Clone | Makes a deep clone of this object.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf | Returns the zero-based index of the specified value in the collection.
Remove | Removes the specified value from the collection.
RemoveAt | Removes a value at the specified index.

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace | CustomXmlPart | Schemas


CustomXmlSchemaCollection.Add Method

Adds an item to the collection.

[Visual Basic]
Public Sub Add( _
ByVal value As String _
)
[C#]
public void Add(
string value
);

Parameters

value
The item to add.

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection.Clone Method

Makes a deep clone of this object.

[Visual Basic]
Public Function Clone() As CustomXmlSchemaCollection
[C#]
public CustomXmlSchemaCollection Clone();

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of String) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<string> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection.IndexOf Method

Returns the zero-based index of the specified value in the collection.

[Visual Basic]
Public Function IndexOf( _
ByVal value As String _
) As Integer
[C#]
public int IndexOf(
string value
);

Parameters

value
The case-sensitive value to locate.

Return Value

The zero based index. Negative value if not found.

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection.Remove Method

Removes the specified value from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal name As String _
)
[C#]
public void Remove(
string name
);

Parameters

name
The case-sensitive value to remove.

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


CustomXmlSchemaCollection.RemoveAt Method

Removes a value at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to work with an XML schema collection.

[C#]

// Create a document and add a custom XML part
Document doc = new Document();

string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// Once the part is created, we can add XML schema associations like this,
// and perform other collection-related operations on the list of schemas for this part
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// Collections can be cloned and elements can be added
CustomXmlSchemaCollection schemas = xmlPart.Schemas.Clone();
schemas.Add("http://www.w3.org/2001/XMLSchema-instance");
schemas.Add("http://schemas.microsoft.com/office/2006/metadata/contentType");

Assert.AreEqual(3, schemas.Count);
Assert.AreEqual(2, schemas.IndexOf(("http://schemas.microsoft.com/office/2006/metadata/contentType")));

// We can iterate over the collection with an enumerator
using (IEnumerator<string> enumerator = schemas.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

// We can also remove elements by index, element, or we can clear the entire collection
schemas.RemoveAt(2);
schemas.Remove("http://www.w3.org/2001/XMLSchema");
schemas.Clear();

Assert.AreEqual(0, schemas.Count);

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


MarkupLevel Enumeration

Specifies the level in the document tree where a particular StructuredDocumentTag can occur.

[Visual Basic]
Public Enum MarkupLevel
[C#]
public enum MarkupLevel

Example

Shows how to work with styles for content control elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Get specific style from the document to apply it to an SDT
Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
StructuredDocumentTag sdtPlainText = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
sdtPlainText.Style = quoteStyle;

StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
sdtRichText.StyleName = "Quote"; // Second method to apply specific style to an SDT control

// Insert content controls into the document
builder.InsertNode(sdtPlainText);
builder.InsertNode(sdtRichText);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

// We can get a collection of StructuredDocumentTags by looking for the document's child nodes of this NodeType
Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (Node node in tags)
{
    StructuredDocumentTag sdt = (StructuredDocumentTag) node;
    // If style was not defined before, style should be "Default Paragraph Font"
    Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
    Assert.AreEqual("Quote", sdt.StyleName);
}

Members

Member Name | Description | Value
Unknown | Specifies the unknown or invalid value. | 0
Inline | The element occurs at the inline level (e.g. among as runs of text). | 1
Block | The element occurs at the block level (e.g. among tables and paragraphs). | 2
Row | The element occurs among rows in a table. | 3
Cell | The element occurs among cells in a row. | 4

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Markup Namespace


SdtCalendarType Enumeration

Specifies the possible types of calendars which can be used to specify CalendarType in an Office Open XML document.

[Visual Basic]
Public Enum SdtCalendarType
[C#]
public enum SdtCalendarType

Members

Member Name | Description | Value
Default | Used as default value in OOXML. Equals Gregorian. | 0
Gregorian | Specifies that the Gregorian calendar, as defined in ISO 8601, shall be used. This calendar should be localized into the appropriate language. | 0
GregorianArabic | Specifies that the Gregorian calendar, as defined in ISO 8601, shall be used. The values for this calendar should be presented in Arabic. | 1
GregorianMeFrench | Specifies that the Gregorian calendar, as defined in ISO 8601, shall be used. The values for this calendar should be presented in Middle East French. | 2
GregorianUs | Specifies that the Gregorian calendar, as defined in ISO 8601, shall be used. The values for this calendar should be presented in English. | 3
GregorianXlitEnglish | Specifies that the Gregorian calendar, as defined in ISO 8601, shall be used. The values for this calendar should be the representation of the English strings in the corresponding Arabic characters (the Arabic transliteration of the English for the Gregorian calendar). | 4
GregorianXlitFrench | Specifies that the Gregorian calendar, as defined in ISO 8601, shall be used. The values for this calendar should be the representation of the French strings in the corresponding Arabic characters (the Arabic transliteration of the French for the Gregorian calendar). | 5
Hebrew | Specifies that the Hebrew lunar calendar, as described by the Gauss formula for Passover [CITATION] and The Complete Restatement of Oral Law (Mishneh Torah),shall be used. | 6
Hijri | Specifies that the Hijri lunar calendar, as described by the Kingdom of Saudi Arabia, Ministry of Islamic Affairs, Endowments, Da‘wah and Guidance, shall be used. | 7
Japan | Specifies that the Japanese Emperor Era calendar, as described by Japanese Industrial Standard JIS X 0301, shall be used. | 8
Korea | Specifies that the Korean Tangun Era calendar, as described by Korean Law Enactment No. 4, shall be used. | 9
None | Specifies that no calendar should be used. | 10
Saka | Specifies that the Saka Era calendar, as described by the Calendar Reform Committee of India, as part of the Indian Ephemeris and Nautical Almanac, shall be used. | 11
Taiwan | Specifies that the Taiwanese calendar, as defined by the Chinese National Standard CNS 7648, shall be used. | 12
Thai | Specifies that the Thai calendar, as defined by the Royal Decree of H.M. King Vajiravudh (Rama VI) in Royal Gazette B. E. 2456 (1913 A.D.) and by the decree of Prime Minister Phibunsongkhram (1941 A.D.) to start the year on the Gregorian January 1 and to map year zero to Gregorian year 543 B.C., shall be used. | 13

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Markup Namespace


SdtDateStorageFormat Enumeration

Specifies how the date for a date SDT is stored/retrieved when the SDT is bound to an XML node in the document's data store.

[Visual Basic]
Public Enum SdtDateStorageFormat
[C#]
public enum SdtDateStorageFormat

Members

Member Name | Description | Value
Date | The date value for a date SDT is stored as a date in the standard XML Schema Date format. | 0
DateTime | The date value for a date SDT is stored as a date in the standard XML Schema DateTime format. | 1
Text | The date value for a date SDT is stored as text. | 2
Default | Defaults to DateTime | 1

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Markup Namespace


SdtListItem Class

This element specifies a single list item within a parent ComboBox or DropDownList structured document tag.

For a list of all members of this type, see SdtListItem Members.

System.Object
Aspose.Words.Markup.SdtListItem

[Visual Basic]
Public Class SdtListItem
[C#]
public class SdtListItem

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SdtListItem Members | Aspose.Words.Markup Namespace


SdtListItem Members

SdtListItem overview

Public Instance Constructors

SdtListItem Overloaded. Initializes a new instance of the SdtListItem class.

Public Instance Properties

DisplayText | Gets the text to display in the run content in place of the Value attribute contents for this list item.
Value | Gets the value of this list item.

See Also

SdtListItem Class | Aspose.Words.Markup Namespace


SdtListItem Constructor

Initializes a new instance of this class.

Overload List

Initializes a new instance of this class.

public SdtListItem(string);

Initializes a new instance of this class.

public SdtListItem(string,string);

See Also

SdtListItem Class | Aspose.Words.Markup Namespace


SdtListItem Constructor (String, String)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal displayText As String, _
ByVal value As String _
)
[C#]
public SdtListItem(
string displayText,
string value
);

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItem Class | Aspose.Words.Markup Namespace | SdtListItem Constructor Overload List


SdtListItem Constructor (String)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal value As String _
)
[C#]
public SdtListItem(
string value
);

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItem Class | Aspose.Words.Markup Namespace | SdtListItem Constructor Overload List


SdtListItem Properties

The properties of the SdtListItem class are listed below. For a complete list of SdtListItem class members, see the SdtListItem Members topic.

Public Instance Properties

DisplayText | Gets the text to display in the run content in place of the Value attribute contents for this list item.
Value | Gets the value of this list item.

See Also

SdtListItem Class | Aspose.Words.Markup Namespace


DisplayText Property

Aspose.Words

SdtListItem.DisplayText Property

Gets the text to display in the run content in place of the Value attribute contents for this list item.

[Visual Basic]
Public ReadOnly Property DisplayText As String
[C#]
public string DisplayText {get;}

Remarks

Cannot be null and cannot be an empty string.

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItem Class | Aspose.Words.Markup Namespace


Value Property

Aspose.Words

SdtListItem.Value Property

Gets the value of this list item.

[Visual Basic]
Public ReadOnly Property Value As String
[C#]
public string Value {get;}

Remarks

Cannot be null and cannot be an empty string.

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItem Class | Aspose.Words.Markup Namespace


SdtListItemCollection Class

Provides access to SdtListItem elements of a structured document tag.

For a list of all members of this type, see SdtListItemCollection Members.

System.Object
Aspose.Words.Markup.SdtListItemCollection

[Visual Basic]
Public Class SdtListItemCollection
Implements IEnumerable`1([Aspose.Words.Markup.SdtListItem, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class SdtListItemCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SdtListItemCollection Members | Aspose.Words.Markup Namespace


SdtListItemCollection Members

SdtListItemCollection overview

Public Instance Properties

Count | Gets number of items in the collection.
Item | Returns a SdtListItem object given its zero-based index in the collection.
SelectedValue | Specifies currently selected value in this list. Null value allowed, meaning that no currently selected entry is associated with this list item collection.

Public Instance Methods

Add | Adds an item to this collection.
Clear | Clears all items from this collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes a list item at the specified index.

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtListItemCollection Properties

The properties of the SdtListItemCollection class are listed below. For a complete list of SdtListItemCollection class members, see the SdtListItemCollection Members topic.

Public Instance Properties

Count | Gets number of items in the collection.
Item | Returns a SdtListItem object given its zero-based index in the collection.
SelectedValue | Specifies currently selected value in this list. Null value allowed, meaning that no currently selected entry is associated with this list item collection.

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


Count Property

Aspose.Words

SdtListItemCollection.Count Property

Gets number of items in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


Item Property

Aspose.Words

SdtListItemCollection.Item Property

Returns a SdtListItem object given its zero-based index in the collection.

[Visual Basic]
Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As SdtListItem
[C#]
public SdtListItem this[
int index
] {get;}

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SelectedValue Property

Aspose.Words

SdtListItemCollection.SelectedValue Property

Specifies currently selected value in this list. Null value allowed, meaning that no currently selected entry is associated with this list item collection.

[Visual Basic]
Public Property SelectedValue As SdtListItem
[C#]
public SdtListItem SelectedValue {get; set;}

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtListItemCollection Methods

The methods of the SdtListItemCollection class are listed below. For a complete list of SdtListItemCollection class members, see the SdtListItemCollection Members topic.

Public Instance Methods

Add | Adds an item to this collection.
Clear | Clears all items from this collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes a list item at the specified index.

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtListItemCollection.Add Method

Adds an item to this collection.

[Visual Basic]
Public Sub Add( _
ByVal item As SdtListItem _
)
[C#]
public void Add(
SdtListItem item
);

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtListItemCollection.Clear Method

Clears all items from this collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtListItemCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of SdtListItem) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<SdtListItem> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtListItemCollection.RemoveAt Method

Removes a list item at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the item to remove.

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

SdtListItemCollection Class | Aspose.Words.Markup Namespace


SdtType Enumeration

Specifies the type of a structured document tag (SDT) node.

[Visual Basic]
Public Enum SdtType
[C#]
public enum SdtType

Example

Shows how to work with styles for content control elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Get specific style from the document to apply it to an SDT
Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
StructuredDocumentTag sdtPlainText = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
sdtPlainText.Style = quoteStyle;

StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
sdtRichText.StyleName = "Quote"; // Second method to apply specific style to an SDT control

// Insert content controls into the document
builder.InsertNode(sdtPlainText);
builder.InsertNode(sdtRichText);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

// We can get a collection of StructuredDocumentTags by looking for the document's child nodes of this NodeType
Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (Node node in tags)
{
    StructuredDocumentTag sdt = (StructuredDocumentTag) node;
    // If style was not defined before, style should be "Default Paragraph Font"
    Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
    Assert.AreEqual("Quote", sdt.StyleName);
}

Members

Member Name | Description | Value
None | No type is assigned to the SDT. | 0
Bibliography | The SDT represents a bibliography entry. | 1
Citation | The SDT represents a citation. | 2
Equation | The SDT represents an equation. | 3
DropDownList | The SDT represents a drop down list when displayed in the document. | 4
ComboBox | The SDT represents a combo box when displayed in the document. | 5
Date | The SDT represents a date picker when displayed in the document. | 6
BuildingBlockGallery | The SDT represents a building block gallery type. | 7
DocPartObj | The SDT represents a document part type. | 8
Group | The SDT represents a restricted grouping when displayed in the document. | 9
Picture | The SDT represents a picture when displayed in the document. | 10
RichText | The SDT represents a rich text box when displayed in the document. | 11
PlainText | The SDT represents a plain text box when displayed in the document. | 12
Checkbox | The SDT represents a checkbox when displayed in the document. | 13
RepeatingSection | The SDT represents repeating section type when displayed in the document. | 14
EntityPicker | The SDT represents an entity picker that allows the user to select an instance of an external content type. | 15

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Markup Namespace


SmartTag Class

This element specifies the presence of a smart tag around one or more inline structures (runs, images, fields,etc.) within a paragraph.

For a list of all members of this type, see SmartTag Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Markup.SmartTag

[Visual Basic]
Public Class SmartTag
Inherits CompositeNode
[C#]
public class SmartTag : CompositeNode

Remarks

Smart tags is a kind of custom XML markup. Smart tags provide a facility for embedding customer-defined semantics into the document via the ability to provide a basic namespace/name for a run or set of runs within a document.

SmartTag can be a child of a Paragraph or another SmartTag node.

The complete list of child nodes that can occur inside a smart tag consists of BookmarkStart, BookmarkEnd, FieldStart, FieldSeparator, FieldEnd, FormField, Comment, Footnote, Run, SpecialChar, Shape, GroupShape, CommentRangeStart, CommentRangeEnd, SmartTag.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SmartTag Members | Aspose.Words.Markup Namespace


SmartTag Members

SmartTag overview

Public Instance Constructors

SmartTag Constructor Initializes a new instance of the SmartTag class.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
Element | Specifies the name of the smart tag within the document.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.SmartTag.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Properties | A collection of the smart tag properties.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Uri | Specifies the namespace URI of the smart tag.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

SmartTag Class | Aspose.Words.Markup Namespace


SmartTag Constructor

Initializes a new instance of the SmartTag class.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public SmartTag(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When you create a new node, you need to specify a document to which the node belongs. A node cannot exist without a document because it depends on the document-wide structures such as lists and styles. Although a node always belongs to a document, a node might or might not be a part of the document tree.

When a node is created, it belongs to a document, but is not yet part of the document tree and ParentNode is null. To insert a node into the document, use the InsertAfter or InsertBefore methods on the parent node.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

SmartTag Class | Aspose.Words.Markup Namespace


SmartTag Properties

The properties of the SmartTag class are listed below. For a complete list of SmartTag class members, see the SmartTag Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
Element | Specifies the name of the smart tag within the document.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.SmartTag.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Properties | A collection of the smart tag properties.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Uri | Specifies the namespace URI of the smart tag.

See Also

SmartTag Class | Aspose.Words.Markup Namespace


Element Property

Aspose.Words

SmartTag.Element Property

Specifies the name of the smart tag within the document.

[Visual Basic]
Public Property Element As String
[C#]
public string Element {get; set;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

SmartTag Class | Aspose.Words.Markup Namespace


NodeType Property

Aspose.Words

SmartTag.NodeType Property

Returns NodeType.SmartTag.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

SmartTag Class | Aspose.Words.Markup Namespace


Properties Property

Aspose.Words

SmartTag.Properties Property

A collection of the smart tag properties.

[Visual Basic]
Public ReadOnly Property Properties As CustomXmlPropertyCollection
[C#]
public CustomXmlPropertyCollection Properties {get;}

Remarks

Cannot be null.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

SmartTag Class | Aspose.Words.Markup Namespace


Uri Property

Aspose.Words

SmartTag.Uri Property

Specifies the namespace URI of the smart tag.

[Visual Basic]
Public Property Uri As String
[C#]
public string Uri {get; set;}

Remarks

Cannot be null.

Default is empty string.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

SmartTag Class | Aspose.Words.Markup Namespace


SmartTag Methods

The methods of the SmartTag class are listed below. For a complete list of SmartTag class members, see the SmartTag Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

SmartTag Class | Aspose.Words.Markup Namespace


SmartTag.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitSmartTagStart, then calls Accept for all child nodes of the smart tag and calls VisitSmartTagEnd at the end.

Example

Shows how to create smart tags.

[C#]

public void SmartTags()
{
    Document doc = new Document();
    SmartTag smartTag = new SmartTag(doc);
    smartTag.Element = "date";

    // Specify a date and set smart tag properties accordingly
    smartTag.AppendChild(new Run(doc, "May 29, 2019"));

    smartTag.Properties.Add(new CustomXmlProperty("Day", "", "29"));
    smartTag.Properties.Add(new CustomXmlProperty("Month", "", "5"));
    smartTag.Properties.Add(new CustomXmlProperty("Year", "", "2019"));

    // Set the smart tag's uri to the default
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a date. "));

    // Create and add one more smart tag, this time for a financial symbol
    smartTag = new SmartTag(doc);
    smartTag.Element = "stockticker";
    smartTag.Uri = "urn:schemas-microsoft-com:office:smarttags";

    smartTag.AppendChild(new Run(doc, "MSFT"));

    doc.FirstSection.Body.FirstParagraph.AppendChild(smartTag);
    doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, " is a stock ticker."));

    // Print all the smart tags in our document with a document visitor
    doc.Accept(new SmartTagVisitor());

    doc.Save(ArtifactsDir + "StructuredDocumentTag.SmartTags.docx");
}

/// <summary>
/// DocumentVisitor implementation that prints smart tags and their contents
/// </summary>
private class SmartTagVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a SmartTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSmartTagStart(SmartTag smartTag)
    {
        Console.WriteLine($"Smart tag type: {smartTag.Element}");
        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a SmartTag node is ended.
    /// </summary>
    public override VisitorAction VisitSmartTagEnd(SmartTag smartTag)
    {
        Console.WriteLine($"\tContents: \"{smartTag.ToString(SaveFormat.Text)}\"");

        if (smartTag.Properties.Count == 0)
        {
            Console.WriteLine("\tContains no properties");

        }
        else
        {
            Console.Write("\tProperties: ");
            string[] properties = new string[smartTag.Properties.Count];
            int index = 0;

            foreach (CustomXmlProperty cxp in smartTag.Properties)
            {
                properties[index++] = $"\"{cxp.Name}\" = \"{cxp.Value}\"";
            }

            Console.WriteLine(String.Join(", ", properties));
        }

        return VisitorAction.Continue;
    }
}

See Also

SmartTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag Class

Represents a structured document tag (SDT or content control) in a document.

For a list of all members of this type, see StructuredDocumentTag Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Markup.StructuredDocumentTag

[Visual Basic]
Public Class StructuredDocumentTag
Inherits CompositeNode
[C#]
public class StructuredDocumentTag : CompositeNode

Remarks

Structured document tags (SDTs) allow to embed customer-defined semantics as well as its behavior and appearance into a document.

In this version Aspose.Words provides a number of public methods and properties to manipulate the behavior and content of StructuredDocumentTag. Mapping of SDT nodes to custom XML packages within a document can be performed with using the XmlMapping property.

StructuredDocumentTag can occur in a document in the following places:

  • Block-level - Among paragraphs and tables, as a child of a Body, HeaderFooter, Comment, Footnote or a Shape node.
  • Row-level - Among rows in a table, as a child of a Table node.
  • Cell-level - Among cells in a table row, as a child of a Row node.
  • Inline-level - Among inline content inside, as a child of a Paragraph.
  • Nested inside another StructuredDocumentTag.

Example

Shows how to work with styles for content control elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Get specific style from the document to apply it to an SDT
Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
StructuredDocumentTag sdtPlainText = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
sdtPlainText.Style = quoteStyle;

StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
sdtRichText.StyleName = "Quote"; // Second method to apply specific style to an SDT control

// Insert content controls into the document
builder.InsertNode(sdtPlainText);
builder.InsertNode(sdtRichText);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

// We can get a collection of StructuredDocumentTags by looking for the document's child nodes of this NodeType
Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (Node node in tags)
{
    StructuredDocumentTag sdt = (StructuredDocumentTag) node;
    // If style was not defined before, style should be "Default Paragraph Font"
    Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
    Assert.AreEqual("Quote", sdt.StyleName);
}

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

StructuredDocumentTag Members | Aspose.Words.Markup Namespace


StructuredDocumentTag Members

StructuredDocumentTag overview

Public Instance Constructors

StructuredDocumentTag Constructor Initializes a new instance of the Structured document tag class.

Public Instance Properties

BuildingBlockCategory | Specifies category of building block for this SDT node. Can not be null.
BuildingBlockGallery | Specifies type of building block for this SDT. Can not be null.
CalendarType | Specifies the type of calendar for this SDT. Default is Default
Checked | Gets/Sets current state of the Checkbox SDT. Default value for this property is false.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Color | Gets or sets the color of the structured document tag.
ContentsFont | Font formatting that will be applied to text entered into SDT.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DateDisplayFormat | String that represents the format in which dates are displayed. Can not be null. The dates for English (U.S.) is "mm/dd/yyyy"
DateDisplayLocale | Allows to set/get the language format for the date displayed in this SDT.
DateStorageFormat | Gets/sets format in which the date for a date SDT is stored when the SDT is bound to an XML node in the document's data store. Default value is DateTime
Document (inherited from Node) | Gets the document to which this node belongs.
EndCharacterFont | Font formatting that will be applied to the last character of text entered into SDT.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FullDate | Specifies the full date and time last entered into this SDT.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Id | Specifies a unique read-only persistent numerical Id for this SDT.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsShowingPlaceholderText | Specifies whether the content of this SDT shall be interpreted to contain placeholder text (as opposed to regular text contents within the SDT). if set to true, this state shall be resumed (showing placeholder text) upon opening this document.
IsTemporary | Specifies whether this SDT shall be removed from the WordprocessingML document when its contents are modified.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Level | Gets the level at which this SDT occurs in the document tree.
ListItems | Gets SdtListItemCollection associated with this SDT.
LockContentControl | When set to true, this property will prohibit a user from deleting this SDT.
LockContents | When set to true, this property will prohibit a user from editing the contents of this SDT.
Multiline | Specifies whether this SDT allows multiple lines of text.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.StructuredDocumentTag.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
Placeholder | Gets the BuildingBlock containing placeholder text which should be displayed when this SDT run contents are empty, the associated mapped XML element is empty as specified via the XmlMapping element or the IsShowingPlaceholderText element is true.
PlaceholderName | Gets or sets Name of the BuildingBlock containing placeholder text. BuildingBlock with this name Name has to be present in the GlossaryDocument otherwise InvalidOperationException will occur.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
SdtType | Gets type of this Structured document tag.
Style | Gets or sets the Style of the structured document tag.
StyleName | Gets or sets the name of the style applied to the structured document tag.
Tag | Specifies a tag associated with the current SDT node. Can not be null.
Title | Specifies the friendly name associated with this SDT. Can not be null.
XmlMapping | Gets an object that represents the mapping of this structured document tag to XML data in a custom XML part of the current document.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clear | Clears contents of this structured document tag and displays a placeholder if it is defined.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSelfOnly | Removes just this SDT node itself, but keeps the content of it inside the document tree.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag Constructor

Initializes a new instance of the Structured document tag class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase, _
ByVal type As SdtType, _
ByVal level As MarkupLevel _
)
[C#]
public StructuredDocumentTag(
DocumentBase doc,
SdtType type,
MarkupLevel level
);

Parameters

doc
The owner document.
type
Type of SDT node.
level
Level of SDT node within the document.

Remarks

The following types of SDT can be created:

  • Checkbox
  • DropDownList
  • ComboBox
  • Date
  • BuildingBlockGallery
  • Group
  • Picture
  • RichText
  • PlainText

Example

Show how to create and insert checkbox structured document tag.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

StructuredDocumentTag sdtCheckBox = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
sdtCheckBox.Checked = true;

// Insert content control into the document
builder.InsertNode(sdtCheckBox);

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag Properties

The properties of the StructuredDocumentTag class are listed below. For a complete list of StructuredDocumentTag class members, see the StructuredDocumentTag Members topic.

Public Instance Properties

BuildingBlockCategory | Specifies category of building block for this SDT node. Can not be null.
BuildingBlockGallery | Specifies type of building block for this SDT. Can not be null.
CalendarType | Specifies the type of calendar for this SDT. Default is Default
Checked | Gets/Sets current state of the Checkbox SDT. Default value for this property is false.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Color | Gets or sets the color of the structured document tag.
ContentsFont | Font formatting that will be applied to text entered into SDT.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DateDisplayFormat | String that represents the format in which dates are displayed. Can not be null. The dates for English (U.S.) is "mm/dd/yyyy"
DateDisplayLocale | Allows to set/get the language format for the date displayed in this SDT.
DateStorageFormat | Gets/sets format in which the date for a date SDT is stored when the SDT is bound to an XML node in the document's data store. Default value is DateTime
Document (inherited from Node) | Gets the document to which this node belongs.
EndCharacterFont | Font formatting that will be applied to the last character of text entered into SDT.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FullDate | Specifies the full date and time last entered into this SDT.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
Id | Specifies a unique read-only persistent numerical Id for this SDT.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsShowingPlaceholderText | Specifies whether the content of this SDT shall be interpreted to contain placeholder text (as opposed to regular text contents within the SDT). if set to true, this state shall be resumed (showing placeholder text) upon opening this document.
IsTemporary | Specifies whether this SDT shall be removed from the WordprocessingML document when its contents are modified.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
Level | Gets the level at which this SDT occurs in the document tree.
ListItems | Gets SdtListItemCollection associated with this SDT.
LockContentControl | When set to true, this property will prohibit a user from deleting this SDT.
LockContents | When set to true, this property will prohibit a user from editing the contents of this SDT.
Multiline | Specifies whether this SDT allows multiple lines of text.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.StructuredDocumentTag.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
Placeholder | Gets the BuildingBlock containing placeholder text which should be displayed when this SDT run contents are empty, the associated mapped XML element is empty as specified via the XmlMapping element or the IsShowingPlaceholderText element is true.
PlaceholderName | Gets or sets Name of the BuildingBlock containing placeholder text. BuildingBlock with this name Name has to be present in the GlossaryDocument otherwise InvalidOperationException will occur.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
SdtType | Gets type of this Structured document tag.
Style | Gets or sets the Style of the structured document tag.
StyleName | Gets or sets the name of the style applied to the structured document tag.
Tag | Specifies a tag associated with the current SDT node. Can not be null.
Title | Specifies the friendly name associated with this SDT. Can not be null.
XmlMapping | Gets an object that represents the mapping of this structured document tag to XML data in a custom XML part of the current document.

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


BuildingBlockCategory Property

Aspose.Words

StructuredDocumentTag.BuildingBlockCategory Property

Specifies category of building block for this SDT node. Can not be null.

[Visual Basic]
Public Property BuildingBlockCategory As String
[C#]
public string BuildingBlockCategory {get; set;}

Remarks

Accessing this property will only work for BuildingBlockGallery and DocPartObj SDT types. It is read-only for SDT of the document part type.

For all other SDT types exception will occur.

Example

Shows how to insert a StructuredDocumentTag as a building block and set its category and gallery.

[C#]

Document doc = new Document();

StructuredDocumentTag buildingBlockSdt =
    new StructuredDocumentTag(doc, SdtType.BuildingBlockGallery, MarkupLevel.Block)
    {
        BuildingBlockCategory = "Built-in",
        BuildingBlockGallery = "Table of Contents"
    };

doc.FirstSection.Body.AppendChild(buildingBlockSdt);

doc.Save(ArtifactsDir + "StructuredDocumentTag.BuildingBlockCategories.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


BuildingBlockGallery Property

Aspose.Words

StructuredDocumentTag.BuildingBlockGallery Property

Specifies type of building block for this SDT. Can not be null.

[Visual Basic]
Public Property BuildingBlockGallery As String
[C#]
public string BuildingBlockGallery {get; set;}

Remarks

Accessing this property will only work for BuildingBlockGallery and DocPartObj SDT types. It is read-only for SDT of the document part type.

For all other SDT types exception will occur.

Example

Shows how to insert a StructuredDocumentTag as a building block and set its category and gallery.

[C#]

Document doc = new Document();

StructuredDocumentTag buildingBlockSdt =
    new StructuredDocumentTag(doc, SdtType.BuildingBlockGallery, MarkupLevel.Block)
    {
        BuildingBlockCategory = "Built-in",
        BuildingBlockGallery = "Table of Contents"
    };

doc.FirstSection.Body.AppendChild(buildingBlockSdt);

doc.Save(ArtifactsDir + "StructuredDocumentTag.BuildingBlockCategories.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


CalendarType Property

Aspose.Words

StructuredDocumentTag.CalendarType Property

Specifies the type of calendar for this SDT. Default is Default

[Visual Basic]
Public Property CalendarType As SdtCalendarType
[C#]
public SdtCalendarType CalendarType {get; set;}

Remarks

Accessing this property will only work for Date SDT type.

For all other SDT types exception will occur.

Example

Shows how to prompt the user to enter a date with a StructuredDocumentTag.

[C#]

// Create a new document
Document doc = new Document();

// Insert a StructuredDocumentTag that prompts the user to enter a date
// In Microsoft Word, this element is known as a "Date picker content control"
// When we click on the arrow on the right end of this tag in Microsoft Word,
// we will see a pop up in the form of a clickable calendar
// We can use that popup to select a date that will be displayed by the tag
StructuredDocumentTag sdtDate = new StructuredDocumentTag(doc, SdtType.Date, MarkupLevel.Inline);

// This attribute sets the language that the calendar will be displayed in,
// which in this case will be Saudi Arabian Arabic
sdtDate.DateDisplayLocale = CultureInfo.GetCultureInfo("ar-SA").LCID;

// We can set the format with which to display the date like this
// The locale we set above will be carried over to the displayed date
sdtDate.DateDisplayFormat = "dd MMMM, yyyy";

// Select how the data will be stored in the document
sdtDate.DateStorageFormat = SdtDateStorageFormat.DateTime;

// Set the calendar type that will be used to select and display the date
sdtDate.CalendarType = SdtCalendarType.Hijri;

// Before a date is chosen, the tag will display the text "Click here to enter a date."
// We can set a default date to display by setting this variable
// We must convert the date to the appropriate calendar ourselves
sdtDate.FullDate = new DateTime(1440, 10, 20);

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(sdtDate);

doc.Save(ArtifactsDir + "SDT.Date.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Checked Property

Aspose.Words

StructuredDocumentTag.Checked Property

Gets/Sets current state of the Checkbox SDT. Default value for this property is false.

[Visual Basic]
Public Property Checked As Boolean
[C#]
public bool Checked {get; set;}

Remarks

Accessing this property will only work for Checkbox SDT types.

For all other SDT types exception will occur.

Example

Show how to create and insert checkbox structured document tag.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

StructuredDocumentTag sdtCheckBox = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
sdtCheckBox.Checked = true;

// Insert content control into the document
builder.InsertNode(sdtCheckBox);

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Color Property

Aspose.Words

StructuredDocumentTag.Color Property

Gets or sets the color of the structured document tag.

[Visual Basic]
Public Property Color As Color
[C#]
public Color Color {get; set;}

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


ContentsFont Property

Aspose.Words

StructuredDocumentTag.ContentsFont Property

Font formatting that will be applied to text entered into SDT.

[Visual Basic]
Public ReadOnly Property ContentsFont As Font
[C#]
public Font ContentsFont {get;}

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


DateDisplayFormat Property

Aspose.Words

StructuredDocumentTag.DateDisplayFormat Property

String that represents the format in which dates are displayed. Can not be null. The dates for English (U.S.) is "mm/dd/yyyy"

[Visual Basic]
Public Property DateDisplayFormat As String
[C#]
public string DateDisplayFormat {get; set;}

Remarks

Accessing this property will only work for Date SDT type.

For all other SDT types exception will occur.

Example

Shows how to prompt the user to enter a date with a StructuredDocumentTag.

[C#]

// Create a new document
Document doc = new Document();

// Insert a StructuredDocumentTag that prompts the user to enter a date
// In Microsoft Word, this element is known as a "Date picker content control"
// When we click on the arrow on the right end of this tag in Microsoft Word,
// we will see a pop up in the form of a clickable calendar
// We can use that popup to select a date that will be displayed by the tag
StructuredDocumentTag sdtDate = new StructuredDocumentTag(doc, SdtType.Date, MarkupLevel.Inline);

// This attribute sets the language that the calendar will be displayed in,
// which in this case will be Saudi Arabian Arabic
sdtDate.DateDisplayLocale = CultureInfo.GetCultureInfo("ar-SA").LCID;

// We can set the format with which to display the date like this
// The locale we set above will be carried over to the displayed date
sdtDate.DateDisplayFormat = "dd MMMM, yyyy";

// Select how the data will be stored in the document
sdtDate.DateStorageFormat = SdtDateStorageFormat.DateTime;

// Set the calendar type that will be used to select and display the date
sdtDate.CalendarType = SdtCalendarType.Hijri;

// Before a date is chosen, the tag will display the text "Click here to enter a date."
// We can set a default date to display by setting this variable
// We must convert the date to the appropriate calendar ourselves
sdtDate.FullDate = new DateTime(1440, 10, 20);

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(sdtDate);

doc.Save(ArtifactsDir + "SDT.Date.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


DateDisplayLocale Property

Aspose.Words

StructuredDocumentTag.DateDisplayLocale Property

Allows to set/get the language format for the date displayed in this SDT.

[Visual Basic]
Public Property DateDisplayLocale As Integer
[C#]
public int DateDisplayLocale {get; set;}

Remarks

Accessing this property will only work for Date SDT type.

For all other SDT types exception will occur.

Example

Shows how to prompt the user to enter a date with a StructuredDocumentTag.

[C#]

// Create a new document
Document doc = new Document();

// Insert a StructuredDocumentTag that prompts the user to enter a date
// In Microsoft Word, this element is known as a "Date picker content control"
// When we click on the arrow on the right end of this tag in Microsoft Word,
// we will see a pop up in the form of a clickable calendar
// We can use that popup to select a date that will be displayed by the tag
StructuredDocumentTag sdtDate = new StructuredDocumentTag(doc, SdtType.Date, MarkupLevel.Inline);

// This attribute sets the language that the calendar will be displayed in,
// which in this case will be Saudi Arabian Arabic
sdtDate.DateDisplayLocale = CultureInfo.GetCultureInfo("ar-SA").LCID;

// We can set the format with which to display the date like this
// The locale we set above will be carried over to the displayed date
sdtDate.DateDisplayFormat = "dd MMMM, yyyy";

// Select how the data will be stored in the document
sdtDate.DateStorageFormat = SdtDateStorageFormat.DateTime;

// Set the calendar type that will be used to select and display the date
sdtDate.CalendarType = SdtCalendarType.Hijri;

// Before a date is chosen, the tag will display the text "Click here to enter a date."
// We can set a default date to display by setting this variable
// We must convert the date to the appropriate calendar ourselves
sdtDate.FullDate = new DateTime(1440, 10, 20);

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(sdtDate);

doc.Save(ArtifactsDir + "SDT.Date.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


DateStorageFormat Property

Aspose.Words

StructuredDocumentTag.DateStorageFormat Property

Gets/sets format in which the date for a date SDT is stored when the SDT is bound to an XML node in the document's data store. Default value is DateTime

[Visual Basic]
Public Property DateStorageFormat As SdtDateStorageFormat
[C#]
public SdtDateStorageFormat DateStorageFormat {get; set;}

Remarks

Accessing this property will only work for Date SDT type.

For all other SDT types exception will occur.

Example

Shows how to prompt the user to enter a date with a StructuredDocumentTag.

[C#]

// Create a new document
Document doc = new Document();

// Insert a StructuredDocumentTag that prompts the user to enter a date
// In Microsoft Word, this element is known as a "Date picker content control"
// When we click on the arrow on the right end of this tag in Microsoft Word,
// we will see a pop up in the form of a clickable calendar
// We can use that popup to select a date that will be displayed by the tag
StructuredDocumentTag sdtDate = new StructuredDocumentTag(doc, SdtType.Date, MarkupLevel.Inline);

// This attribute sets the language that the calendar will be displayed in,
// which in this case will be Saudi Arabian Arabic
sdtDate.DateDisplayLocale = CultureInfo.GetCultureInfo("ar-SA").LCID;

// We can set the format with which to display the date like this
// The locale we set above will be carried over to the displayed date
sdtDate.DateDisplayFormat = "dd MMMM, yyyy";

// Select how the data will be stored in the document
sdtDate.DateStorageFormat = SdtDateStorageFormat.DateTime;

// Set the calendar type that will be used to select and display the date
sdtDate.CalendarType = SdtCalendarType.Hijri;

// Before a date is chosen, the tag will display the text "Click here to enter a date."
// We can set a default date to display by setting this variable
// We must convert the date to the appropriate calendar ourselves
sdtDate.FullDate = new DateTime(1440, 10, 20);

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(sdtDate);

doc.Save(ArtifactsDir + "SDT.Date.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


EndCharacterFont Property

Aspose.Words

StructuredDocumentTag.EndCharacterFont Property

Font formatting that will be applied to the last character of text entered into SDT.

[Visual Basic]
Public ReadOnly Property EndCharacterFont As Font
[C#]
public Font EndCharacterFont {get;}

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


FullDate Property

Aspose.Words

StructuredDocumentTag.FullDate Property

Specifies the full date and time last entered into this SDT.

[Visual Basic]
Public Property FullDate As Date
[C#]
public DateTime FullDate {get; set;}

Remarks

Accessing this property will only work for Date SDT type.

For all other SDT types exception will occur.

Example

Shows how to prompt the user to enter a date with a StructuredDocumentTag.

[C#]

// Create a new document
Document doc = new Document();

// Insert a StructuredDocumentTag that prompts the user to enter a date
// In Microsoft Word, this element is known as a "Date picker content control"
// When we click on the arrow on the right end of this tag in Microsoft Word,
// we will see a pop up in the form of a clickable calendar
// We can use that popup to select a date that will be displayed by the tag
StructuredDocumentTag sdtDate = new StructuredDocumentTag(doc, SdtType.Date, MarkupLevel.Inline);

// This attribute sets the language that the calendar will be displayed in,
// which in this case will be Saudi Arabian Arabic
sdtDate.DateDisplayLocale = CultureInfo.GetCultureInfo("ar-SA").LCID;

// We can set the format with which to display the date like this
// The locale we set above will be carried over to the displayed date
sdtDate.DateDisplayFormat = "dd MMMM, yyyy";

// Select how the data will be stored in the document
sdtDate.DateStorageFormat = SdtDateStorageFormat.DateTime;

// Set the calendar type that will be used to select and display the date
sdtDate.CalendarType = SdtCalendarType.Hijri;

// Before a date is chosen, the tag will display the text "Click here to enter a date."
// We can set a default date to display by setting this variable
// We must convert the date to the appropriate calendar ourselves
sdtDate.FullDate = new DateTime(1440, 10, 20);

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(sdtDate);

doc.Save(ArtifactsDir + "SDT.Date.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Id Property

Aspose.Words

StructuredDocumentTag.Id Property

Specifies a unique read-only persistent numerical Id for this SDT.

[Visual Basic]
Public ReadOnly Property Id As Integer
[C#]
public int Id {get;}

Remarks

Id attribute shall follow these rules:

  • The document shall retain SDT ids only if the whole document is cloned Clone.
  • During ImportNode Id shall be retained if import does not cause conflicts with other SDT Ids in the target document.
  • If multiple SDT nodes specify the same decimal number value for the Id attribute, then the first SDT in the document shall maintain this original Id, and all subsequent SDT nodes shall have new identifiers assigned to them when the document is loaded.
  • During standalone SDT Clone operation new unique ID will be generated for the cloned SDT node.
  • If Id is not specified in the source document, then the SDT node shall have a new unique identifier assigned to it when the document is loaded.

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


IsShowingPlaceholderText Property

Aspose.Words

StructuredDocumentTag.IsShowingPlaceholderText Property

Specifies whether the content of this SDT shall be interpreted to contain placeholder text (as opposed to regular text contents within the SDT).

if set to true, this state shall be resumed (showing placeholder text) upon opening this document.

[Visual Basic]
Public Property IsShowingPlaceholderText As Boolean
[C#]
public bool IsShowingPlaceholderText {get; set;}

Example

Shows how to use the contents of a BuildingBlock as a custom placeholder text for a StructuredDocumentTag.

[C#]

Document doc = new Document();

// Insert a plain text StructuredDocumentTag of the PlainText type, which will function like a text box
// It contains a default "Click here to enter text." prompt, which we can click and replace with our own text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// We can substitute that default placeholder with a custom phrase, which will be drawn from a BuildingBlock
// First we will need to create the BuildingBlock, give it content and add it to the GlossaryDocument
GlossaryDocument glossaryDoc = doc.GlossaryDocument;

BuildingBlock substituteBlock = new BuildingBlock(glossaryDoc);
substituteBlock.Name = "Custom Placeholder";
substituteBlock.AppendChild(new Section(glossaryDoc));
substituteBlock.FirstSection.AppendChild(new Body(glossaryDoc));
substituteBlock.FirstSection.Body.AppendParagraph("Custom placeholder text.");

glossaryDoc.AppendChild(substituteBlock);

// The substitute BuildingBlock we made can be referenced by name
tag.PlaceholderName = "Custom Placeholder";

// If PlaceholderName refers to an existing block in the parent document's GlossaryDocument,
// the BuildingBlock will be automatically found and assigned to the Placeholder attribute
Assert.AreEqual(substituteBlock, tag.Placeholder);

// Setting this to true will register the text inside the StructuredDocumentTag as placeholder text
// This means that, in Microsoft Word, all the text contents of the StructuredDocumentTag will be highlighted with one click,
// so we can immediately replace the entire substitute text by typing
// If this is false, the text will behave like an ordinary Paragraph and a cursor will be placed with nothing highlighted
tag.IsShowingPlaceholderText = true;

// Insert the StructuredDocumentTag into the document using a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

doc.Save(ArtifactsDir + "SDT.PlaceholderBuildingBlock.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


IsTemporary Property

Aspose.Words

StructuredDocumentTag.IsTemporary Property

Specifies whether this SDT shall be removed from the WordprocessingML document when its contents are modified.

[Visual Basic]
Public Property IsTemporary As Boolean
[C#]
public bool IsTemporary {get; set;}

Example

Demonstrates the effects of making a StructuredDocumentTag temporary.

[C#]

// Create a new Document
Document doc = new Document();

// Insert a plain text StructuredDocumentTag, which will prompt the user to enter text
// and allow them to edit it like a text box
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// If we set its Temporary attribute to true, as soon as we start typing,
// the tag will disappear and its contents will be assimilated into the parent Paragraph
tag.IsTemporary = true;

// Insert the StructuredDocumentTag with a DocumentBuilder
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Temporary text box: ");
builder.InsertNode(tag);

// A StructuredDocumentTag in the form of a check box will let the user a square to check and uncheck
// Setting it to temporary will freeze its value after the first time it is clicked
tag = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
tag.IsTemporary = true;

builder.Write("\nTemporary checkbox: ");
builder.InsertNode(tag);

doc.Save(ArtifactsDir + "SDT.IsTemporary.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Level Property

Aspose.Words

StructuredDocumentTag.Level Property

Gets the level at which this SDT occurs in the document tree.

[Visual Basic]
Public ReadOnly Property Level As MarkupLevel
[C#]
public MarkupLevel Level {get;}

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


ListItems Property

Aspose.Words

StructuredDocumentTag.ListItems Property

Gets SdtListItemCollection associated with this SDT.

[Visual Basic]
Public ReadOnly Property ListItems As SdtListItemCollection
[C#]
public SdtListItemCollection ListItems {get;}

Remarks

Accessing this property will only work for ComboBox or DropDownList SDT types.

For all other SDT types exception will occur.

Example

Shows how to work with StructuredDocumentTag nodes of the DropDownList type.

[C#]

// Create a blank document and insert a StructuredDocumentTag that will contain a drop down list
Document doc = new Document();
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DropDownList, MarkupLevel.Block);
doc.FirstSection.Body.AppendChild(tag);

// A drop down list needs elements, each of which will be a SdtListItem
SdtListItemCollection listItems = tag.ListItems;
listItems.Add(new SdtListItem("Value 1"));

// Each SdtListItem has text that will be displayed when the drop down list is opened, and also a value
// When we initialize with one string, we are providing just the value
// Accordingly, value is passed as DisplayText and will consequently be displayed on the screen
Assert.AreEqual(listItems[0].DisplayText, listItems[0].Value);

// Add 3 more SdtListItems with non-empty strings passed to DisplayText
listItems.Add(new SdtListItem("Item 2", "Value 2"));
listItems.Add(new SdtListItem("Item 3", "Value 3"));
listItems.Add(new SdtListItem("Item 4", "Value 4"));

// We can obtain a count of the SdtListItems and also set the drop down list's SelectedValue attribute to
// automatically have one of them pre-selected when we open the document in Microsoft Word
Assert.AreEqual(4, listItems.Count);
listItems.SelectedValue = listItems[3];

Assert.AreEqual("Value 4", listItems.SelectedValue.Value);

// We can enumerate over the collection and print each element
using (IEnumerator<SdtListItem> enumerator = listItems.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        if (enumerator.Current != null)
            Console.WriteLine($"List item: {enumerator.Current.DisplayText}, value: {enumerator.Current.Value}");
    }
}

// We can also remove elements one at a time
listItems.RemoveAt(3);
Assert.AreEqual(3, listItems.Count);

// Make sure to update the SelectedValue's index if it ever ends up out of bounds before saving the document
listItems.SelectedValue = listItems[1];

doc.Save(ArtifactsDir + "SDT.ListItemCollection.docx");

// We can clear the whole collection at once too
listItems.Clear();
Assert.AreEqual(0, listItems.Count);

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


LockContentControl Property

Aspose.Words

StructuredDocumentTag.LockContentControl Property

When set to true, this property will prohibit a user from deleting this SDT.

[Visual Basic]
Public Property LockContentControl As Boolean
[C#]
public bool LockContentControl {get; set;}

Example

Shows how to restrict the editing of a StructuredDocumentTag.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a plain text StructuredDocumentTag of the PlainText type, which will function like a text box
// It contains a default "Click here to enter text." prompt, which we can click and replace with our own text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// We can prohibit the users from editing the inner text in Microsoft Word by setting this to true
tag.LockContents = true;
builder.Write("The contents of this StructuredDocumentTag cannot be edited: ");
builder.InsertNode(tag);

tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Setting this to true will disable the deletion of this StructuredDocumentTag
// by text editing operations in Microsoft Word
tag.LockContentControl = true;

builder.InsertParagraph();
builder.Write("This StructuredDocumentTag cannot be deleted but its contents can be edited: ");
builder.InsertNode(tag);

doc.Save(ArtifactsDir + "SDT.Lock.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


LockContents Property

Aspose.Words

StructuredDocumentTag.LockContents Property

When set to true, this property will prohibit a user from editing the contents of this SDT.

[Visual Basic]
Public Property LockContents As Boolean
[C#]
public bool LockContents {get; set;}

Example

Shows how to restrict the editing of a StructuredDocumentTag.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a plain text StructuredDocumentTag of the PlainText type, which will function like a text box
// It contains a default "Click here to enter text." prompt, which we can click and replace with our own text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// We can prohibit the users from editing the inner text in Microsoft Word by setting this to true
tag.LockContents = true;
builder.Write("The contents of this StructuredDocumentTag cannot be edited: ");
builder.InsertNode(tag);

tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Setting this to true will disable the deletion of this StructuredDocumentTag
// by text editing operations in Microsoft Word
tag.LockContentControl = true;

builder.InsertParagraph();
builder.Write("This StructuredDocumentTag cannot be deleted but its contents can be edited: ");
builder.InsertNode(tag);

doc.Save(ArtifactsDir + "SDT.Lock.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Multiline Property

Aspose.Words

StructuredDocumentTag.Multiline Property

Specifies whether this SDT allows multiple lines of text.

[Visual Basic]
Public Property Multiline As Boolean
[C#]
public bool Multiline {get; set;}

Remarks

Accessing this property will only work for RichText and PlainText SDT type.

For all other SDT types exception will occur.

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


NodeType Property

Aspose.Words

StructuredDocumentTag.NodeType Property

Returns NodeType.StructuredDocumentTag.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to work with styles for content control elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Get specific style from the document to apply it to an SDT
Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
StructuredDocumentTag sdtPlainText = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
sdtPlainText.Style = quoteStyle;

StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
sdtRichText.StyleName = "Quote"; // Second method to apply specific style to an SDT control

// Insert content controls into the document
builder.InsertNode(sdtPlainText);
builder.InsertNode(sdtRichText);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

// We can get a collection of StructuredDocumentTags by looking for the document's child nodes of this NodeType
Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (Node node in tags)
{
    StructuredDocumentTag sdt = (StructuredDocumentTag) node;
    // If style was not defined before, style should be "Default Paragraph Font"
    Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
    Assert.AreEqual("Quote", sdt.StyleName);
}

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Placeholder Property

Aspose.Words

StructuredDocumentTag.Placeholder Property

Gets the BuildingBlock containing placeholder text which should be displayed when this SDT run contents are empty, the associated mapped XML element is empty as specified via the XmlMapping element or the IsShowingPlaceholderText element is true.

[Visual Basic]
Public ReadOnly Property Placeholder As BuildingBlock
[C#]
public BuildingBlock Placeholder {get;}

Remarks

Can be null, meaning that the placeholder is not applicable for this Sdt.

Example

Shows how to use the contents of a BuildingBlock as a custom placeholder text for a StructuredDocumentTag.

[C#]

Document doc = new Document();

// Insert a plain text StructuredDocumentTag of the PlainText type, which will function like a text box
// It contains a default "Click here to enter text." prompt, which we can click and replace with our own text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// We can substitute that default placeholder with a custom phrase, which will be drawn from a BuildingBlock
// First we will need to create the BuildingBlock, give it content and add it to the GlossaryDocument
GlossaryDocument glossaryDoc = doc.GlossaryDocument;

BuildingBlock substituteBlock = new BuildingBlock(glossaryDoc);
substituteBlock.Name = "Custom Placeholder";
substituteBlock.AppendChild(new Section(glossaryDoc));
substituteBlock.FirstSection.AppendChild(new Body(glossaryDoc));
substituteBlock.FirstSection.Body.AppendParagraph("Custom placeholder text.");

glossaryDoc.AppendChild(substituteBlock);

// The substitute BuildingBlock we made can be referenced by name
tag.PlaceholderName = "Custom Placeholder";

// If PlaceholderName refers to an existing block in the parent document's GlossaryDocument,
// the BuildingBlock will be automatically found and assigned to the Placeholder attribute
Assert.AreEqual(substituteBlock, tag.Placeholder);

// Setting this to true will register the text inside the StructuredDocumentTag as placeholder text
// This means that, in Microsoft Word, all the text contents of the StructuredDocumentTag will be highlighted with one click,
// so we can immediately replace the entire substitute text by typing
// If this is false, the text will behave like an ordinary Paragraph and a cursor will be placed with nothing highlighted
tag.IsShowingPlaceholderText = true;

// Insert the StructuredDocumentTag into the document using a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

doc.Save(ArtifactsDir + "SDT.PlaceholderBuildingBlock.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


PlaceholderName Property

Aspose.Words

StructuredDocumentTag.PlaceholderName Property

Gets or sets Name of the BuildingBlock containing placeholder text.

BuildingBlock with this name Name has to be present in the GlossaryDocument otherwise InvalidOperationException will occur.

[Visual Basic]
Public Property PlaceholderName As String
[C#]
public string PlaceholderName {get; set;}

Example

Shows how to use the contents of a BuildingBlock as a custom placeholder text for a StructuredDocumentTag.

[C#]

Document doc = new Document();

// Insert a plain text StructuredDocumentTag of the PlainText type, which will function like a text box
// It contains a default "Click here to enter text." prompt, which we can click and replace with our own text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// We can substitute that default placeholder with a custom phrase, which will be drawn from a BuildingBlock
// First we will need to create the BuildingBlock, give it content and add it to the GlossaryDocument
GlossaryDocument glossaryDoc = doc.GlossaryDocument;

BuildingBlock substituteBlock = new BuildingBlock(glossaryDoc);
substituteBlock.Name = "Custom Placeholder";
substituteBlock.AppendChild(new Section(glossaryDoc));
substituteBlock.FirstSection.AppendChild(new Body(glossaryDoc));
substituteBlock.FirstSection.Body.AppendParagraph("Custom placeholder text.");

glossaryDoc.AppendChild(substituteBlock);

// The substitute BuildingBlock we made can be referenced by name
tag.PlaceholderName = "Custom Placeholder";

// If PlaceholderName refers to an existing block in the parent document's GlossaryDocument,
// the BuildingBlock will be automatically found and assigned to the Placeholder attribute
Assert.AreEqual(substituteBlock, tag.Placeholder);

// Setting this to true will register the text inside the StructuredDocumentTag as placeholder text
// This means that, in Microsoft Word, all the text contents of the StructuredDocumentTag will be highlighted with one click,
// so we can immediately replace the entire substitute text by typing
// If this is false, the text will behave like an ordinary Paragraph and a cursor will be placed with nothing highlighted
tag.IsShowingPlaceholderText = true;

// Insert the StructuredDocumentTag into the document using a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

doc.Save(ArtifactsDir + "SDT.PlaceholderBuildingBlock.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


SdtType Property

Aspose.Words

StructuredDocumentTag.SdtType Property

Gets type of this Structured document tag.

[Visual Basic]
Public ReadOnly Property SdtType As SdtType
[C#]
public SdtType SdtType {get;}

Example

Shows how to get type of structured document tag.

[C#]

Document doc = new Document(MyDir + "TestRepeatingSection.docx");

NodeCollection sdTags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (StructuredDocumentTag sdTag in sdTags.OfType<StructuredDocumentTag>())
{
    Console.WriteLine("Type of this SDT is: {0}", sdTag.SdtType);
}

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Style Property

Aspose.Words

StructuredDocumentTag.Style Property

Gets or sets the Style of the structured document tag.

[Visual Basic]
Public Property Style As Style
[C#]
public Style Style {get; set;}

Remarks

Only Character style or Paragraph style with linked character style can be set.

Example

Shows how to work with styles for content control elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Get specific style from the document to apply it to an SDT
Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
StructuredDocumentTag sdtPlainText = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
sdtPlainText.Style = quoteStyle;

StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
sdtRichText.StyleName = "Quote"; // Second method to apply specific style to an SDT control

// Insert content controls into the document
builder.InsertNode(sdtPlainText);
builder.InsertNode(sdtRichText);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

// We can get a collection of StructuredDocumentTags by looking for the document's child nodes of this NodeType
Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (Node node in tags)
{
    StructuredDocumentTag sdt = (StructuredDocumentTag) node;
    // If style was not defined before, style should be "Default Paragraph Font"
    Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
    Assert.AreEqual("Quote", sdt.StyleName);
}

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StyleName Property

Aspose.Words

StructuredDocumentTag.StyleName Property

Gets or sets the name of the style applied to the structured document tag.

[Visual Basic]
Public Property StyleName As String
[C#]
public string StyleName {get; set;}

Example

Shows how to work with styles for content control elements.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Get specific style from the document to apply it to an SDT
Style quoteStyle = doc.Styles[StyleIdentifier.Quote];
StructuredDocumentTag sdtPlainText = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);
sdtPlainText.Style = quoteStyle;

StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Inline);
sdtRichText.StyleName = "Quote"; // Second method to apply specific style to an SDT control

// Insert content controls into the document
builder.InsertNode(sdtPlainText);
builder.InsertNode(sdtRichText);

MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);

// We can get a collection of StructuredDocumentTags by looking for the document's child nodes of this NodeType
Assert.AreEqual(NodeType.StructuredDocumentTag, sdtPlainText.NodeType);

NodeCollection tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);

foreach (Node node in tags)
{
    StructuredDocumentTag sdt = (StructuredDocumentTag) node;
    // If style was not defined before, style should be "Default Paragraph Font"
    Assert.AreEqual(StyleIdentifier.Quote, sdt.Style.StyleIdentifier);
    Assert.AreEqual("Quote", sdt.StyleName);
}

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Tag Property

Aspose.Words

StructuredDocumentTag.Tag Property

Specifies a tag associated with the current SDT node. Can not be null.

[Visual Basic]
Public Property Tag As String
[C#]
public string Tag {get; set;}

Remarks

A tag is an arbitrary string which applications can associate with SDT in order to identify it without providing a visible friendly name.

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Title Property

Aspose.Words

StructuredDocumentTag.Title Property

Specifies the friendly name associated with this SDT. Can not be null.

[Visual Basic]
Public Property Title As String
[C#]
public string Title {get; set;}

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


XmlMapping Property

Aspose.Words

StructuredDocumentTag.XmlMapping Property

Gets an object that represents the mapping of this structured document tag to XML data in a custom XML part of the current document.

[Visual Basic]
Public ReadOnly Property XmlMapping As XmlMapping
[C#]
public XmlMapping XmlMapping {get;}

Remarks

You can use the SetMapping method of this object to map a structured document tag to XML data.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag Methods

The methods of the StructuredDocumentTag class are listed below. For a complete list of StructuredDocumentTag class members, see the StructuredDocumentTag Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clear | Clears contents of this structured document tag and displays a placeholder if it is defined.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSelfOnly | Removes just this SDT node itself, but keeps the content of it inside the document tree.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitStructuredDocumentTagStart, then calls Accept for all child nodes of the smart tag and calls VisitStructuredDocumentTagEnd at the end.

Example

Traverse a document with a visitor that prints all structured document tag nodes that it encounters.

[C#]

public void StructuredDocumentTagToText()
{
    // Open the document that has structured document tags we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    StructuredDocumentTagInfoPrinter visitor = new StructuredDocumentTagInfoPrinter();

    // Accepring a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about structured document tags encountered in the document.
/// </summary>
public class StructuredDocumentTagInfoPrinter : DocumentVisitor
{
    public StructuredDocumentTagInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideStructuredDocumentTag = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideStructuredDocumentTag) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a StructuredDocumentTag node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitStructuredDocumentTagStart(StructuredDocumentTag sdt)
    {
        IndentAndAppendLine("[StructuredDocumentTag start] Title: " + sdt.Title);
        mDocTraversalDepth++;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a StructuredDocumentTag node is ended.
    /// </summary>
    public override VisitorAction VisitStructuredDocumentTagEnd(StructuredDocumentTag sdt)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[StructuredDocumentTag end]");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private readonly bool mVisitorIsInsideStructuredDocumentTag;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag.Clear Method

Clears contents of this structured document tag and displays a placeholder if it is defined.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Remarks

It is not possible to clear contents of a structured document tag if it has revisions.

If this structured document tag is mapped to custom XML (with using the XmlMapping property), the referenced XML node is cleared.

Example

Shows how to delete content of StructuredDocumentTag elements.

[C#]

Document doc = new Document(MyDir + "TestRepeatingSection.docx");

NodeCollection sdts = doc.GetChildNodes(NodeType.StructuredDocumentTag, true);
Assert.IsNotNull(sdts);

foreach (StructuredDocumentTag sdt in sdts.OfType<StructuredDocumentTag>())
{
    sdt.Clear();
}

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


StructuredDocumentTag.RemoveSelfOnly Method

Removes just this SDT node itself, but keeps the content of it inside the document tree.

[Visual Basic]
Public Sub RemoveSelfOnly()
[C#]
public void RemoveSelfOnly();

Example

Shows how to create a StructuredDocumentTag in the form of a plain text box and modify its appearance.

[C#]

// Create a new document
Document doc = new Document();

// Create a StructuredDocumentTag that will contain plain text
StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Inline);

// Set the title and color of the frame that appears when you mouse over it
tag.Title = "My plain text";
tag.Color = Color.Magenta;

// Set a programmatic tag for this StructuredDocumentTag
// Unlike the title, this value will not be visible in the document but will be programmatically obtainable
// as an XML element named "tag", with the string below in its "@val" attribute
tag.Tag = "MyPlainTextSDT";

// Every StructuredDocumentTag gets a random unique ID
Assert.Positive(tag.Id);

// Set the font for the text inside the StructuredDocumentTag
tag.ContentsFont.Name = "Arial";

// Set the font for the text at the end of the StructuredDocumentTag
// Any text that's typed in the document body after moving out of the tag with arrow keys will keep this font
tag.EndCharacterFont.Name = "Arial Black";

// By default, this is false and pressing enter while inside a StructuredDocumentTag does nothing
// When set to true, our StructuredDocumentTag can have multiple lines
tag.Multiline = true;

// Insert the StructuredDocumentTag into the document with a DocumentBuilder and save the document to a file
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(tag);

// Insert a clone of our StructuredDocumentTag in a new paragraph
StructuredDocumentTag tagClone = (StructuredDocumentTag)tag.Clone(true);
builder.InsertParagraph();
builder.InsertNode(tagClone);

// We can remove the tag while keeping its contents where they were in the Paragraph by calling RemoveSelfOnly()
tagClone.RemoveSelfOnly();

doc.Save(ArtifactsDir + "SDT.PlainText.docx");

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


XmlMapping Class

Specifies the information that is used to establish a mapping between the parent structured document tag and an XML element stored within a custom XML data part in the document.

For a list of all members of this type, see XmlMapping Members.

System.Object
Aspose.Words.Markup.XmlMapping

[Visual Basic]
Public Class XmlMapping
[C#]
public class XmlMapping

Requirements

Namespace: Aspose.Words.Markup

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

XmlMapping Members | Aspose.Words.Markup Namespace


XmlMapping Members

XmlMapping overview

Public Instance Properties

CustomXmlPart | Returns the custom XML data part to which the parent structured document tag is mapped.
IsMapped | Returns true if the parent structured document tag is successfully mapped to XML data.
PrefixMappings | Returns XML namespace prefix mappings to evaluate the XPath.
StoreItemId | Specifies the custom XML data identifier for the custom XML data part which shall be used to evaluate the XPath expression.
XPath | Returns the XPath expression, which is evaluated to find the custom XML node that is mapped to the parent structured document tag.

Public Instance Methods

Delete | Deletes mapping of the parent structured document to XML data.
SetMapping | Sets a mapping between the parent structured document tag and an XML node of a custom XML data part.

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


XmlMapping Properties

The properties of the XmlMapping class are listed below. For a complete list of XmlMapping class members, see the XmlMapping Members topic.

Public Instance Properties

CustomXmlPart | Returns the custom XML data part to which the parent structured document tag is mapped.
IsMapped | Returns true if the parent structured document tag is successfully mapped to XML data.
PrefixMappings | Returns XML namespace prefix mappings to evaluate the XPath.
StoreItemId | Specifies the custom XML data identifier for the custom XML data part which shall be used to evaluate the XPath expression.
XPath | Returns the XPath expression, which is evaluated to find the custom XML node that is mapped to the parent structured document tag.

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


CustomXmlPart Property

Aspose.Words

XmlMapping.CustomXmlPart Property

Returns the custom XML data part to which the parent structured document tag is mapped.

[Visual Basic]
Public ReadOnly Property CustomXmlPart As CustomXmlPart
[C#]
public CustomXmlPart CustomXmlPart {get;}

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


IsMapped Property

Aspose.Words

XmlMapping.IsMapped Property

Returns true if the parent structured document tag is successfully mapped to XML data.

[Visual Basic]
Public ReadOnly Property IsMapped As Boolean
[C#]
public bool IsMapped {get;}

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


PrefixMappings Property

Aspose.Words

XmlMapping.PrefixMappings Property

Returns XML namespace prefix mappings to evaluate the XPath.

[Visual Basic]
Public ReadOnly Property PrefixMappings As String
[C#]
public string PrefixMappings {get;}

Remarks

Specifies the set of prefix mappings, which shall be used to interpret the XPath expression when the XPath expression is evaluated against the custom XML data parts in the document.

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


StoreItemId Property

Aspose.Words

XmlMapping.StoreItemId Property

Specifies the custom XML data identifier for the custom XML data part which shall be used to evaluate the XPath expression.

[Visual Basic]
Public ReadOnly Property StoreItemId As String
[C#]
public string StoreItemId {get;}

Example

Shows how to get special id of your xml part.

[C#]

Document doc = new Document(ArtifactsDir + "SDT.CustomXml.docx");

StructuredDocumentTag sdt = (StructuredDocumentTag) doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
Console.WriteLine("The Id of your custom xml part is: " + sdt.XmlMapping.StoreItemId);

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


XPath Property

Aspose.Words

XmlMapping.XPath Property

Returns the XPath expression, which is evaluated to find the custom XML node that is mapped to the parent structured document tag.

[Visual Basic]
Public ReadOnly Property XPath As String
[C#]
public string XPath {get;}

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


XmlMapping Methods

The methods of the XmlMapping class are listed below. For a complete list of XmlMapping class members, see the XmlMapping Members topic.

Public Instance Methods

Delete | Deletes mapping of the parent structured document to XML data.
SetMapping | Sets a mapping between the parent structured document tag and an XML node of a custom XML data part.

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


XmlMapping.Delete Method

Deletes mapping of the parent structured document to XML data.

[Visual Basic]
Public Sub Delete()
[C#]
public void Delete();

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


XmlMapping.SetMapping Method

Sets a mapping between the parent structured document tag and an XML node of a custom XML data part.

[Visual Basic]
Public Function SetMapping( _
ByVal customXmlPart As CustomXmlPart, _
ByVal xPath As String, _
ByVal prefixMapping As String _
) As Boolean
[C#]
public bool SetMapping(
CustomXmlPart customXmlPart,
string xPath,
string prefixMapping
);

Parameters

customXmlPart
A custom XML data part to map to.
xPath
An XPath expression to find the XML node.
prefixMapping
XML namespace prefix mappings to evaluate the XPath.

Return Value

A flag indicating whether the parent structured document tag is successfully mapped to the XML node.

Example

Shows how to create structured document tag with a custom XML data.

[C#]

Document doc = new Document();

// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Mircosoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
string xmlPartId = Guid.NewGuid().ToString("B");
string xmlPartContent = "<root><text>Hello, World!</text></root>";
CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

// The data we entered resides in these variables
Assert.AreEqual(xmlPartContent.ToCharArray(), xmlPart.Data);
Assert.AreEqual(xmlPartId, xmlPart.Id);

// XML parts can be referenced by collection index or GUID
Assert.AreEqual(xmlPart, doc.CustomXmlParts[0]);
Assert.AreEqual(xmlPart, doc.CustomXmlParts.GetById(xmlPartId));

// Once the part is created, we can add XML schema associations like this
xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

// We can also clone parts and insert them into the collection directly
CustomXmlPart xmlPartClone = xmlPart.Clone();
xmlPartClone.Id = Guid.NewGuid().ToString("B");
doc.CustomXmlParts.Add(xmlPartClone);

Assert.AreEqual(2, doc.CustomXmlParts.Count);

// Iterate through collection with an enumerator and print the contents of each part
using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
{
    int index = 0;
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
        Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
        index++;
    }
}

// XML parts can be removed by index
doc.CustomXmlParts.RemoveAt(1);

Assert.AreEqual(1, doc.CustomXmlParts.Count);

// The XML part collection itself can be cloned also
CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();

// And all elements can be cleared like this
customXmlParts.Clear();

// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
sdt.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", "");

doc.FirstSection.Body.AppendChild(sdt);

doc.Save(ArtifactsDir + "SDT.CustomXml.docx");

See Also

XmlMapping Class | Aspose.Words.Markup Namespace


Aspose.Words.Math

Aspose.Words

Aspose.Words.Math Namespace

The Aspose.Words.Math namespace contains classes that represent Office Math elements.

Namespace hierarchy

Classes

Class | Description
OfficeMath | Represents an Office Math object such as function, equation, matrix or alike. Can contain child elements including runs of mathematical text, bookmarks, comments, other OfficeMath instances and some other nodes.

Enumerations

Enumeration | Description
MathObjectType | Specifies type of an Office Math object.
OfficeMathDisplayType | Specifies the display format type of the equation.
OfficeMathJustification | Specifies the justification of the equation.


MathObjectType Enumeration

Specifies type of an Office Math object.

[Visual Basic]
Public Enum MathObjectType
[C#]
public enum MathObjectType

Example

Traverse a document with a visitor that prints all OfficeMath nodes that it encounters.

[C#]

public void OfficeMathToText()
{
    // Open the document that has office math objects we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    OfficeMathInfoPrinter visitor = new OfficeMathInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about office math objects encountered in the document.
/// </summary>
public class OfficeMathInfoPrinter : DocumentVisitor
{
    public OfficeMathInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideOfficeMath = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideOfficeMath) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an OfficeMath node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitOfficeMathStart(OfficeMath officeMath)
    {
        IndentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.MathObjectType);
        mDocTraversalDepth++;
        mVisitorIsInsideOfficeMath = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a OfficeMath node is ended.
    /// </summary>
    public override VisitorAction VisitOfficeMathEnd(OfficeMath officeMath)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[OfficeMath end]");
        mVisitorIsInsideOfficeMath = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideOfficeMath;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

Members

Member Name | Description | Value
OMath | Instance of mathematical text. | 0
OMathPara | Math paragraph, or display math zone, that contains one or more OMath elements that are in display mode. | 1
Accent | Accent function, consisting of a base and a combining diacritical mark. | 2
Bar | Bar function, consisting of a base argument and an overbar or underbar. | 3
BorderBox | Border Box object, consisting of a border drawn around an instance of mathematical text (such as a formula or equation) | 4
Box | Box object, which is used to group components of an equation or other instance of mathematical text. | 5
Delimiter | Delimiter object, consisting of opening and closing delimiters (such as parentheses, braces, brackets, and vertical bars), and an element contained inside. | 6
Degree | Degree in the mathematical radical. | 7
Argument | Argument object. Encloses Office Math entities when they are used as arguments to other Office Math entities. | 8
Array | Array object, consisting of one or more equations, expressions, or other mathematical text runs that can be vertically justified as a unit with respect to surrounding text on the line. | 9
Fraction | Fraction object, consisting of a numerator and denominator separated by a fraction bar. | 10
Denominator | Denominator of a fraction object. | 11
Numerator | Numerator of the Fraction object. | 12
Function | Function-Apply object, which consists of a function name and an argument element acted upon. | 13
FunctionName | Name of the function. For example, function names are sin and cos. | 14
GroupCharacter | Group-Character object, consisting of a character drawn above or below text, often with the purpose of visually grouping items | 15
Limit | Lower limit of the LowerLimit object and the upper limit of the UpperLimit function. | 16
LowerLimit | Lower-Limit object, consisting of text on the baseline and reduced-size text immediately below it. | 17
UpperLimit | Upper-Limit object, consisting of text on the baseline and reduced-size text immediately above it. | 18
Matrix | Matrix object, consisting of one or more elements laid out in one or more rows and one or more columns. | 19
MatrixRow | Single row of the matrix. | 20
NAry | N-ary object, consisting of an n-ary object, a base (or operand), and optional upper and lower limits. | 21
Phantom | Phantom object. | 22
Radical | Radical object, consisting of a radical, a base element, and an optional degree . | 23
SubscriptPart | Subscript of the object that can have subscript part. | 24
SuperscriptPart | Superscript of the superscript object. | 25
PreSubSuperscript | Pre-Sub-Superscript object, which consists of a base element and a subscript and superscript placed to the left of the base. | 26
Subscript | Subscript object, which consists of a base element and a reduced-size script placed below and to the right. | 27
SubSuperscript | Sub-superscript object, which consists of a base element, a reduced-size script placed below and to the right, and a reduced-size script placed above and to the right. | 28
Supercript | Superscript object, which consists of a base element and a reduced-size script placed above and to the right. | 29

Requirements

Namespace: Aspose.Words.Math

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Math Namespace


OfficeMath Class

Represents an Office Math object such as function, equation, matrix or alike. Can contain child elements including runs of mathematical text, bookmarks, comments, other OfficeMath instances and some other nodes.

For a list of all members of this type, see OfficeMath Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Math.OfficeMath

[Visual Basic]
Public Class OfficeMath
Inherits CompositeNode
[C#]
public class OfficeMath : CompositeNode

Remarks

In this version of Aspose.Words, OfficeMath nodes do not provide public methods and properties to create or modify a OfficeMath object. In this version you are not able to instantiate Aspose.Words.Math nodes or modify existing except deleting them.

OfficeMath can only be a child of Paragraph.

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

Requirements

Namespace: Aspose.Words.Math

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OfficeMath Members | Aspose.Words.Math Namespace


OfficeMath Members

OfficeMath overview

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DisplayType | Gets/sets Office Math display format type which represents whether an equation is displayed inline with the text or displayed on its own line.
Document (inherited from Node) | Gets the document to which this node belongs.
EquationXmlEncoding | Gets/sets an encoding that was used to encode equation XML, if this office math object is read from equation XML. We use the encoding on saving a document to write in same encoding that it was read.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
Justification | Gets/sets Office Math justification.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
MathObjectType | Gets type MathObjectType of this Office Math object.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.OfficeMath.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetMathRenderer | Creates and returns an object that can be used to render this equation into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString | Overloaded.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

OfficeMath Class | Aspose.Words.Math Namespace


OfficeMath Properties

The properties of the OfficeMath class are listed below. For a complete list of OfficeMath class members, see the OfficeMath Members topic.

Public Instance Properties

ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
DisplayType | Gets/sets Office Math display format type which represents whether an equation is displayed inline with the text or displayed on its own line.
Document (inherited from Node) | Gets the document to which this node belongs.
EquationXmlEncoding | Gets/sets an encoding that was used to encode equation XML, if this office math object is read from equation XML. We use the encoding on saving a document to write in same encoding that it was read.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
Justification | Gets/sets Office Math justification.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
MathObjectType | Gets type MathObjectType of this Office Math object.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.OfficeMath.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentParagraph | Retrieves the parent Paragraph of this node.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.

See Also

OfficeMath Class | Aspose.Words.Math Namespace


DisplayType Property

Aspose.Words

OfficeMath.DisplayType Property

Gets/sets Office Math display format type which represents whether an equation is displayed inline with the text or displayed on its own line.

[Visual Basic]
Public Property DisplayType As OfficeMathDisplayType
[C#]
public OfficeMathDisplayType DisplayType {get; set;}

Remarks

Display format type has effect for top level Office Math only.

Returned display format type is always Inline for nested Office Math.

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

See Also

OfficeMath Class | Aspose.Words.Math Namespace


EquationXmlEncoding Property

Aspose.Words

OfficeMath.EquationXmlEncoding Property

Gets/sets an encoding that was used to encode equation XML, if this office math object is read from equation XML. We use the encoding on saving a document to write in same encoding that it was read.

[Visual Basic]
Public Property EquationXmlEncoding As Encoding
[C#]
public Encoding EquationXmlEncoding {get; set;}

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

See Also

OfficeMath Class | Aspose.Words.Math Namespace


Justification Property

Aspose.Words

OfficeMath.Justification Property

Gets/sets Office Math justification.

[Visual Basic]
Public Property Justification As OfficeMathJustification
[C#]
public OfficeMathJustification Justification {get; set;}

Remarks

Justification cannot be set to the Office Math with display format type Inline.

Inline justification cannot be set to the Office Math with display format type Display.

Corresponding DisplayType has to be set before setting Office Math justification.

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

See Also

OfficeMath Class | Aspose.Words.Math Namespace


MathObjectType Property

Aspose.Words

OfficeMath.MathObjectType Property

Gets type MathObjectType of this Office Math object.

[Visual Basic]
Public ReadOnly Property MathObjectType As MathObjectType
[C#]
public MathObjectType MathObjectType {get;}

Example

Traverse a document with a visitor that prints all OfficeMath nodes that it encounters.

[C#]

public void OfficeMathToText()
{
    // Open the document that has office math objects we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    OfficeMathInfoPrinter visitor = new OfficeMathInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about office math objects encountered in the document.
/// </summary>
public class OfficeMathInfoPrinter : DocumentVisitor
{
    public OfficeMathInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideOfficeMath = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideOfficeMath) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an OfficeMath node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitOfficeMathStart(OfficeMath officeMath)
    {
        IndentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.MathObjectType);
        mDocTraversalDepth++;
        mVisitorIsInsideOfficeMath = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a OfficeMath node is ended.
    /// </summary>
    public override VisitorAction VisitOfficeMathEnd(OfficeMath officeMath)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[OfficeMath end]");
        mVisitorIsInsideOfficeMath = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideOfficeMath;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

OfficeMath Class | Aspose.Words.Math Namespace


NodeType Property

Aspose.Words

OfficeMath.NodeType Property

Returns NodeType.OfficeMath.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

See Also

OfficeMath Class | Aspose.Words.Math Namespace


ParentParagraph Property

Aspose.Words

OfficeMath.ParentParagraph Property

Retrieves the parent Paragraph of this node.

[Visual Basic]
Public ReadOnly Property ParentParagraph As Paragraph
[C#]
public Paragraph ParentParagraph {get;}

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

See Also

OfficeMath Class | Aspose.Words.Math Namespace


OfficeMath Methods

The methods of the OfficeMath class are listed below. For a complete list of OfficeMath class members, see the OfficeMath Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetMathRenderer | Creates and returns an object that can be used to render this equation into an image.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString | Overloaded.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

OfficeMath Class | Aspose.Words.Math Namespace


OfficeMath.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls VisitOfficeMathStart, then calls Accept for all child nodes of the Office Math and calls VisitOfficeMathEnd at the end.

Example

Traverse a document with a visitor that prints all OfficeMath nodes that it encounters.

[C#]

public void OfficeMathToText()
{
    // Open the document that has office math objects we want to print the info of
    Document doc = new Document(MyDir + "DocumentVisitor.Destination.docx");

    // Create an object that inherits from the DocumentVisitor class
    OfficeMathInfoPrinter visitor = new OfficeMathInfoPrinter();

    // Accepting a visitor lets it start traversing the nodes in the document,
    // starting with the node that accepted it to then recursively visit every child
    doc.Accept(visitor);

    // Once the visiting is complete, we can retrieve the result of the operation,
    // that in this example, has accumulated in the visitor
    Console.WriteLine(visitor.GetText());
}

/// <summary>
/// This Visitor implementation prints information about office math objects encountered in the document.
/// </summary>
public class OfficeMathInfoPrinter : DocumentVisitor
{
    public OfficeMathInfoPrinter()
    {
        mBuilder = new StringBuilder();
        mVisitorIsInsideOfficeMath = false;
    }

    /// <summary>
    /// Gets the plain text of the document that was accumulated by the visitor.
    /// </summary>
    public String GetText()
    {
        return mBuilder.ToString();
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (mVisitorIsInsideOfficeMath) IndentAndAppendLine("[Run] \"" + run.Text + "\"");

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when an OfficeMath node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitOfficeMathStart(OfficeMath officeMath)
    {
        IndentAndAppendLine("[OfficeMath start] Math object type: " + officeMath.MathObjectType);
        mDocTraversalDepth++;
        mVisitorIsInsideOfficeMath = true;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when the visiting of a OfficeMath node is ended.
    /// </summary>
    public override VisitorAction VisitOfficeMathEnd(OfficeMath officeMath)
    {
        mDocTraversalDepth--;
        IndentAndAppendLine("[OfficeMath end]");
        mVisitorIsInsideOfficeMath = false;

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
    /// </summary>
    /// <param name="text"></param>
    private void IndentAndAppendLine(String text)
    {
        for (int i = 0; i < mDocTraversalDepth; i++)
        {
            mBuilder.Append("|  ");
        }

        mBuilder.AppendLine(text);
    }

    private bool mVisitorIsInsideOfficeMath;
    private int mDocTraversalDepth;
    private readonly StringBuilder mBuilder;
}

See Also

OfficeMath Class | Aspose.Words.Math Namespace


OfficeMath.GetMathRenderer Method

Creates and returns an object that can be used to render this equation into an image.

[Visual Basic]
Public Function GetMathRenderer() As OfficeMathRenderer
[C#]
public OfficeMathRenderer GetMathRenderer();

Return Value

The renderer object for this equation.

Remarks

This method just invokes the OfficeMathRenderer constructor and passes this object as a parameter.

Example

Shows how to convert specific object into image

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

//Get OfficeMath node from the document and render this as image (you can also do the same with the Shape node)
OfficeMath math = (OfficeMath)doc.GetChild(NodeType.OfficeMath, 0, true);
math.GetMathRenderer().Save(ArtifactsDir + "Shape.OfficeMath.svg", new ImageSaveOptions(SaveFormat.Svg));

See Also

OfficeMath Class | Aspose.Words.Math Namespace


ToString Method

Aspose.Words

OfficeMath.ToString Method

Overload List

public override string ToString();

Inherited from Node.

public string ToString(SaveFormat);

Inherited from Node.

public string ToString(SaveOptions);

See Also

OfficeMath Class | Aspose.Words.Math Namespace


OfficeMath.ToString Method ()

[Visual Basic]
Overrides Overloads Public Function ToString() As String
[C#]
public override string ToString();

See Also

OfficeMath Class | Aspose.Words.Math Namespace | OfficeMath.ToString Overload List


OfficeMathDisplayType Enumeration

Specifies the display format type of the equation.

[Visual Basic]
Public Enum OfficeMathDisplayType
[C#]
public enum OfficeMathDisplayType

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

Members

Member Name | Description | Value
Display | The Office Math is displayed on its own line. | 0
Inline | The Office Math is displayed inline with the text. | 1

Requirements

Namespace: Aspose.Words.Math

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Math Namespace


OfficeMathJustification Enumeration

Specifies the justification of the equation.

[Visual Basic]
Public Enum OfficeMathJustification
[C#]
public enum OfficeMathJustification

Example

Shows how to set office math display formatting.

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

OfficeMath officeMath = (OfficeMath) doc.GetChild(NodeType.OfficeMath, 0, true);

// OfficeMath nodes that are children of other OfficeMath nodes are always inline
// The node we are working with is a base node, so its location and display type can be changed
Assert.AreEqual(MathObjectType.OMathPara, officeMath.MathObjectType);
Assert.AreEqual(NodeType.OfficeMath, officeMath.NodeType);
Assert.AreEqual(officeMath.ParentNode, officeMath.ParentParagraph);

// Used by OOXML and WML formats
Assert.IsNull(officeMath.EquationXmlEncoding);

// We can change the location and display type of the OfficeMath node
officeMath.DisplayType = OfficeMathDisplayType.Display;
officeMath.Justification = OfficeMathJustification.Left;

doc.Save(ArtifactsDir + "Shape.OfficeMath.docx");

Members

Member Name | Description | Value
CenterGroup | Justifies instances of mathematical text to the left with respect to each other, and centers the group of mathematical text (the Math Paragraph) with respect to the page. | 1
Center | Centers each instance of mathematical text individually with respect to margins. | 2
Left | Left justification of Math Paragraph. | 3
Right | Right Justification of Math Paragraph. | 4
Inline | Inline position of Math. | 7
Default | Default value CenterGroup. | 1

Requirements

Namespace: Aspose.Words.Math

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Math Namespace


Aspose.Words.Properties

Aspose.Words

Aspose.Words.Properties Namespace

The Aspose.Words.Properties namespace provides classes to work with custom and built-in document properties such as title, keywords, company etc.

Namespace hierarchy

Classes

Class | Description
BuiltInDocumentProperties | A collection of built-in document properties.
CustomDocumentProperties | A collection of custom document properties.
DocumentProperty | Represents a custom or built-in document property.
DocumentPropertyCollection | Base class for BuiltInDocumentProperties and CustomDocumentProperties collections.

Enumerations

Enumeration | Description
DocumentSecurity | Used as a value for the Security property. Specifies the security level of a document as a numeric value.
PropertyType | Specifies data type of a document property.


BuiltInDocumentProperties Class

A collection of built-in document properties.

For a list of all members of this type, see BuiltInDocumentProperties Members.

System.Object
Aspose.Words.Properties.DocumentPropertyCollection
Aspose.Words.Properties.BuiltInDocumentProperties

[Visual Basic]
Public Class BuiltInDocumentProperties
Inherits DocumentPropertyCollection
[C#]
public class BuiltInDocumentProperties : DocumentPropertyCollection

Remarks

Provides access to DocumentProperty objects by their names (using an indexer) and via a set of typed properties that return values of appropriate types.

The names of the properties are case-insensitive.

The properties in the collection are sorted alphabetically by name.

Example

Enumerates through all built-in and custom properties in a document.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty docProperty in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

Requirements

Namespace: Aspose.Words.Properties

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BuiltInDocumentProperties Members | Aspose.Words.Properties Namespace | Document | BuiltInDocumentProperties | CustomDocumentProperties


BuiltInDocumentProperties Members

BuiltInDocumentProperties overview

Public Instance Properties

Author | Gets or sets the name of the document's author.
Bytes | Represents an estimate of the number of bytes in the document.
Category | Gets or sets the category of the document.
Characters | Represents an estimate of the number of characters in the document.
CharactersWithSpaces | Represents an estimate of the number of characters (including spaces) in the document.
Comments | Gets or sets the document comments.
Company | Gets or sets the company property.
ContentStatus | Gets or sets the ContentStatus of the document.
ContentType | Gets or sets the ContentStatus of the document.
Count (inherited from DocumentPropertyCollection) | Gets number of items in the collection.
CreatedTime | Gets or sets date of the document creation in UTC.
HeadingPairs | Specifies document headings and their names.
HyperlinkBase | Specifies the base string used for evaluating relative hyperlinks in this document.
Item | Overloaded. Returns a DocumentProperty object by the name of the property.
Keywords | Gets or sets the document keywords.
LastPrinted | Gets or sets the date when the document was last printed in UTC.
LastSavedBy | Gets or sets the name of the last author.
LastSavedTime | Gets or sets the time of the last save in UTC.
Lines | Represents an estimate of the number of lines in the document.
LinksUpToDate | Indicates whether hyperlinks in a document are up-to-date.
Manager | Gets or sets the manager property.
NameOfApplication | Gets or sets the name of the application.
Pages | Represents an estimate of the number of pages in the document.
Paragraphs | Represents an estimate of the number of paragraphs in the document.
RevisionNumber | Gets or sets the document revision number.
Security | Specifies the security level of a document as a numeric value.
Subject | Gets or sets the subject of the document.
Template | Gets or sets the informational name of the document template.
Thumbnail | Gets or sets the thumbnail of the document.
Title | Gets or sets the title of the document.
TitlesOfParts | Each string in the array specifies the name of a part in the document.
TotalEditingTime | Gets or sets the total editing time in minutes.
Version | Represents the version number of the application that created the document.
Words | Represents an estimate of the number of words in the document.

Public Instance Methods

Clear (inherited from DocumentPropertyCollection) | Removes all properties from the collection.
Contains (inherited from DocumentPropertyCollection) | Returns true if a property with the specified name exists in the collection.
GetEnumerator (inherited from IEnumerator<DocumentProperty>) | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf (inherited from DocumentPropertyCollection) | Gets the index of a property by name.
Remove (inherited from DocumentPropertyCollection) | Removes a property with the specified name from the collection.
RemoveAt (inherited from DocumentPropertyCollection) | Removes a property at the specified index.

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace | Document | BuiltInDocumentProperties | CustomDocumentProperties


BuiltInDocumentProperties Properties

The properties of the BuiltInDocumentProperties class are listed below. For a complete list of BuiltInDocumentProperties class members, see the BuiltInDocumentProperties Members topic.

Public Instance Properties

Author | Gets or sets the name of the document's author.
Bytes | Represents an estimate of the number of bytes in the document.
Category | Gets or sets the category of the document.
Characters | Represents an estimate of the number of characters in the document.
CharactersWithSpaces | Represents an estimate of the number of characters (including spaces) in the document.
Comments | Gets or sets the document comments.
Company | Gets or sets the company property.
ContentStatus | Gets or sets the ContentStatus of the document.
ContentType | Gets or sets the ContentStatus of the document.
Count (inherited from DocumentPropertyCollection) | Gets number of items in the collection.
CreatedTime | Gets or sets date of the document creation in UTC.
HeadingPairs | Specifies document headings and their names.
HyperlinkBase | Specifies the base string used for evaluating relative hyperlinks in this document.
Item | Overloaded. Returns a DocumentProperty object by the name of the property.
Keywords | Gets or sets the document keywords.
LastPrinted | Gets or sets the date when the document was last printed in UTC.
LastSavedBy | Gets or sets the name of the last author.
LastSavedTime | Gets or sets the time of the last save in UTC.
Lines | Represents an estimate of the number of lines in the document.
LinksUpToDate | Indicates whether hyperlinks in a document are up-to-date.
Manager | Gets or sets the manager property.
NameOfApplication | Gets or sets the name of the application.
Pages | Represents an estimate of the number of pages in the document.
Paragraphs | Represents an estimate of the number of paragraphs in the document.
RevisionNumber | Gets or sets the document revision number.
Security | Specifies the security level of a document as a numeric value.
Subject | Gets or sets the subject of the document.
Template | Gets or sets the informational name of the document template.
Thumbnail | Gets or sets the thumbnail of the document.
Title | Gets or sets the title of the document.
TitlesOfParts | Each string in the array specifies the name of a part in the document.
TotalEditingTime | Gets or sets the total editing time in minutes.
Version | Represents the version number of the application that created the document.
Words | Represents an estimate of the number of words in the document.

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace | Document | BuiltInDocumentProperties | CustomDocumentProperties


Author Property

Aspose.Words

BuiltInDocumentProperties.Author Property

Gets or sets the name of the document's author.

[Visual Basic]
Public Property Author As String
[C#]
public string Author {get; set;}

Example

Shows how to work with document properties in the "Description" category.

[C#]

// Create a blank document
Document doc = new Document();

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Set the values of some descriptive properties
// These are metadata that can be glanced at without opening the document in the "Details" or "Content" folder views in Windows Explorer
// The "Details" view has columns dedicated to these properties
// Fields such as AUTHOR, SUBJECT, TITLE etc. can be used to display these values inside the document
properties.Author = "John Doe";
properties.Title = "John's Document";
properties.Subject = "My subject";
properties.Category = "My category";
properties.Comments = $"This is {properties.Author}'s document about {properties.Subject}";

// Tags can be used as keywords and are separated by semicolons
properties.Keywords = "Tag 1; Tag 2; Tag 3";

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Description
doc.Save(ArtifactsDir + "Properties.Description.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Bytes Property

Aspose.Words

BuiltInDocumentProperties.Bytes Property

Represents an estimate of the number of bytes in the document.

[Visual Basic]
Public Property Bytes As Integer
[C#]
public int Bytes {get; set;}

Remarks

Microsoft Word does not always set this property.

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Category Property

Aspose.Words

BuiltInDocumentProperties.Category Property

Gets or sets the category of the document.

[Visual Basic]
Public Property Category As String
[C#]
public string Category {get; set;}

Example

Shows how to work with document properties in the "Description" category.

[C#]

// Create a blank document
Document doc = new Document();

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Set the values of some descriptive properties
// These are metadata that can be glanced at without opening the document in the "Details" or "Content" folder views in Windows Explorer
// The "Details" view has columns dedicated to these properties
// Fields such as AUTHOR, SUBJECT, TITLE etc. can be used to display these values inside the document
properties.Author = "John Doe";
properties.Title = "John's Document";
properties.Subject = "My subject";
properties.Category = "My category";
properties.Comments = $"This is {properties.Author}'s document about {properties.Subject}";

// Tags can be used as keywords and are separated by semicolons
properties.Keywords = "Tag 1; Tag 2; Tag 3";

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Description
doc.Save(ArtifactsDir + "Properties.Description.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Characters Property

Aspose.Words

BuiltInDocumentProperties.Characters Property

Represents an estimate of the number of characters in the document.

[Visual Basic]
Public Property Characters As Integer
[C#]
public int Characters {get; set;}

Remarks

Aspose.Words updates this property when you call UpdateWordCount.

Example

Shows how to update all list labels in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Some work should be done here that changes the document's content.

// Update the word, character and paragraph count of the document.
doc.UpdateWordCount();

// Display the updated document properties.
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Shows how to work with document properties in the "Content" category.
[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


CharactersWithSpaces Property

Aspose.Words

BuiltInDocumentProperties.CharactersWithSpaces Property

Represents an estimate of the number of characters (including spaces) in the document.

[Visual Basic]
Public Property CharactersWithSpaces As Integer
[C#]
public int CharactersWithSpaces {get; set;}

Remarks

Aspose.Words updates this property when you call UpdateWordCount.

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Comments Property

Aspose.Words

BuiltInDocumentProperties.Comments Property

Gets or sets the document comments.

[Visual Basic]
Public Property Comments As String
[C#]
public string Comments {get; set;}

Example

Shows how to work with document properties in the "Description" category.

[C#]

// Create a blank document
Document doc = new Document();

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Set the values of some descriptive properties
// These are metadata that can be glanced at without opening the document in the "Details" or "Content" folder views in Windows Explorer
// The "Details" view has columns dedicated to these properties
// Fields such as AUTHOR, SUBJECT, TITLE etc. can be used to display these values inside the document
properties.Author = "John Doe";
properties.Title = "John's Document";
properties.Subject = "My subject";
properties.Category = "My category";
properties.Comments = $"This is {properties.Author}'s document about {properties.Subject}";

// Tags can be used as keywords and are separated by semicolons
properties.Keywords = "Tag 1; Tag 2; Tag 3";

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Description
doc.Save(ArtifactsDir + "Properties.Description.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Company Property

Aspose.Words

BuiltInDocumentProperties.Company Property

Gets or sets the company property.

[Visual Basic]
Public Property Company As String
[C#]
public string Company {get; set;}

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


ContentStatus Property

Aspose.Words

BuiltInDocumentProperties.ContentStatus Property

Gets or sets the ContentStatus of the document.

[Visual Basic]
Public Property ContentStatus As String
[C#]
public string ContentStatus {get; set;}

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


ContentType Property

Aspose.Words

BuiltInDocumentProperties.ContentType Property

Gets or sets the ContentStatus of the document.

[Visual Basic]
Public Property ContentType As String
[C#]
public string ContentType {get; set;}

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


CreatedTime Property

Aspose.Words

BuiltInDocumentProperties.CreatedTime Property

Gets or sets date of the document creation in UTC.

[Visual Basic]
Public Property CreatedTime As Date
[C#]
public DateTime CreatedTime {get; set;}

Remarks

For documents originated from RTF format this property returns local time of the author's machine at the moment of document creation.

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


HeadingPairs Property

Aspose.Words

BuiltInDocumentProperties.HeadingPairs Property

Specifies document headings and their names.

[Visual Basic]
Public Property HeadingPairs As Object()
[C#]
public object[] HeadingPairs {get; set;}

Remarks

Every heading pair occupies two elements in this array.

The first element of the pair is a String and specifies the heading name. The second element of the pair is an Int32 and specifies the count of document parts for this heading in the TitlesOfParts property.

The total sum of counts for all heading pairs in this property must be equal to the number of elements in the TitlesOfParts property.

Aspose.Words does not update this property.

Example

Shows the relationship between HeadingPairs and TitlesOfParts properties.

[C#]

// Open a document that contains entries in the HeadingPairs/TitlesOfParts properties
Document doc = new Document(MyDir + "Properties.HeadingPairs.docx");

// We can find the combined values of these collections in File > Properties > Advanced Properties > Contents tab

// The HeadingPairs property is a collection of <string, int> pairs that determines
// how many document parts a heading spans over
object[] headingPairs = doc.BuiltInDocumentProperties.HeadingPairs;

// The TitlesOfParts property contains the names of parts that belong to the above headings
string[] titlesOfParts = doc.BuiltInDocumentProperties.TitlesOfParts;

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace | TitlesOfParts


HyperlinkBase Property

Aspose.Words

BuiltInDocumentProperties.HyperlinkBase Property

Specifies the base string used for evaluating relative hyperlinks in this document.

[Visual Basic]
Public Property HyperlinkBase As String
[C#]
public string HyperlinkBase {get; set;}

Remarks

Aspose.Words does not use this property.

Example

Shows how to store the base part of a hyperlink in the document's properties.

[C#]

// Create a blank document and a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a relative hyperlink to "Document.docx", which will open that document when clicked on
builder.InsertHyperlink("Relative hyperlink", "Document.docx", false);

// If we don't have a "Document.docx" in the same folder as the document we are about to save, we will end up with a broken link
Assert.False(File.Exists(ArtifactsDir + "Document.docx"));
doc.Save(ArtifactsDir + "Properties.HyperlinkBase.BrokenLink.docx");

// We could keep prepending something like "C:\users\...\data" to every hyperlink we place to remedy this
// Alternatively, if we know that all our linked files will come from the same folder,
// we could set a base hyperlink in the document properties, keeping our hyperlinks short
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

Assert.True(File.Exists(MyDir + "Document.docx"));
properties.HyperlinkBase = MyDir;

doc.Save(ArtifactsDir + "Properties.HyperlinkBase.WorkingLink.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Item Property

Aspose.Words

BuiltInDocumentProperties.Item Property

Returns a DocumentProperty object by the name of the property.

[Visual Basic]
Overrides Overloads Public Default ReadOnly Property Item( _
ByVal name As String _
) As DocumentProperty
[C#]
public override DocumentProperty this[
string name
] {get;}

Parameters

name
The case-insensitive name of the property to retrieve.

Remarks

The string names of the properties correspond to the names of the typed properties available from BuiltInDocumentProperties.

If you request a property that is not present in the document, but the name of the property is recognized as a valid built-in name, a new DocumentProperty is created, added to the collection and returned. The newly created property is assigned a default value (empty string, zero, false or DateTime.MinValue depending on the type of the built-in property).

If you request a property that is not present in the document and the name is not recognized as a built-in name, a null is returned.

Example

Retrieves a built-in document property by name.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

DocumentProperty docProperty = doc.BuiltInDocumentProperties["Keywords"];
Console.WriteLine(docProperty.ToString());

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Keywords Property

Aspose.Words

BuiltInDocumentProperties.Keywords Property

Gets or sets the document keywords.

[Visual Basic]
Public Property Keywords As String
[C#]
public string Keywords {get; set;}

Example

Shows how to work with document properties in the "Description" category.

[C#]

// Create a blank document
Document doc = new Document();

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Set the values of some descriptive properties
// These are metadata that can be glanced at without opening the document in the "Details" or "Content" folder views in Windows Explorer
// The "Details" view has columns dedicated to these properties
// Fields such as AUTHOR, SUBJECT, TITLE etc. can be used to display these values inside the document
properties.Author = "John Doe";
properties.Title = "John's Document";
properties.Subject = "My subject";
properties.Category = "My category";
properties.Comments = $"This is {properties.Author}'s document about {properties.Subject}";

// Tags can be used as keywords and are separated by semicolons
properties.Keywords = "Tag 1; Tag 2; Tag 3";

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Description
doc.Save(ArtifactsDir + "Properties.Description.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


LastPrinted Property

Aspose.Words

BuiltInDocumentProperties.LastPrinted Property

Gets or sets the date when the document was last printed in UTC.

[Visual Basic]
Public Property LastPrinted As Date
[C#]
public DateTime LastPrinted {get; set;}

Remarks

For documents originated from RTF format this property returns the local time of last print operation.

If the document was never printed, this property will return DateTime.MinValue.

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


LastSavedBy Property

Aspose.Words

BuiltInDocumentProperties.LastSavedBy Property

Gets or sets the name of the last author.

[Visual Basic]
Public Property LastSavedBy As String
[C#]
public string LastSavedBy {get; set;}

Remarks

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


LastSavedTime Property

Aspose.Words

BuiltInDocumentProperties.LastSavedTime Property

Gets or sets the time of the last save in UTC.

[Visual Basic]
Public Property LastSavedTime As Date
[C#]
public DateTime LastSavedTime {get; set;}

Remarks

For documents originated from RTF format this property returns the local time of last save operation.

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Lines Property

Aspose.Words

BuiltInDocumentProperties.Lines Property

Represents an estimate of the number of lines in the document.

[Visual Basic]
Public Property Lines As Integer
[C#]
public int Lines {get; set;}

Remarks

Aspose.Words updates this property when you call UpdateWordCount.

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


LinksUpToDate Property

Aspose.Words

BuiltInDocumentProperties.LinksUpToDate Property

Indicates whether hyperlinks in a document are up-to-date.

[Visual Basic]
Public Property LinksUpToDate As Boolean
[C#]
public bool LinksUpToDate {get; set;}

Remarks

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Manager Property

Aspose.Words

BuiltInDocumentProperties.Manager Property

Gets or sets the manager property.

[Visual Basic]
Public Property Manager As String
[C#]
public string Manager {get; set;}

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


NameOfApplication Property

Aspose.Words

BuiltInDocumentProperties.NameOfApplication Property

Gets or sets the name of the application.

[Visual Basic]
Public Property NameOfApplication As String
[C#]
public string NameOfApplication {get; set;}

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Pages Property

Aspose.Words

BuiltInDocumentProperties.Pages Property

Represents an estimate of the number of pages in the document.

[Visual Basic]
Public Property Pages As Integer
[C#]
public int Pages {get; set;}

Remarks

Aspose.Words updates this property when you call UpdatePageLayout.

Example

Shows how to work with document properties in the "Content" category.

[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Paragraphs Property

Aspose.Words

BuiltInDocumentProperties.Paragraphs Property

Represents an estimate of the number of paragraphs in the document.

[Visual Basic]
Public Property Paragraphs As Integer
[C#]
public int Paragraphs {get; set;}

Remarks

Aspose.Words updates this property when you call UpdateWordCount.

Example

Shows how to update all list labels in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Some work should be done here that changes the document's content.

// Update the word, character and paragraph count of the document.
doc.UpdateWordCount();

// Display the updated document properties.
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Shows how to work with document properties in the "Content" category.
[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


RevisionNumber Property

Aspose.Words

BuiltInDocumentProperties.RevisionNumber Property

Gets or sets the document revision number.

[Visual Basic]
Public Property RevisionNumber As Integer
[C#]
public int RevisionNumber {get; set;}

Remarks

Aspose.Words does not update this property.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Security Property

Aspose.Words

BuiltInDocumentProperties.Security Property

Specifies the security level of a document as a numeric value.

[Visual Basic]
Public Property Security As DocumentSecurity
[C#]
public DocumentSecurity Security {get; set;}

Remarks

Use this property for informational purposes only because Microsoft Word does not always set this property. This property is available in DOC and OOXML documents only.

To protect or unprotect a document use the Protect and Unprotect methods.

Aspose.Words updates this property to a correct value before saving a document.

Example

Shows how to use document properties to display the security level of a document.

[C#]

// Create a blank document, which has no security of any kind by default
Document doc = new Document();

// The "Security" property serves as a description of the security level of a document
Assert.AreEqual(DocumentSecurity.None, doc.BuiltInDocumentProperties.Security);

// Upon saving a document after setting its security level, Aspose automatically updates this property to the appropriate value
doc.WriteProtection.ReadOnlyRecommended = true;
doc.Save(ArtifactsDir + "Properties.Security.ReadOnlyRecommended.docx");

// We can open a document and glance at its security level like this
Assert.AreEqual(DocumentSecurity.ReadOnlyRecommended,
    new Document(ArtifactsDir + "Properties.Security.ReadOnlyRecommended.docx").BuiltInDocumentProperties.Security);

// Create a new document and set it to Write-Protected
doc = new Document();

Assert.False(doc.WriteProtection.IsWriteProtected);
doc.WriteProtection.SetPassword("MyPassword");
Assert.True(doc.WriteProtection.ValidatePassword("MyPassword"));
Assert.True(doc.WriteProtection.IsWriteProtected);
doc.Save(ArtifactsDir + "Properties.Security.ReadOnlyEnforced.docx");

// This document's security level counts as "ReadOnlyEnforced"
Assert.AreEqual(DocumentSecurity.ReadOnlyEnforced,
    new Document(ArtifactsDir + "Properties.Security.ReadOnlyEnforced.docx").BuiltInDocumentProperties.Security);

// Since this is still a descriptive property, we can protect a document and pick a suitable value ourselves
doc = new Document();

doc.Protect(ProtectionType.AllowOnlyComments, "MyPassword");
doc.BuiltInDocumentProperties.Security = DocumentSecurity.ReadOnlyExceptAnnotations;
doc.Save(ArtifactsDir + "Properties.Security.ReadOnlyExceptAnnotations.docx");

Assert.AreEqual(DocumentSecurity.ReadOnlyExceptAnnotations,
    new Document(ArtifactsDir + "Properties.Security.ReadOnlyExceptAnnotations.docx").BuiltInDocumentProperties.Security);

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Subject Property

Aspose.Words

BuiltInDocumentProperties.Subject Property

Gets or sets the subject of the document.

[Visual Basic]
Public Property Subject As String
[C#]
public string Subject {get; set;}

Example

Shows how to work with document properties in the "Description" category.

[C#]

// Create a blank document
Document doc = new Document();

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Set the values of some descriptive properties
// These are metadata that can be glanced at without opening the document in the "Details" or "Content" folder views in Windows Explorer
// The "Details" view has columns dedicated to these properties
// Fields such as AUTHOR, SUBJECT, TITLE etc. can be used to display these values inside the document
properties.Author = "John Doe";
properties.Title = "John's Document";
properties.Subject = "My subject";
properties.Category = "My category";
properties.Comments = $"This is {properties.Author}'s document about {properties.Subject}";

// Tags can be used as keywords and are separated by semicolons
properties.Keywords = "Tag 1; Tag 2; Tag 3";

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Description
doc.Save(ArtifactsDir + "Properties.Description.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Template Property

Aspose.Words

BuiltInDocumentProperties.Template Property

Gets or sets the informational name of the document template.

[Visual Basic]
Public Property Template As String
[C#]
public string Template {get; set;}

Remarks

In Microsoft Word, this property is for informational purposes only and usually contains only the file name of the template without the path.

Empty string means the document is attached to the Normal template.

To get or set the actual name of the attached template, use the AttachedTemplate property.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace | AttachedTemplate


Thumbnail Property

Aspose.Words

BuiltInDocumentProperties.Thumbnail Property

Gets or sets the thumbnail of the document.

[Visual Basic]
Public Property Thumbnail As Byte()
[C#]
public byte[] Thumbnail {get; set;}

Remarks

For now this property is used only when a document is being exported to ePub, it's not read from and written to other document formats.

Image of arbitrary format can be set to this property, but the format is checked during export. InvalidOperationException is thrown if the image is invalid or its format is unsupported for specific format of document.

Only gif, jpeg and png images can be used for ePub publication.

Example

Shows how to append a thumbnail to an Epub document.

[C#]

// Create a blank document and add some text with a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello world!");

// The thumbnail property resides in a document's built in properties, but is used exclusively by Epub e-book documents
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Load an image from our file system into a byte array
byte[] thumbnailBytes = File.ReadAllBytes(ImageDir + "Aspose.Words.gif");

// Set the value of the Thumbnail property to the array from above
properties.Thumbnail = thumbnailBytes;

// Our thumbnail should be visible at the start of the document, before the text we added
doc.Save(ArtifactsDir + "Properties.Thumbnail.epub");

// We can also extract a thumbnail property into a byte array and then into the local file system like this
DocumentProperty thumbnail = doc.BuiltInDocumentProperties["Thumbnail"];
File.WriteAllBytes(ArtifactsDir + "Properties.Thumbnail.gif", thumbnail.ToByteArray());

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Title Property

Aspose.Words

BuiltInDocumentProperties.Title Property

Gets or sets the title of the document.

[Visual Basic]
Public Property Title As String
[C#]
public string Title {get; set;}

Example

Shows how to work with document properties in the "Description" category.

[C#]

// Create a blank document
Document doc = new Document();

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Set the values of some descriptive properties
// These are metadata that can be glanced at without opening the document in the "Details" or "Content" folder views in Windows Explorer
// The "Details" view has columns dedicated to these properties
// Fields such as AUTHOR, SUBJECT, TITLE etc. can be used to display these values inside the document
properties.Author = "John Doe";
properties.Title = "John's Document";
properties.Subject = "My subject";
properties.Category = "My category";
properties.Comments = $"This is {properties.Author}'s document about {properties.Subject}";

// Tags can be used as keywords and are separated by semicolons
properties.Keywords = "Tag 1; Tag 2; Tag 3";

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Description
doc.Save(ArtifactsDir + "Properties.Description.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


TitlesOfParts Property

Aspose.Words

BuiltInDocumentProperties.TitlesOfParts Property

Each string in the array specifies the name of a part in the document.

[Visual Basic]
Public Property TitlesOfParts As String()
[C#]
public string[] TitlesOfParts {get; set;}

Remarks

Aspose.Words does not update this property.

Example

Shows the relationship between HeadingPairs and TitlesOfParts properties.

[C#]

// Open a document that contains entries in the HeadingPairs/TitlesOfParts properties
Document doc = new Document(MyDir + "Properties.HeadingPairs.docx");

// We can find the combined values of these collections in File > Properties > Advanced Properties > Contents tab

// The HeadingPairs property is a collection of <string, int> pairs that determines
// how many document parts a heading spans over
object[] headingPairs = doc.BuiltInDocumentProperties.HeadingPairs;

// The TitlesOfParts property contains the names of parts that belong to the above headings
string[] titlesOfParts = doc.BuiltInDocumentProperties.TitlesOfParts;

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace | HeadingPairs


TotalEditingTime Property

Aspose.Words

BuiltInDocumentProperties.TotalEditingTime Property

Gets or sets the total editing time in minutes.

[Visual Basic]
Public Property TotalEditingTime As Integer
[C#]
public int TotalEditingTime {get; set;}

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Version Property

Aspose.Words

BuiltInDocumentProperties.Version Property

Represents the version number of the application that created the document.

[Visual Basic]
Public Property Version As Integer
[C#]
public int Version {get; set;}

Remarks

When a document was created by Microsoft Word, then high 16 bit represent the major version and low 16 bit represent the build number.

Example

Shows how to work with document properties in the "Origin" category.

[C#]

// Open a document
Document doc = new Document(MyDir + "Properties.doc");

// The properties we will work with are members of the BuiltInDocumentProperties attribute
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Since this document has been edited and printed in the past, values generated by Microsoft Word will appear here
// These values can be glanced at by right clicking the file in Windows Explorer, without actually opening the document
// Fields such as PRINTDATE, EDITTIME etc. can display these values inside the document
Console.WriteLine($"Created using {properties.NameOfApplication}, on {properties.CreatedTime}");
Console.WriteLine($"Minutes spent editing: {properties.TotalEditingTime}");
Console.WriteLine($"Date/time last printed: {properties.LastPrinted}");
Console.WriteLine($"Template document: {properties.Template}");

// We can set these properties ourselves
properties.Company = "Doe Ltd.";
properties.Manager = "Jane Doe";
properties.Version = 5;
properties.RevisionNumber++;

// If we plan on programmatically saving the document, we may record some details like this
properties.LastSavedBy = "John Doe";
properties.LastSavedTime = DateTime.Now;

// When right clicking the document file in Windows Explorer, these properties are found in Properties > Details > Origin
doc.Save(ArtifactsDir + "Properties.Origin.docx");

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


Words Property

Aspose.Words

BuiltInDocumentProperties.Words Property

Represents an estimate of the number of words in the document.

[Visual Basic]
Public Property Words As Integer
[C#]
public int Words {get; set;}

Remarks

Aspose.Words updates this property when you call UpdateWordCount.

Example

Shows how to update all list labels in a document.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Some work should be done here that changes the document's content.

// Update the word, character and paragraph count of the document.
doc.UpdateWordCount();

// Display the updated document properties.
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Shows how to work with document properties in the "Content" category.
[C#]

public void Content()
{
    // Open a document with a couple paragraphs of content
    Document doc = new Document(MyDir + "Properties.Content.docx");

    // The properties we will work with are members of the BuiltInDocumentProperties attribute
    BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

    // By using built in properties,
    // we can treat document statistics such as word/page/character counts as metadata that can be glanced at without opening the document
    // These properties are accessed by right-clicking the file in Windows Explorer and navigating to Properties > Details > Content
    // If we want to display this data inside the document, we can use fields such as NUMPAGES, NUMWORDS, NUMCHARS etc.
    // Also, these values can also be viewed in Microsoft Word by navigating File > Properties > Advanced Properties > Statistics
    // Page count: The PageCount attribute shows the page count in real time and its value can be assigned to the Pages property
    properties.Pages = doc.PageCount;
    Assert.AreEqual(2, properties.Pages);

    // Word count: The UpdateWordCount() automatically assigns the real time word/character counts to the respective built in properties
    doc.UpdateWordCount();
    Assert.AreEqual(198, properties.Words);
    Assert.AreEqual(1114, properties.Characters);
    Assert.AreEqual(1310, properties.CharactersWithSpaces);

    // Line count: Count the lines in a document and assign value to the Lines property\
    LineCounter lineCounter = new LineCounter(doc);
    properties.Lines = lineCounter.GetLineCount();
    Assert.AreEqual(14, properties.Lines);

    // Paragraph count: Assign the size of the count of child Paragraph-nodes to the Paragraphs built in property
    properties.Paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Count;
    Assert.AreEqual(2, properties.Paragraphs);

    // Bytes: Use a stream to find out the real file size of our document and assign it to the Property
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream, SaveFormat.Docx);
        properties.Bytes = (int)stream.Length;
        Assert.AreEqual(10871, properties.Bytes);
    }

    // Template: The Template attribute can reflect the filename of the attached template document
    doc.AttachedTemplate = MyDir + "Document.BusinessBrochureTemplate.dot";
    Assert.AreEqual("Normal", properties.Template);
    properties.Template = doc.AttachedTemplate;

    // Content status: This is a descriptive field
    properties.ContentStatus = "Draft";

    // Content type: Upon saving, any value we assign to this field will be overwritten by the MIME type of the output save format
    Assert.AreEqual("", properties.ContentType);

    // If the document contains links and they are all up to date, we can set this to true
    Assert.False(properties.LinksUpToDate);

    doc.Save(ArtifactsDir + "Properties.Content.docx");
}

/// <summary>
/// Util class that counts the lines in a document
/// Upon construction, traverses the document's layout entities tree, counting entities of the "Line" type that also contain real text
/// </summary>
private class LineCounter
{
    public LineCounter(Document doc)
    {
        mLayoutEnumerator = new LayoutEnumerator(doc);

        CountLines();
    }

    public int GetLineCount()
    {
        return mLineCount;
    }

    private void CountLines()
    {
        do
        {
            if (mLayoutEnumerator.Type == LayoutEntityType.Line)
            {
                mScanningLineForRealText = true;
            }

            if (mLayoutEnumerator.MoveFirstChild())
            {
                if (mScanningLineForRealText && mLayoutEnumerator.Kind.StartsWith("TEXT"))
                {
                    mLineCount++;
                    mScanningLineForRealText = false;
                }
                CountLines();
                mLayoutEnumerator.MoveParent();
            }
        } while (mLayoutEnumerator.MoveNext());
    }

    private readonly LayoutEnumerator mLayoutEnumerator;
    private int mLineCount;
    private bool mScanningLineForRealText;
}

See Also

BuiltInDocumentProperties Class | Aspose.Words.Properties Namespace


CustomDocumentProperties Class

A collection of custom document properties.

For a list of all members of this type, see CustomDocumentProperties Members.

System.Object
Aspose.Words.Properties.DocumentPropertyCollection
Aspose.Words.Properties.CustomDocumentProperties

[Visual Basic]
Public Class CustomDocumentProperties
Inherits DocumentPropertyCollection
[C#]
public class CustomDocumentProperties : DocumentPropertyCollection

Remarks

Each DocumentProperty object represents a custom property of a container document.

The names of the properties are case-insensitive.

The properties in the collection are sorted alphabetically by name.

Example

Enumerates through all built-in and custom properties in a document.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty docProperty in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", docProperty.Name, docProperty.Value);

Requirements

Namespace: Aspose.Words.Properties

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CustomDocumentProperties Members | Aspose.Words.Properties Namespace | Document | BuiltInDocumentProperties | CustomDocumentProperties


CustomDocumentProperties Members

CustomDocumentProperties overview

Public Instance Properties

Count (inherited from DocumentPropertyCollection) | Gets number of items in the collection.
Item (inherited from DocumentPropertyCollection) | Returns a DocumentProperty object by the name of the property.
Item (inherited from DocumentPropertyCollection) | Returns a DocumentProperty object by the name of the property.

Public Instance Methods

Add | Overloaded. Creates a new custom document property.
Clear (inherited from DocumentPropertyCollection) | Removes all properties from the collection.
Contains (inherited from DocumentPropertyCollection) | Returns true if a property with the specified name exists in the collection.
GetEnumerator (inherited from IEnumerator<DocumentProperty>) | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf (inherited from DocumentPropertyCollection) | Gets the index of a property by name.
Remove (inherited from DocumentPropertyCollection) | Removes a property with the specified name from the collection.
RemoveAt (inherited from DocumentPropertyCollection) | Removes a property at the specified index.

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | Document | BuiltInDocumentProperties | CustomDocumentProperties


CustomDocumentProperties Methods

The methods of the CustomDocumentProperties class are listed below. For a complete list of CustomDocumentProperties class members, see the CustomDocumentProperties Members topic.

Public Instance Methods

Add | Overloaded. Creates a new custom document property.
Clear (inherited from DocumentPropertyCollection) | Removes all properties from the collection.
Contains (inherited from DocumentPropertyCollection) | Returns true if a property with the specified name exists in the collection.
GetEnumerator (inherited from IEnumerator<DocumentProperty>) | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf (inherited from DocumentPropertyCollection) | Gets the index of a property by name.
Remove (inherited from DocumentPropertyCollection) | Removes a property with the specified name from the collection.
RemoveAt (inherited from DocumentPropertyCollection) | Removes a property at the specified index.

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | Document | BuiltInDocumentProperties | CustomDocumentProperties


Add Method

Aspose.Words

CustomDocumentProperties.Add Method

Creates a new custom document property.

Overload List

Creates a new custom document property of the PropertyType.Boolean data type.

public DocumentProperty Add(string,bool);

Creates a new custom document property of the PropertyType.DateTime data type.

public DocumentProperty Add(string,DateTime);

Creates a new custom document property of the PropertyType.Float data type.

public DocumentProperty Add(string,double);

Creates a new custom document property of the PropertyType.Number data type.

public DocumentProperty Add(string,int);

Creates a new custom document property of the PropertyType.String data type.

public DocumentProperty Add(string,string);

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace


CustomDocumentProperties.Add Method (String, Boolean)

Creates a new custom document property of the PropertyType.Boolean data type.

[Visual Basic]
Overloads Public Function Add( _
ByVal name As String, _
ByVal value As Boolean _
) As DocumentProperty
[C#]
public DocumentProperty Add(
string name,
bool value
);

Parameters

name
The name of the property.
value
The value of the property.

Return Value

The newly created property object.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | CustomDocumentProperties.Add Overload List


CustomDocumentProperties.Add Method (String, DateTime)

Creates a new custom document property of the PropertyType.DateTime data type.

[Visual Basic]
Overloads Public Function Add( _
ByVal name As String, _
ByVal value As Date _
) As DocumentProperty
[C#]
public DocumentProperty Add(
string name,
DateTime value
);

Parameters

name
The name of the property.
value
The value of the property.

Return Value

The newly created property object.

Example

Retrieves a custom document property by name.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

DocumentProperty docProperty = doc.CustomDocumentProperties["Authorized Date"];

if (docProperty != null)
{
    Console.WriteLine(docProperty.ToDateTime());
}
else
{
    Console.WriteLine("The document is not authorized. Authorizing...");
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now);
}
Shows how to add custom properties to a document.
[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | CustomDocumentProperties.Add Overload List


CustomDocumentProperties.Add Method (String, Double)

Creates a new custom document property of the PropertyType.Float data type.

[Visual Basic]
Overloads Public Function Add( _
ByVal name As String, _
ByVal value As Double _
) As DocumentProperty
[C#]
public DocumentProperty Add(
string name,
double value
);

Parameters

name
The name of the property.
value
The value of the property.

Return Value

The newly created property object.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | CustomDocumentProperties.Add Overload List


CustomDocumentProperties.Add Method (String, Int32)

Creates a new custom document property of the PropertyType.Number data type.

[Visual Basic]
Overloads Public Function Add( _
ByVal name As String, _
ByVal value As Integer _
) As DocumentProperty
[C#]
public DocumentProperty Add(
string name,
int value
);

Parameters

name
The name of the property.
value
The value of the property.

Return Value

The newly created property object.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | CustomDocumentProperties.Add Overload List


CustomDocumentProperties.Add Method (String, String)

Creates a new custom document property of the PropertyType.String data type.

[Visual Basic]
Overloads Public Function Add( _
ByVal name As String, _
ByVal value As String _
) As DocumentProperty
[C#]
public DocumentProperty Add(
string name,
string value
);

Parameters

name
The name of the property.
value
The value of the property.

Return Value

The newly created property object.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

CustomDocumentProperties Class | Aspose.Words.Properties Namespace | CustomDocumentProperties.Add Overload List


DocumentProperty Class

Represents a custom or built-in document property.

For a list of all members of this type, see DocumentProperty Members.

System.Object
Aspose.Words.Properties.DocumentProperty

[Visual Basic]
Public Class DocumentProperty
[C#]
public class DocumentProperty

Remarks

Example

Enumerates through all built-in and custom properties in a document using indexed access.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Requirements

Namespace: Aspose.Words.Properties

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocumentProperty Members | Aspose.Words.Properties Namespace | DocumentPropertyCollection


DocumentProperty Members

DocumentProperty overview

Public Instance Properties

Name | Returns the name of the property.
Type | Gets the data type of the property.
Value | Gets or sets the value of the property.

Public Instance Methods

ToBool | Returns the property value as bool.
ToByteArray | Returns the property value as byte array.
ToDateTime | Returns the property value as DateTime in UTC.
ToDouble | Returns the property value as double.
ToInt | Returns the property value as integer.
ToString | Returns the property value as a string formatted according to the current locale.

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace | DocumentPropertyCollection


DocumentProperty Properties

The properties of the DocumentProperty class are listed below. For a complete list of DocumentProperty class members, see the DocumentProperty Members topic.

Public Instance Properties

Name | Returns the name of the property.
Type | Gets the data type of the property.
Value | Gets or sets the value of the property.

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace | DocumentPropertyCollection


Name Property

Aspose.Words

DocumentProperty.Name Property

Returns the name of the property.

[Visual Basic]
Public ReadOnly Property Name As String
[C#]
public string Name {get;}

Remarks

Cannot be null and cannot be an empty string.

Example

Enumerates through all built-in and custom properties in a document using indexed access.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


Type Property

Aspose.Words

DocumentProperty.Type Property

Gets the data type of the property.

[Visual Basic]
Public ReadOnly Property Type As PropertyType
[C#]
public PropertyType Type {get;}

Example

Enumerates through all built-in and custom properties in a document using indexed access.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}
Retrieves the types and values of the custom document properties.
[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


Value Property

Aspose.Words

DocumentProperty.Value Property

Gets or sets the value of the property.

[Visual Basic]
Public Property Value As Object
[C#]
public object Value {get; set;}

Remarks

Cannot be null.

Example

Enumerates through all built-in and custom properties in a document using indexed access.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentProperty Methods

The methods of the DocumentProperty class are listed below. For a complete list of DocumentProperty class members, see the DocumentProperty Members topic.

Public Instance Methods

ToBool | Returns the property value as bool.
ToByteArray | Returns the property value as byte array.
ToDateTime | Returns the property value as DateTime in UTC.
ToDouble | Returns the property value as double.
ToInt | Returns the property value as integer.
ToString | Returns the property value as a string formatted according to the current locale.

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace | DocumentPropertyCollection


DocumentProperty.ToBool Method

Returns the property value as bool.

[Visual Basic]
Public Function ToBool() As Boolean
[C#]
public bool ToBool();

Remarks

Throws an exception if the property type is not Boolean.

Example

Retrieves the types and values of the custom document properties.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentProperty.ToByteArray Method

Returns the property value as byte array.

[Visual Basic]
Public Function ToByteArray() As Byte()
[C#]
public byte[] ToByteArray();

Remarks

Throws an exception if the property type is not ByteArray.

Example

Shows how to append a thumbnail to an Epub document.

[C#]

// Create a blank document and add some text with a DocumentBuilder
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello world!");

// The thumbnail property resides in a document's built in properties, but is used exclusively by Epub e-book documents
BuiltInDocumentProperties properties = doc.BuiltInDocumentProperties;

// Load an image from our file system into a byte array
byte[] thumbnailBytes = File.ReadAllBytes(ImageDir + "Aspose.Words.gif");

// Set the value of the Thumbnail property to the array from above
properties.Thumbnail = thumbnailBytes;

// Our thumbnail should be visible at the start of the document, before the text we added
doc.Save(ArtifactsDir + "Properties.Thumbnail.epub");

// We can also extract a thumbnail property into a byte array and then into the local file system like this
DocumentProperty thumbnail = doc.BuiltInDocumentProperties["Thumbnail"];
File.WriteAllBytes(ArtifactsDir + "Properties.Thumbnail.gif", thumbnail.ToByteArray());

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentProperty.ToDateTime Method

Returns the property value as DateTime in UTC.

[Visual Basic]
Public Function ToDateTime() As Date
[C#]
public DateTime ToDateTime();

Remarks

Throws an exception if the property type is not DateTime.

Microsoft Word stores only the date part (no time) for custom date properties.

Example

Retrieves a custom document property by name.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

DocumentProperty docProperty = doc.CustomDocumentProperties["Authorized Date"];

if (docProperty != null)
{
    Console.WriteLine(docProperty.ToDateTime());
}
else
{
    Console.WriteLine("The document is not authorized. Authorizing...");
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now);
}
Retrieves the types and values of the custom document properties.
[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentProperty.ToDouble Method

Returns the property value as double.

[Visual Basic]
Public Function ToDouble() As Double
[C#]
public double ToDouble();

Remarks

Throws an exception if the property type is not Number.

Example

Retrieves the types and values of the custom document properties.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentProperty.ToInt Method

Returns the property value as integer.

[Visual Basic]
Public Function ToInt() As Integer
[C#]
public int ToInt();

Remarks

Throws an exception if the property type is not Number.

Example

Retrieves the types and values of the custom document properties.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentProperty.ToString Method

Returns the property value as a string formatted according to the current locale.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();

Remarks

Converts a boolean property into "Y" or "N". Converts a date property into a short date string. For all other types converts a property using Object.ToString().

Example

Retrieves a built-in document property by name.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

DocumentProperty docProperty = doc.BuiltInDocumentProperties["Keywords"];
Console.WriteLine(docProperty.ToString());
Retrieves the types and values of the custom document properties.
[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

See Also

DocumentProperty Class | Aspose.Words.Properties Namespace


DocumentPropertyCollection Class

Base class for BuiltInDocumentProperties and CustomDocumentProperties collections.

For a list of all members of this type, see DocumentPropertyCollection Members.

System.Object
Aspose.Words.Properties.DocumentPropertyCollection
Aspose.Words.Properties.BuiltInDocumentProperties
Aspose.Words.Properties.CustomDocumentProperties

[Visual Basic]
MustInherit Public Class DocumentPropertyCollection
Implements IEnumerable`1([Aspose.Words.Properties.DocumentProperty, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public abstract class DocumentPropertyCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

The names of the properties are case-insensitive.

The properties in the collection are sorted alphabetically by name.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

Requirements

Namespace: Aspose.Words.Properties

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocumentPropertyCollection Members | Aspose.Words.Properties Namespace | BuiltInDocumentProperties | CustomDocumentProperties


DocumentPropertyCollection Members

DocumentPropertyCollection overview

Public Instance Properties

Count | Gets number of items in the collection.
Item | Overloaded. Provides access to the collection items.

Public Instance Methods

Clear | Removes all properties from the collection.
Contains | Returns true if a property with the specified name exists in the collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf | Gets the index of a property by name.
Remove | Removes a property with the specified name from the collection.
RemoveAt | Removes a property at the specified index.

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace | BuiltInDocumentProperties | CustomDocumentProperties


DocumentPropertyCollection Properties

The properties of the DocumentPropertyCollection class are listed below. For a complete list of DocumentPropertyCollection class members, see the DocumentPropertyCollection Members topic.

Public Instance Properties

Count | Gets number of items in the collection.
Item | Overloaded. Provides access to the collection items.

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace | BuiltInDocumentProperties | CustomDocumentProperties


Count Property

Aspose.Words

DocumentPropertyCollection.Count Property

Gets number of items in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

Example

Enumerates through all built-in and custom properties in a document using indexed access.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


Item Property

Aspose.Words

DocumentPropertyCollection.Item Property

Provides access to the collection items.

Overload List

Returns a DocumentProperty object by index.

public DocumentProperty this[int] {get;}

Returns a DocumentProperty object by the name of the property.

public virtual DocumentProperty this[string] {get;}

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


Item Property (Int32)

Aspose.Words

DocumentPropertyCollection.Item Property (Int32)

Returns a DocumentProperty object by index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As DocumentProperty
[C#]
public DocumentProperty this[
int index
] {get;}

Parameters

index
Zero-based index of the DocumentProperty to retrieve.

Example

Enumerates through all built-in and custom properties in a document using indexed access.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

Console.WriteLine("1. Document name: {0}", doc.OriginalFileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty docProperty = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", docProperty.Name, docProperty.Type, docProperty.Value);
}

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace | DocumentPropertyCollection.Item Overload List


Item Property (String)

Aspose.Words

DocumentPropertyCollection.Item Property (String)

Returns a DocumentProperty object by the name of the property.

[Visual Basic]
Overridable Overloads Public Default ReadOnly Property Item( _
ByVal name As String _
) As DocumentProperty
[C#]
public virtual DocumentProperty this[
string name
] {get;}

Parameters

name
The case-insensitive name of the property to retrieve.

Remarks

Returns null if a property with the specified name is not found.

Example

Retrieves a custom document property by name.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

DocumentProperty docProperty = doc.CustomDocumentProperties["Authorized Date"];

if (docProperty != null)
{
    Console.WriteLine(docProperty.ToDateTime());
}
else
{
    Console.WriteLine("The document is not authorized. Authorizing...");
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now);
}

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace | DocumentPropertyCollection.Item Overload List


DocumentPropertyCollection Methods

The methods of the DocumentPropertyCollection class are listed below. For a complete list of DocumentPropertyCollection class members, see the DocumentPropertyCollection Members topic.

Public Instance Methods

Clear | Removes all properties from the collection.
Contains | Returns true if a property with the specified name exists in the collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
IndexOf | Gets the index of a property by name.
Remove | Removes a property with the specified name from the collection.
RemoveAt | Removes a property at the specified index.

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace | BuiltInDocumentProperties | CustomDocumentProperties


DocumentPropertyCollection.Clear Method

Removes all properties from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


DocumentPropertyCollection.Contains Method

Returns true if a property with the specified name exists in the collection.

[Visual Basic]
Public Function Contains( _
ByVal name As String _
) As Boolean
[C#]
public bool Contains(
string name
);

Parameters

name
The case-insensitive name of the property.

Return Value

True if the property exists in the collection; false otherwise.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


DocumentPropertyCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of DocumentProperty) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<DocumentProperty> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


DocumentPropertyCollection.IndexOf Method

Gets the index of a property by name.

[Visual Basic]
Public Function IndexOf( _
ByVal name As String _
) As Integer
[C#]
public int IndexOf(
string name
);

Parameters

name
The case-insensitive name of the property.

Return Value

The zero based index. Negative value if not found.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


DocumentPropertyCollection.Remove Method

Removes a property with the specified name from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal name As String _
)
[C#]
public void Remove(
string name
);

Parameters

name
The case-insensitive name of the property.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


DocumentPropertyCollection.RemoveAt Method

Removes a property at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

Example

Shows how to add custom properties to a document.

[C#]

// Create a blank document and get its custom property collection
Document doc = new Document();
CustomDocumentProperties properties = doc.CustomDocumentProperties;

// The collection will be empty by default
Assert.AreEqual(0, properties.Count);

// We can populate it with key/value pairs with a variety of value types
properties.Add("Authorized", true);
properties.Add("Authorized By", "John Doe");
properties.Add("Authorized Date", DateTime.Today);
properties.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
properties.Add("Authorized Amount", 123.45);

// Custom properties are automatically sorted in alphabetic order
Assert.AreEqual(1, properties.IndexOf("Authorized Amount"));
Assert.AreEqual(5, properties.Count);

// Enumerate and print all custom properties
using (IEnumerator<DocumentProperty> enumerator = properties.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine($"Name: \"{enumerator.Current.Name}\", Type: \"{enumerator.Current.Type}\", Value: \"{enumerator.Current.Value}\"");
    }
}

// We can view/edit custom properties by opening the document and looking in File > Properties > Advanced Properties > Custom
doc.Save(ArtifactsDir + "Properties.DocumentPropertyCollection.docx");

// We can remove elements from the property collection by index or by name
properties.RemoveAt(1);
Assert.False(properties.Contains("Authorized Amount"));
Assert.AreEqual(4, properties.Count);

properties.Remove("Authorized Revision");
Assert.False(properties.Contains("Authorized Revision"));
Assert.AreEqual(3, properties.Count);

// We can also empty the entire custom property collection at once
properties.Clear();
Assert.AreEqual(0, properties.Count);

See Also

DocumentPropertyCollection Class | Aspose.Words.Properties Namespace


DocumentSecurity Enumeration

Used as a value for the Security property. Specifies the security level of a document as a numeric value.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum DocumentSecurity
[C#]
public enum DocumentSecurity

Example

Shows how to use document properties to display the security level of a document.

[C#]

// Create a blank document, which has no security of any kind by default
Document doc = new Document();

// The "Security" property serves as a description of the security level of a document
Assert.AreEqual(DocumentSecurity.None, doc.BuiltInDocumentProperties.Security);

// Upon saving a document after setting its security level, Aspose automatically updates this property to the appropriate value
doc.WriteProtection.ReadOnlyRecommended = true;
doc.Save(ArtifactsDir + "Properties.Security.ReadOnlyRecommended.docx");

// We can open a document and glance at its security level like this
Assert.AreEqual(DocumentSecurity.ReadOnlyRecommended,
    new Document(ArtifactsDir + "Properties.Security.ReadOnlyRecommended.docx").BuiltInDocumentProperties.Security);

// Create a new document and set it to Write-Protected
doc = new Document();

Assert.False(doc.WriteProtection.IsWriteProtected);
doc.WriteProtection.SetPassword("MyPassword");
Assert.True(doc.WriteProtection.ValidatePassword("MyPassword"));
Assert.True(doc.WriteProtection.IsWriteProtected);
doc.Save(ArtifactsDir + "Properties.Security.ReadOnlyEnforced.docx");

// This document's security level counts as "ReadOnlyEnforced"
Assert.AreEqual(DocumentSecurity.ReadOnlyEnforced,
    new Document(ArtifactsDir + "Properties.Security.ReadOnlyEnforced.docx").BuiltInDocumentProperties.Security);

// Since this is still a descriptive property, we can protect a document and pick a suitable value ourselves
doc = new Document();

doc.Protect(ProtectionType.AllowOnlyComments, "MyPassword");
doc.BuiltInDocumentProperties.Security = DocumentSecurity.ReadOnlyExceptAnnotations;
doc.Save(ArtifactsDir + "Properties.Security.ReadOnlyExceptAnnotations.docx");

Assert.AreEqual(DocumentSecurity.ReadOnlyExceptAnnotations,
    new Document(ArtifactsDir + "Properties.Security.ReadOnlyExceptAnnotations.docx").BuiltInDocumentProperties.Security);

Members

Member Name | Description | Value
None | There are no security states specified by the property. | 0
PasswordProtected | The document is password protected. (Note has never been seen in a document so far). | 1
ReadOnlyRecommended | The document to be opened read-only if possible, but the setting can be overridden. | 2
ReadOnlyEnforced | The document to always be opened read-only. | 4
ReadOnlyExceptAnnotations | The document to always be opened read-only except for annotations. | 8

Requirements

Namespace: Aspose.Words.Properties

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Properties Namespace


PropertyType Enumeration

Specifies data type of a document property.

[Visual Basic]
Public Enum PropertyType
[C#]
public enum PropertyType

Remarks

Example

Retrieves the types and values of the custom document properties.

[C#]

Document doc = new Document(MyDir + "Properties.doc");

foreach (DocumentProperty docProperty in doc.CustomDocumentProperties)
{
    Console.WriteLine(docProperty.Name);
    switch (docProperty.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a String value.");
            Console.WriteLine(docProperty.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(docProperty.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(docProperty.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(docProperty.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(docProperty.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}

Members

Member Name | Description | Value
Boolean | The property is a boolean value. | 0
DateTime | The property is a date time value. | 1
Double | The property is a floating number. | 2
Number | The property is an integer number. | 3
String | The property is a string value. | 4
StringArray | The property is an array of strings. | 5
ObjectArray | The property is an array of objects. | 6
ByteArray | The property is an array of bytes. | 7
Other | The property is some other type. | 8

Requirements

Namespace: Aspose.Words.Properties

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Properties Namespace | DocumentProperty | Type


Aspose.Words.Rendering

Aspose.Words

Aspose.Words.Rendering Namespace

The Aspose.Words.Rendering namespace provides classes that allow to customize printing or rendering of documents.

To actually render, print or convert a document use the corresponding methods on the Document object.

Namespace hierarchy

Classes

Class | Description
AsposeWordsPrintDocument | Provides a default implementation for printing of a Document within the .NET printing framework.
NodeRendererBase | Base class for ShapeRenderer and OfficeMathRenderer.
OfficeMathRenderer | Provides methods to render an individual OfficeMath to a raster or vector image or to a Graphics object.
PageInfo | Represents information about a particular document page.
PrinterSettingsContainer | Represent a storage for some parameters of PrinterSettings object. Access to data of PrinterSettings takes long time. PrinterSettingsContainer caches parameters from PrinterSettings, so printing works faster.
ShapeRenderer | Provides methods to render an individual Shape or GroupShape to a raster or vector image or to a Graphics object.
ThumbnailGeneratingOptions | Can be used to specify additional options when generating thumbnail for a document. User can call method UpdateThumbnail to generate Thumbnail for a document.


AsposeWordsPrintDocument Class

Provides a default implementation for printing of a Document within the .NET printing framework.

For a list of all members of this type, see AsposeWordsPrintDocument Members.

System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Drawing.Printing.PrintDocument
Aspose.Words.Rendering.AsposeWordsPrintDocument

[Visual Basic]
Public Class AsposeWordsPrintDocument
Inherits PrintDocument
[C#]
public class AsposeWordsPrintDocument : PrintDocument

Remarks

AsposeWordsPrintDocument overrides OnBeginPrint to print the range of pages that is specified in PrinterSettings.

A single Word document can consist of multiple sections that specify pages with different sizes, orientation and paper trays. AsposeWordsPrintDocument overrides OnQueryPageSettings to properly select paper size, orientation and paper source when printing a Word document.

Microsoft Word stores printer specific values for paper trays in a Word document and therefore, only printing on the same printer model as the one that was selected when the user specified the paper trays will result in printing from the correct trays. If you print a document on a different printer, then most likely the default paper tray will be used, not the trays specified in the document.

Example

Shows the Print dialog that allows selecting the printer and page range to print with. Then brings up the print preview from which you can preview the document and choose to print or close.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PrintPreviewDialog previewDlg = new PrintPreviewDialog();
// Show non-modal first is a hack for the print preview form to show on top.
previewDlg.Show();

// Initialize the Print Dialog with the number of pages in the document.
PrintDialog printDlg = new PrintDialog();
printDlg.AllowSomePages = true;
printDlg.PrinterSettings.MinimumPage = 1;
printDlg.PrinterSettings.MaximumPage = doc.PageCount;
printDlg.PrinterSettings.FromPage = 1;
printDlg.PrinterSettings.ToPage = doc.PageCount;

if (!printDlg.ShowDialog().Equals(DialogResult.OK))
    return;

// Create the Aspose.Words' implementation of the .NET print document
// and pass the printer settings from the dialog to the print document.
// Use 'CachePrinterSettings' to reduce time of first call of Print() method.
AsposeWordsPrintDocument awPrintDoc = new AsposeWordsPrintDocument(doc);
awPrintDoc.PrinterSettings = printDlg.PrinterSettings;
awPrintDoc.CachePrinterSettings();

// Hide and invalidate preview is a hack for print preview to show on top.
previewDlg.Hide();
previewDlg.PrintPreviewControl.InvalidatePreview();

// Pass the Aspose.Words' print document to the .NET Print Preview dialog.
previewDlg.Document = awPrintDoc;

previewDlg.ShowDialog();

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

AsposeWordsPrintDocument Members | Aspose.Words.Rendering Namespace


AsposeWordsPrintDocument Members

AsposeWordsPrintDocument overview

Public Instance Constructors

AsposeWordsPrintDocument Constructor Initializes a new instance of this class.

Public Instance Methods

CachePrinterSettings Reads and caches some fields of PrinterSettings to reduce printing time.

See Also

AsposeWordsPrintDocument Class | Aspose.Words.Rendering Namespace


AsposeWordsPrintDocument Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal document As Document _
)
[C#]
public AsposeWordsPrintDocument(
Document document
);

Parameters

document
The document to print.

See Also

AsposeWordsPrintDocument Class | Aspose.Words.Rendering Namespace


AsposeWordsPrintDocument Methods

The methods of the AsposeWordsPrintDocument class are listed below. For a complete list of AsposeWordsPrintDocument class members, see the AsposeWordsPrintDocument Members topic.

Public Instance Methods

CachePrinterSettings Reads and caches some fields of PrinterSettings to reduce printing time.

See Also

AsposeWordsPrintDocument Class | Aspose.Words.Rendering Namespace


AsposeWordsPrintDocument.CachePrinterSettings Method

Reads and caches some fields of PrinterSettings to reduce printing time.

[Visual Basic]
Public Sub CachePrinterSettings()
[C#]
public void CachePrinterSettings();

Remarks

This method is called before the printing starts if it wasn't executed previously.

See Also

AsposeWordsPrintDocument Class | Aspose.Words.Rendering Namespace


NodeRendererBase Class

Base class for ShapeRenderer and OfficeMathRenderer.

For a list of all members of this type, see NodeRendererBase Members.

System.Object
Aspose.Words.Rendering.NodeRendererBase
Aspose.Words.Rendering.OfficeMathRenderer
Aspose.Words.Rendering.ShapeRenderer

[Visual Basic]
MustInherit Public Class NodeRendererBase
[C#]
public abstract class NodeRendererBase

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

NodeRendererBase Members | Aspose.Words.Rendering Namespace


NodeRendererBase Members

NodeRendererBase overview

Public Instance Properties

BoundsInPoints | Gets the actual bounds of the shape in points.
OpaqueBoundsInPoints | Gets the opaque bounds of the shape in points.
SizeInPoints | Gets the actual size of the shape in points.

Public Instance Methods

GetBoundsInPixels | Overloaded. Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.
GetOpaqueBoundsInPixels | Overloaded. Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.
GetSizeInPixels | Overloaded. Calculates the size of the shape in pixels for a specified zoom factor and resolution.
RenderToScale | Renders the shape into a Graphics object to a specified scale.
RenderToSize | Renders the shape into a Graphics object to a specified size.
Save | Overloaded. Renders the shape and saves into an image.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase Properties

The properties of the NodeRendererBase class are listed below. For a complete list of NodeRendererBase class members, see the NodeRendererBase Members topic.

Public Instance Properties

BoundsInPoints | Gets the actual bounds of the shape in points.
OpaqueBoundsInPoints | Gets the opaque bounds of the shape in points.
SizeInPoints | Gets the actual size of the shape in points.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


BoundsInPoints Property

Aspose.Words

NodeRendererBase.BoundsInPoints Property

Gets the actual bounds of the shape in points.

[Visual Basic]
Public ReadOnly Property BoundsInPoints As RectangleF
[C#]
public RectangleF BoundsInPoints {get;}

Remarks

This property returns the actual (as rendered on the page) bounding box of the shape. The bounds takes into account shape rotation (if any).

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


OpaqueBoundsInPoints Property

Aspose.Words

NodeRendererBase.OpaqueBoundsInPoints Property

Gets the opaque bounds of the shape in points.

[Visual Basic]
Public ReadOnly Property OpaqueBoundsInPoints As RectangleF
[C#]
public RectangleF OpaqueBoundsInPoints {get;}

Remarks

This property returns the opaque (i.e. transparent parts of the shape are ignored) bounding box of the shape. The bounds takes the shape rotation into account.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


SizeInPoints Property

Aspose.Words

NodeRendererBase.SizeInPoints Property

Gets the actual size of the shape in points.

[Visual Basic]
Public ReadOnly Property SizeInPoints As SizeF
[C#]
public SizeF SizeInPoints {get;}

Remarks

This property returns the size of the actual (as rendered on the page) bounding box of the shape. The size takes into account shape rotation (if any).

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase Methods

The methods of the NodeRendererBase class are listed below. For a complete list of NodeRendererBase class members, see the NodeRendererBase Members topic.

Public Instance Methods

GetBoundsInPixels | Overloaded. Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.
GetOpaqueBoundsInPixels | Overloaded. Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.
GetSizeInPixels | Overloaded. Calculates the size of the shape in pixels for a specified zoom factor and resolution.
RenderToScale | Renders the shape into a Graphics object to a specified scale.
RenderToSize | Renders the shape into a Graphics object to a specified size.
Save | Overloaded. Renders the shape and saves into an image.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


GetBoundsInPixels Method

Aspose.Words

NodeRendererBase.GetBoundsInPixels Method

Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.

Overload List

Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.

public Rectangle GetBoundsInPixels(float,float);

Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.

public Rectangle GetBoundsInPixels(float,float,float);

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase.GetBoundsInPixels Method (Single, Single)

Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetBoundsInPixels( _
ByVal scale As Single, _
ByVal dpi As Single _
) As Rectangle
[C#]
public Rectangle GetBoundsInPixels(
float scale,
float dpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
dpi
The resolution (horizontal and vertical) to convert from points to pixels (dots per inch).

Return Value

The actual (as rendered on the page) bounding box of the shape in pixels.

Remarks

This method converts BoundsInPoints into rectangle in pixels.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.GetBoundsInPixels Overload List


NodeRendererBase.GetBoundsInPixels Method (Single, Single, Single)

Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetBoundsInPixels( _
ByVal scale As Single, _
ByVal horizontalDpi As Single, _
ByVal verticalDpi As Single _
) As Rectangle
[C#]
public Rectangle GetBoundsInPixels(
float scale,
float horizontalDpi,
float verticalDpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
horizontalDpi
The horizontal resolution to convert from points to pixels (dots per inch).
verticalDpi
The vertical resolution to convert from points to pixels (dots per inch).

Return Value

The actual (as rendered on the page) bounding box of the shape in pixels.

Remarks

This method converts BoundsInPoints into rectangle in pixels.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.GetBoundsInPixels Overload List


GetOpaqueBoundsInPixels Method

Aspose.Words

NodeRendererBase.GetOpaqueBoundsInPixels Method

Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.

Overload List

Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.

public Rectangle GetOpaqueBoundsInPixels(float,float);

Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.

public Rectangle GetOpaqueBoundsInPixels(float,float,float);

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase.GetOpaqueBoundsInPixels Method (Single, Single)

Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetOpaqueBoundsInPixels( _
ByVal scale As Single, _
ByVal dpi As Single _
) As Rectangle
[C#]
public Rectangle GetOpaqueBoundsInPixels(
float scale,
float dpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
dpi
The resolution to convert from points to pixels (dots per inch).

Return Value

The opaque rectangle of the shape in pixels.

Remarks

This method converts OpaqueBoundsInPoints into rectangle in pixels and it is useful when you want to create a bitmap for rendering the shape with only opaque part of the shape.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.GetOpaqueBoundsInPixels Overload List


NodeRendererBase.GetOpaqueBoundsInPixels Method (Single, Single, Single)

Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetOpaqueBoundsInPixels( _
ByVal scale As Single, _
ByVal horizontalDpi As Single, _
ByVal verticalDpi As Single _
) As Rectangle
[C#]
public Rectangle GetOpaqueBoundsInPixels(
float scale,
float horizontalDpi,
float verticalDpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
horizontalDpi
The horizontal resolution to convert from points to pixels (dots per inch).
verticalDpi
The vertical resolution to convert from points to pixels (dots per inch).

Return Value

The opaque rectangle of the shape in pixels.

Remarks

This method converts OpaqueBoundsInPoints into rectangle in pixels and it is useful when you want to create a bitmap for rendering the shape with only opaque part of the shape.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.GetOpaqueBoundsInPixels Overload List


GetSizeInPixels Method

Aspose.Words

NodeRendererBase.GetSizeInPixels Method

Calculates the size of the shape in pixels for a specified zoom factor and resolution.

Overload List

Calculates the size of the shape in pixels for a specified zoom factor and resolution.

public Size GetSizeInPixels(float,float);

Calculates the size of the shape in pixels for a specified zoom factor and resolution.

public Size GetSizeInPixels(float,float,float);

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase.GetSizeInPixels Method (Single, Single)

Calculates the size of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetSizeInPixels( _
ByVal scale As Single, _
ByVal dpi As Single _
) As Size
[C#]
public Size GetSizeInPixels(
float scale,
float dpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
dpi
The resolution (horizontal and vertical) to convert from points to pixels (dots per inch).

Return Value

The size of the shape in pixels.

Remarks

This method converts SizeInPoints into size in pixels and it is useful when you want to create a bitmap for rendering the shape neatly onto the bitmap.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.GetSizeInPixels Overload List


NodeRendererBase.GetSizeInPixels Method (Single, Single, Single)

Calculates the size of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetSizeInPixels( _
ByVal scale As Single, _
ByVal horizontalDpi As Single, _
ByVal verticalDpi As Single _
) As Size
[C#]
public Size GetSizeInPixels(
float scale,
float horizontalDpi,
float verticalDpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
horizontalDpi
The horizontal resolution to convert from points to pixels (dots per inch).
verticalDpi
The vertical resolution to convert from points to pixels (dots per inch).

Return Value

The size of the shape in pixels.

Remarks

This method converts SizeInPoints into size in pixels and it is useful when you want to create a bitmap for rendering the shape neatly onto the bitmap.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.GetSizeInPixels Overload List


NodeRendererBase.RenderToScale Method

Renders the shape into a Graphics object to a specified scale.

[Visual Basic]
Public Function RenderToScale( _
ByVal graphics As Graphics, _
ByVal x As Single, _
ByVal y As Single, _
ByVal scale As Single _
) As SizeF
[C#]
public SizeF RenderToScale(
Graphics graphics,
float x,
float y,
float scale
);

Parameters

graphics
The object where to render to.
x
The X coordinate (in world units) of the top left corner of the rendered shape.
y
The Y coordinate (in world units) of the top left corner of the rendered shape.
scale
The scale for rendering the shape (1.0 is 100%).

Return Value

The width and height (in world units) of the rendered shape.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase.RenderToSize Method

Renders the shape into a Graphics object to a specified size.

[Visual Basic]
Public Function RenderToSize( _
ByVal graphics As Graphics, _
ByVal x As Single, _
ByVal y As Single, _
ByVal width As Single, _
ByVal height As Single _
) As Single
[C#]
public float RenderToSize(
Graphics graphics,
float x,
float y,
float width,
float height
);

Parameters

graphics
The object where to render to.
x
The X coordinate (in world units) of the top left corner of the rendered shape.
y
The Y coordinate (in world units) of the top left corner of the rendered shape.
width
The maximum width (in world units) that can be occupied by the rendered shape.
height
The maximum height (in world units) that can be occupied by the rendered shape.

Return Value

The scale that was automatically calculated for the rendered shape to fit the specified size.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


Save Method

Aspose.Words

NodeRendererBase.Save Method

Renders the shape and saves into an image.

Overload List

Renders the shape into an image and saves into a stream.

public void Save(Stream,ImageSaveOptions);

Renders the shape into an image and saves into a file.

public void Save(string,ImageSaveOptions);

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace


NodeRendererBase.Save Method (Stream, ImageSaveOptions)

Renders the shape into an image and saves into a stream.

[Visual Basic]
Overloads Public Sub Save( _
ByVal stream As Stream, _
ByVal saveOptions As ImageSaveOptions _
)
[C#]
public void Save(
Stream stream,
ImageSaveOptions saveOptions
);

Parameters

stream
The stream where to save the image of the shape.
saveOptions
Specifies the options that control how the shape is rendered and saved. Can be null. If this is null, the image will be saved in the PNG format.

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.Save Overload List


NodeRendererBase.Save Method (String, ImageSaveOptions)

Renders the shape into an image and saves into a file.

[Visual Basic]
Overloads Public Sub Save( _
ByVal fileName As String, _
ByVal saveOptions As ImageSaveOptions _
)
[C#]
public void Save(
string fileName,
ImageSaveOptions saveOptions
);

Parameters

fileName
The name for the image file. If a file with the specified name already exists, the existing file is overwritten.
saveOptions
Specifies the options that control how the shape is rendered and saved. Can be null.

Example

Shows how to convert specific object into image

[C#]

Document doc = new Document(MyDir + "Shape.OfficeMath.docx");

//Get OfficeMath node from the document and render this as image (you can also do the same with the Shape node)
OfficeMath math = (OfficeMath)doc.GetChild(NodeType.OfficeMath, 0, true);
math.GetMathRenderer().Save(ArtifactsDir + "Shape.OfficeMath.svg", new ImageSaveOptions(SaveFormat.Svg));

See Also

NodeRendererBase Class | Aspose.Words.Rendering Namespace | NodeRendererBase.Save Overload List


OfficeMathRenderer Class

Provides methods to render an individual OfficeMath to a raster or vector image or to a Graphics object.

For a list of all members of this type, see OfficeMathRenderer Members.

System.Object
Aspose.Words.Rendering.NodeRendererBase
Aspose.Words.Rendering.OfficeMathRenderer

[Visual Basic]
Public Class OfficeMathRenderer
Inherits NodeRendererBase
[C#]
public class OfficeMathRenderer : NodeRendererBase

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OfficeMathRenderer Members | Aspose.Words.Rendering Namespace


OfficeMathRenderer Members

OfficeMathRenderer overview

Public Instance Constructors

OfficeMathRenderer Constructor Initializes a new instance of this class.

Public Instance Properties

BoundsInPoints (inherited from NodeRendererBase) | Gets the actual bounds of the shape in points.
OpaqueBoundsInPoints (inherited from NodeRendererBase) | Gets the opaque bounds of the shape in points.
SizeInPoints (inherited from NodeRendererBase) | Gets the actual size of the shape in points.

Public Instance Methods

GetBoundsInPixels (inherited from NodeRendererBase) | Overloaded. Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.
GetOpaqueBoundsInPixels (inherited from NodeRendererBase) | Overloaded. Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.
GetSizeInPixels (inherited from NodeRendererBase) | Overloaded. Calculates the size of the shape in pixels for a specified zoom factor and resolution.
RenderToScale (inherited from NodeRendererBase) | Renders the shape into a Graphics object to a specified scale.
RenderToSize (inherited from NodeRendererBase) | Renders the shape into a Graphics object to a specified size.
Save (inherited from NodeRendererBase) | Overloaded. Renders the shape and saves into an image.

See Also

OfficeMathRenderer Class | Aspose.Words.Rendering Namespace


OfficeMathRenderer Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal math As OfficeMath _
)
[C#]
public OfficeMathRenderer(
OfficeMath math
);

Parameters

math
The OfficeMath object that you want to render.

See Also

OfficeMathRenderer Class | Aspose.Words.Rendering Namespace


PageInfo Class

Represents information about a particular document page.

For a list of all members of this type, see PageInfo Members.

System.Object
Aspose.Words.Rendering.PageInfo

[Visual Basic]
Public Class PageInfo
[C#]
public class PageInfo

Remarks

The page width and height returned by this object represent the "final" size of the page e.g. they are already rotated to the correct orientation.

Example

Retrieves page size and orientation information for every page in a Word document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

Console.WriteLine("Document \"{0}\" contains {1} pages.", doc.OriginalFileName, doc.PageCount);

for (int i = 0; i < doc.PageCount; i++)
{
    PageInfo pageInfo = doc.GetPageInfo(i);
    Console.WriteLine("Page {0}. PaperSize:{1} ({2:F0}x{3:F0}pt), Orientation:{4}, PaperTray:{5}", i + 1,
        pageInfo.PaperSize, pageInfo.WidthInPoints, pageInfo.HeightInPoints,
        pageInfo.Landscape ? "Landscape" : "Portrait", pageInfo.PaperTray);
}
Renders a page of a Word document into a bitmap using a specified zoom factor.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            PageInfo pageInfo = doc.GetPageInfo(0);

            // Let's say we want the image at 50% zoom.
            const float myScale = 0.50f;

            // Let's say we want the image at this resolution.
            const float myResolution = 200.0f;

            Size pageSize = pageInfo.GetSizeInPixels(myScale, myResolution);
#if NETSTANDARD2_0 || __MOBILE__
            using (SKBitmap bitmap = new SKBitmap(pageSize.Width, pageSize.Height))
            {
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    // Scale to compensate for the larger bitmap
                    canvas.Scale(2);

                    // Fill the page background.
                    // If you need to set color without specific options, you can use "canvas.Clear(SKColors.White);"
                    SKPaint paint = new SKPaint
                    {
                        Color = SKColors.White,
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High
                    };

                    canvas.DrawPaint(paint);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, canvas, 0, 0, myScale);
                }

                using (SKFileWStream fs = new SKFileWStream(ArtifactsDir + "Rendering.RenderToScale.png"))
                {
                    bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100);
                }
            }
#else
            using (Bitmap img = new Bitmap(pageSize.Width, pageSize.Height))
            {
                img.SetResolution(myResolution, myResolution);

                using (Graphics gr = Graphics.FromImage(img))
                {
                    // You can apply various settings to the Graphics object.
                    gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    // Fill the page background.
                    gr.FillRectangle(Brushes.White, 0, 0, pageSize.Width, pageSize.Height);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, gr, 0, 0, myScale);
                }

                img.Save(ArtifactsDir + "Rendering.RenderToScale.png");
            }
#endif

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PageInfo Members | Aspose.Words.Rendering Namespace | GetPageInfo


PageInfo Members

PageInfo overview

Public Instance Properties

HeightInPoints | Gets the height of the page in points.
Landscape | Returns true if the page orientation specified in the document for this page is landscape.
PaperSize | Gets the paper size as enumeration.
PaperTray | Gets the paper tray (bin) for this page as specified in the document. The value is implementation (printer) specific.
SizeInPoints | Gets the page size in points.
WidthInPoints | Gets the width of the page in points.

Public Instance Methods

GetDotNetPaperSize | Gets the PaperSize object suitable for printing the page represented by this PageInfo.
GetSizeInPixels | Overloaded. Calculates the page size in pixels for a specified zoom factor and resolution.
GetSpecifiedPrinterPaperSource | Gets the PaperSource object suitable for printing the page represented by this PageInfo.

See Also

PageInfo Class | Aspose.Words.Rendering Namespace | GetPageInfo


PageInfo Properties

The properties of the PageInfo class are listed below. For a complete list of PageInfo class members, see the PageInfo Members topic.

Public Instance Properties

HeightInPoints | Gets the height of the page in points.
Landscape | Returns true if the page orientation specified in the document for this page is landscape.
PaperSize | Gets the paper size as enumeration.
PaperTray | Gets the paper tray (bin) for this page as specified in the document. The value is implementation (printer) specific.
SizeInPoints | Gets the page size in points.
WidthInPoints | Gets the width of the page in points.

See Also

PageInfo Class | Aspose.Words.Rendering Namespace | GetPageInfo


HeightInPoints Property

Aspose.Words

PageInfo.HeightInPoints Property

Gets the height of the page in points.

[Visual Basic]
Public ReadOnly Property HeightInPoints As Single
[C#]
public float HeightInPoints {get;}

Example

Retrieves page size and orientation information for every page in a Word document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

Console.WriteLine("Document \"{0}\" contains {1} pages.", doc.OriginalFileName, doc.PageCount);

for (int i = 0; i < doc.PageCount; i++)
{
    PageInfo pageInfo = doc.GetPageInfo(i);
    Console.WriteLine("Page {0}. PaperSize:{1} ({2:F0}x{3:F0}pt), Orientation:{4}, PaperTray:{5}", i + 1,
        pageInfo.PaperSize, pageInfo.WidthInPoints, pageInfo.HeightInPoints,
        pageInfo.Landscape ? "Landscape" : "Portrait", pageInfo.PaperTray);
}

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


Landscape Property

Aspose.Words

PageInfo.Landscape Property

Returns true if the page orientation specified in the document for this page is landscape.

[Visual Basic]
Public ReadOnly Property Landscape As Boolean
[C#]
public bool Landscape {get;}

Example

Retrieves page size and orientation information for every page in a Word document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

Console.WriteLine("Document \"{0}\" contains {1} pages.", doc.OriginalFileName, doc.PageCount);

for (int i = 0; i < doc.PageCount; i++)
{
    PageInfo pageInfo = doc.GetPageInfo(i);
    Console.WriteLine("Page {0}. PaperSize:{1} ({2:F0}x{3:F0}pt), Orientation:{4}, PaperTray:{5}", i + 1,
        pageInfo.PaperSize, pageInfo.WidthInPoints, pageInfo.HeightInPoints,
        pageInfo.Landscape ? "Landscape" : "Portrait", pageInfo.PaperTray);
}
Shows how to implement your own .NET PrintDocument to completely customize printing of Aspose.Words documents.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            // Create an instance of our own PrintDocument.
            MyPrintDocument printDoc = new MyPrintDocument(doc);
            // Specify the page range to print.
            printDoc.PrinterSettings.PrintRange = System.Drawing.Printing.PrintRange.SomePages;
            printDoc.PrinterSettings.FromPage = 1;
            printDoc.PrinterSettings.ToPage = 1;

            // Print our document.
            printDoc.Print();
        }

        /// <summary>
        /// The way to print in the .NET Framework is to implement a class derived from PrintDocument.
        /// This class is an example on how to implement custom printing of an Aspose.Words document.
        /// It selects an appropriate paper size, orientation and paper tray when printing.
        /// </summary>
        public class MyPrintDocument : PrintDocument
        {
            public MyPrintDocument(Document document)
            {
                mDocument = document;
            }

            /// <summary>
            /// Called before the printing starts.
            /// </summary>
            protected override void OnBeginPrint(PrintEventArgs e)
            {
                base.OnBeginPrint(e);

                // Initialize the range of pages to be printed according to the user selection.
                switch (PrinterSettings.PrintRange)
                {
                    case System.Drawing.Printing.PrintRange.AllPages:
                        mCurrentPage = 1;
                        mPageTo = mDocument.PageCount;
                        break;
                    case System.Drawing.Printing.PrintRange.SomePages:
                        mCurrentPage = PrinterSettings.FromPage;
                        mPageTo = PrinterSettings.ToPage;
                        break;
                    default:
                        throw new InvalidOperationException("Unsupported print range.");
                }
            }

            /// <summary>
            /// Called before each page is printed.
            /// </summary>
            protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
            {
                base.OnQueryPageSettings(e);

                // A single Word document can have multiple sections that specify pages with different sizes,
                // orientation and paper trays. This code is called by the .NET printing framework before
                // each page is printed and we get a chance to specify how the page is to be printed.
                PageInfo pageInfo = mDocument.GetPageInfo(mCurrentPage - 1);
                e.PageSettings.PaperSize = pageInfo.GetDotNetPaperSize(PrinterSettings.PaperSizes);
                // MS Word stores the paper source (printer tray) for each section as a printer-specfic value.
                // To obtain the correct tray value you will need to use the RawKindValue returned
                // by .NET for your printer.
                e.PageSettings.PaperSource.RawKind = pageInfo.PaperTray;
                e.PageSettings.Landscape = pageInfo.Landscape;
            }

            /// <summary>
            /// Called for each page to render it for printing.
            /// </summary>
            protected override void OnPrintPage(PrintPageEventArgs e)
            {
                base.OnPrintPage(e);

                // Aspose.Words rendering engine creates a page that is drawn from the 0,0 of the paper,
                // but there is some hard margin in the printer and the .NET printing framework
                // renders from there. We need to offset by that hard margin.

                // In .NET 1.1 the hard margin is not available programmatically, lets hardcode to about 4mm.
                float hardOffsetX = 20;
                float hardOffsetY = 20;

                // This is in .NET 2.0 only. Uncomment when needed.
                // float hardOffsetX = e.PageSettings.HardMarginX;
                // float hardOffsetY = e.PageSettings.HardMarginY;

                int pageIndex = mCurrentPage - 1;
                mDocument.RenderToScale(mCurrentPage, e.Graphics, -hardOffsetX, -hardOffsetY, 1.0f);

                mCurrentPage++;
                e.HasMorePages = (mCurrentPage <= mPageTo);
            }

            private readonly Document mDocument;
            private int mCurrentPage;
            private int mPageTo;
        }
#endif

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


PaperSize Property

Aspose.Words

PageInfo.PaperSize Property

Gets the paper size as enumeration.

[Visual Basic]
Public ReadOnly Property PaperSize As PaperSize
[C#]
public PaperSize PaperSize {get;}

Example

Retrieves page size and orientation information for every page in a Word document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

Console.WriteLine("Document \"{0}\" contains {1} pages.", doc.OriginalFileName, doc.PageCount);

for (int i = 0; i < doc.PageCount; i++)
{
    PageInfo pageInfo = doc.GetPageInfo(i);
    Console.WriteLine("Page {0}. PaperSize:{1} ({2:F0}x{3:F0}pt), Orientation:{4}, PaperTray:{5}", i + 1,
        pageInfo.PaperSize, pageInfo.WidthInPoints, pageInfo.HeightInPoints,
        pageInfo.Landscape ? "Landscape" : "Portrait", pageInfo.PaperTray);
}

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


PaperTray Property

Aspose.Words

PageInfo.PaperTray Property

Gets the paper tray (bin) for this page as specified in the document. The value is implementation (printer) specific.

[Visual Basic]
Public ReadOnly Property PaperTray As Integer
[C#]
public int PaperTray {get;}

Example

Retrieves page size and orientation information for every page in a Word document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

Console.WriteLine("Document \"{0}\" contains {1} pages.", doc.OriginalFileName, doc.PageCount);

for (int i = 0; i < doc.PageCount; i++)
{
    PageInfo pageInfo = doc.GetPageInfo(i);
    Console.WriteLine("Page {0}. PaperSize:{1} ({2:F0}x{3:F0}pt), Orientation:{4}, PaperTray:{5}", i + 1,
        pageInfo.PaperSize, pageInfo.WidthInPoints, pageInfo.HeightInPoints,
        pageInfo.Landscape ? "Landscape" : "Portrait", pageInfo.PaperTray);
}

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


SizeInPoints Property

Aspose.Words

PageInfo.SizeInPoints Property

Gets the page size in points.

[Visual Basic]
Public ReadOnly Property SizeInPoints As SizeF
[C#]
public SizeF SizeInPoints {get;}

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


WidthInPoints Property

Aspose.Words

PageInfo.WidthInPoints Property

Gets the width of the page in points.

[Visual Basic]
Public ReadOnly Property WidthInPoints As Single
[C#]
public float WidthInPoints {get;}

Example

Retrieves page size and orientation information for every page in a Word document.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

Console.WriteLine("Document \"{0}\" contains {1} pages.", doc.OriginalFileName, doc.PageCount);

for (int i = 0; i < doc.PageCount; i++)
{
    PageInfo pageInfo = doc.GetPageInfo(i);
    Console.WriteLine("Page {0}. PaperSize:{1} ({2:F0}x{3:F0}pt), Orientation:{4}, PaperTray:{5}", i + 1,
        pageInfo.PaperSize, pageInfo.WidthInPoints, pageInfo.HeightInPoints,
        pageInfo.Landscape ? "Landscape" : "Portrait", pageInfo.PaperTray);
}

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


PageInfo Methods

The methods of the PageInfo class are listed below. For a complete list of PageInfo class members, see the PageInfo Members topic.

Public Instance Methods

GetDotNetPaperSize | Gets the PaperSize object suitable for printing the page represented by this PageInfo.
GetSizeInPixels | Overloaded. Calculates the page size in pixels for a specified zoom factor and resolution.
GetSpecifiedPrinterPaperSource | Gets the PaperSource object suitable for printing the page represented by this PageInfo.

See Also

PageInfo Class | Aspose.Words.Rendering Namespace | GetPageInfo


PageInfo.GetDotNetPaperSize Method

Gets the PaperSize object suitable for printing the page represented by this PageInfo.

[Visual Basic]
Public Function GetDotNetPaperSize( _
ByVal paperSizes As PaperSizeCollection _
) As PaperSize
[C#]
public PaperSize GetDotNetPaperSize(
PaperSizeCollection paperSizes
);

Parameters

paperSizes
Available paper sizes.

Return Value

An object that you can use in the .NET printing framework to specify the paper size.

Example

Shows how to implement your own .NET PrintDocument to completely customize printing of Aspose.Words documents.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            // Create an instance of our own PrintDocument.
            MyPrintDocument printDoc = new MyPrintDocument(doc);
            // Specify the page range to print.
            printDoc.PrinterSettings.PrintRange = System.Drawing.Printing.PrintRange.SomePages;
            printDoc.PrinterSettings.FromPage = 1;
            printDoc.PrinterSettings.ToPage = 1;

            // Print our document.
            printDoc.Print();
        }

        /// <summary>
        /// The way to print in the .NET Framework is to implement a class derived from PrintDocument.
        /// This class is an example on how to implement custom printing of an Aspose.Words document.
        /// It selects an appropriate paper size, orientation and paper tray when printing.
        /// </summary>
        public class MyPrintDocument : PrintDocument
        {
            public MyPrintDocument(Document document)
            {
                mDocument = document;
            }

            /// <summary>
            /// Called before the printing starts.
            /// </summary>
            protected override void OnBeginPrint(PrintEventArgs e)
            {
                base.OnBeginPrint(e);

                // Initialize the range of pages to be printed according to the user selection.
                switch (PrinterSettings.PrintRange)
                {
                    case System.Drawing.Printing.PrintRange.AllPages:
                        mCurrentPage = 1;
                        mPageTo = mDocument.PageCount;
                        break;
                    case System.Drawing.Printing.PrintRange.SomePages:
                        mCurrentPage = PrinterSettings.FromPage;
                        mPageTo = PrinterSettings.ToPage;
                        break;
                    default:
                        throw new InvalidOperationException("Unsupported print range.");
                }
            }

            /// <summary>
            /// Called before each page is printed.
            /// </summary>
            protected override void OnQueryPageSettings(QueryPageSettingsEventArgs e)
            {
                base.OnQueryPageSettings(e);

                // A single Word document can have multiple sections that specify pages with different sizes,
                // orientation and paper trays. This code is called by the .NET printing framework before
                // each page is printed and we get a chance to specify how the page is to be printed.
                PageInfo pageInfo = mDocument.GetPageInfo(mCurrentPage - 1);
                e.PageSettings.PaperSize = pageInfo.GetDotNetPaperSize(PrinterSettings.PaperSizes);
                // MS Word stores the paper source (printer tray) for each section as a printer-specfic value.
                // To obtain the correct tray value you will need to use the RawKindValue returned
                // by .NET for your printer.
                e.PageSettings.PaperSource.RawKind = pageInfo.PaperTray;
                e.PageSettings.Landscape = pageInfo.Landscape;
            }

            /// <summary>
            /// Called for each page to render it for printing.
            /// </summary>
            protected override void OnPrintPage(PrintPageEventArgs e)
            {
                base.OnPrintPage(e);

                // Aspose.Words rendering engine creates a page that is drawn from the 0,0 of the paper,
                // but there is some hard margin in the printer and the .NET printing framework
                // renders from there. We need to offset by that hard margin.

                // In .NET 1.1 the hard margin is not available programmatically, lets hardcode to about 4mm.
                float hardOffsetX = 20;
                float hardOffsetY = 20;

                // This is in .NET 2.0 only. Uncomment when needed.
                // float hardOffsetX = e.PageSettings.HardMarginX;
                // float hardOffsetY = e.PageSettings.HardMarginY;

                int pageIndex = mCurrentPage - 1;
                mDocument.RenderToScale(mCurrentPage, e.Graphics, -hardOffsetX, -hardOffsetY, 1.0f);

                mCurrentPage++;
                e.HasMorePages = (mCurrentPage <= mPageTo);
            }

            private readonly Document mDocument;
            private int mCurrentPage;
            private int mPageTo;
        }
#endif

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


GetSizeInPixels Method

Aspose.Words

PageInfo.GetSizeInPixels Method

Calculates the page size in pixels for a specified zoom factor and resolution.

Overload List

Calculates the page size in pixels for a specified zoom factor and resolution.

public Size GetSizeInPixels(float,float);

Calculates the page size in pixels for a specified zoom factor and resolution.

public Size GetSizeInPixels(float,float,float);

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


PageInfo.GetSizeInPixels Method (Single, Single)

Calculates the page size in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetSizeInPixels( _
ByVal scale As Single, _
ByVal dpi As Single _
) As Size
[C#]
public Size GetSizeInPixels(
float scale,
float dpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
dpi
The resolution (horizontal and vertical) to convert from points to pixels (dots per inch).

Return Value

The size of the page in pixels.

Example

Renders a page of a Word document into a bitmap using a specified zoom factor.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

            PageInfo pageInfo = doc.GetPageInfo(0);

            // Let's say we want the image at 50% zoom.
            const float myScale = 0.50f;

            // Let's say we want the image at this resolution.
            const float myResolution = 200.0f;

            Size pageSize = pageInfo.GetSizeInPixels(myScale, myResolution);
#if NETSTANDARD2_0 || __MOBILE__
            using (SKBitmap bitmap = new SKBitmap(pageSize.Width, pageSize.Height))
            {
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    // Scale to compensate for the larger bitmap
                    canvas.Scale(2);

                    // Fill the page background.
                    // If you need to set color without specific options, you can use "canvas.Clear(SKColors.White);"
                    SKPaint paint = new SKPaint
                    {
                        Color = SKColors.White,
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High
                    };

                    canvas.DrawPaint(paint);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, canvas, 0, 0, myScale);
                }

                using (SKFileWStream fs = new SKFileWStream(ArtifactsDir + "Rendering.RenderToScale.png"))
                {
                    bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100);
                }
            }
#else
            using (Bitmap img = new Bitmap(pageSize.Width, pageSize.Height))
            {
                img.SetResolution(myResolution, myResolution);

                using (Graphics gr = Graphics.FromImage(img))
                {
                    // You can apply various settings to the Graphics object.
                    gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    // Fill the page background.
                    gr.FillRectangle(Brushes.White, 0, 0, pageSize.Width, pageSize.Height);

                    // Render the page using the zoom.
                    doc.RenderToScale(0, gr, 0, 0, myScale);
                }

                img.Save(ArtifactsDir + "Rendering.RenderToScale.png");
            }
#endif

See Also

PageInfo Class | Aspose.Words.Rendering Namespace | PageInfo.GetSizeInPixels Overload List


PageInfo.GetSizeInPixels Method (Single, Single, Single)

Calculates the page size in pixels for a specified zoom factor and resolution.

[Visual Basic]
Overloads Public Function GetSizeInPixels( _
ByVal scale As Single, _
ByVal horizontalDpi As Single, _
ByVal verticalDpi As Single _
) As Size
[C#]
public Size GetSizeInPixels(
float scale,
float horizontalDpi,
float verticalDpi
);

Parameters

scale
The zoom factor (1.0 is 100%).
horizontalDpi
The horizontal resolution to convert from points to pixels (dots per inch).
verticalDpi
The vertical resolution to convert from points to pixels (dots per inch).

Return Value

The size of the page in pixels.

See Also

PageInfo Class | Aspose.Words.Rendering Namespace | PageInfo.GetSizeInPixels Overload List


PageInfo.GetSpecifiedPrinterPaperSource Method

Gets the PaperSource object suitable for printing the page represented by this PageInfo.

[Visual Basic]
Public Function GetSpecifiedPrinterPaperSource( _
ByVal paperSources As PaperSourceCollection, _
ByVal defaultPageSettingsPaperSource As PaperSource _
) As PaperSource
[C#]
public PaperSource GetSpecifiedPrinterPaperSource(
PaperSourceCollection paperSources,
PaperSource defaultPageSettingsPaperSource
);

Parameters

paperSources
Available paper sources.
defaultPageSettingsPaperSource
Paper source defined in default printer settings.

Return Value

An object that you can use in the .NET printing framework to specify the paper source.

Remarks

This method requires .NET Framework 2.0 or later.

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


PrinterSettingsContainer Class

Represent a storage for some parameters of PrinterSettings object. Access to data of PrinterSettings takes long time. PrinterSettingsContainer caches parameters from PrinterSettings, so printing works faster.

For a list of all members of this type, see PrinterSettingsContainer Members.

System.Object
Aspose.Words.Rendering.PrinterSettingsContainer

[Visual Basic]
Public Class PrinterSettingsContainer
[C#]
public class PrinterSettingsContainer

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PrinterSettingsContainer Members | Aspose.Words.Rendering Namespace


PrinterSettingsContainer Members

PrinterSettingsContainer overview

Public Instance Constructors

PrinterSettingsContainer Constructor Creates a container for PrinterSettings.

Public Instance Properties

DefaultPageSettingsPaperSource | See PaperSource of DefaultPageSettings.
PaperSizes | See PaperSizes.
PaperSources | See PaperSources.

See Also

PrinterSettingsContainer Class | Aspose.Words.Rendering Namespace


PrinterSettingsContainer Constructor

Creates a container for PrinterSettings.

[Visual Basic]
Public Sub New( _
ByVal settings As PrinterSettings _
)
[C#]
public PrinterSettingsContainer(
PrinterSettings settings
);

See Also

PrinterSettingsContainer Class | Aspose.Words.Rendering Namespace


PrinterSettingsContainer Properties

The properties of the PrinterSettingsContainer class are listed below. For a complete list of PrinterSettingsContainer class members, see the PrinterSettingsContainer Members topic.

Public Instance Properties

DefaultPageSettingsPaperSource | See PaperSource of DefaultPageSettings.
PaperSizes | See PaperSizes.
PaperSources | See PaperSources.

See Also

PrinterSettingsContainer Class | Aspose.Words.Rendering Namespace


DefaultPageSettingsPaperSource Property

Aspose.Words

PrinterSettingsContainer.DefaultPageSettingsPaperSource Property

See PaperSource of DefaultPageSettings.

[Visual Basic]
Public ReadOnly Property DefaultPageSettingsPaperSource As PaperSource
[C#]
public PaperSource DefaultPageSettingsPaperSource {get;}

See Also

PrinterSettingsContainer Class | Aspose.Words.Rendering Namespace


PaperSizes Property

Aspose.Words

PrinterSettingsContainer.PaperSizes Property

See PaperSizes.

[Visual Basic]
Public ReadOnly Property PaperSizes As PaperSizeCollection
[C#]
public PaperSizeCollection PaperSizes {get;}

See Also

PrinterSettingsContainer Class | Aspose.Words.Rendering Namespace


PaperSources Property

Aspose.Words

PrinterSettingsContainer.PaperSources Property

See PaperSources.

[Visual Basic]
Public ReadOnly Property PaperSources As PaperSourceCollection
[C#]
public PaperSourceCollection PaperSources {get;}

See Also

PrinterSettingsContainer Class | Aspose.Words.Rendering Namespace


ShapeRenderer Class

Provides methods to render an individual Shape or GroupShape to a raster or vector image or to a Graphics object.

For a list of all members of this type, see ShapeRenderer Members.

System.Object
Aspose.Words.Rendering.NodeRendererBase
Aspose.Words.Rendering.ShapeRenderer

[Visual Basic]
Public Class ShapeRenderer
Inherits NodeRendererBase
[C#]
public class ShapeRenderer : NodeRendererBase

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ShapeRenderer Members | Aspose.Words.Rendering Namespace


ShapeRenderer Members

ShapeRenderer overview

Public Instance Constructors

ShapeRenderer Constructor Initializes a new instance of this class.

Public Instance Properties

BoundsInPoints (inherited from NodeRendererBase) | Gets the actual bounds of the shape in points.
OpaqueBoundsInPoints (inherited from NodeRendererBase) | Gets the opaque bounds of the shape in points.
SizeInPoints (inherited from NodeRendererBase) | Gets the actual size of the shape in points.

Public Instance Methods

GetBoundsInPixels (inherited from NodeRendererBase) | Overloaded. Calculates the bounds of the shape in pixels for a specified zoom factor and resolution.
GetOpaqueBoundsInPixels (inherited from NodeRendererBase) | Overloaded. Calculates the opaque bounds of the shape in pixels for a specified zoom factor and resolution.
GetSizeInPixels (inherited from NodeRendererBase) | Overloaded. Calculates the size of the shape in pixels for a specified zoom factor and resolution.
RenderToScale (inherited from NodeRendererBase) | Renders the shape into a Graphics object to a specified scale.
RenderToSize (inherited from NodeRendererBase) | Renders the shape into a Graphics object to a specified size.
Save (inherited from NodeRendererBase) | Overloaded. Renders the shape and saves into an image.

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal shape As ShapeBase _
)
[C#]
public ShapeRenderer(
ShapeBase shape
);

Parameters

shape
The DrawinML shape object that you want to render.

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ThumbnailGeneratingOptions Class

Can be used to specify additional options when generating thumbnail for a document. User can call method UpdateThumbnail to generate Thumbnail for a document.

For a list of all members of this type, see ThumbnailGeneratingOptions Members.

System.Object
Aspose.Words.Rendering.ThumbnailGeneratingOptions

[Visual Basic]
Public Class ThumbnailGeneratingOptions
[C#]
public class ThumbnailGeneratingOptions

Requirements

Namespace: Aspose.Words.Rendering

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ThumbnailGeneratingOptions Members | Aspose.Words.Rendering Namespace


ThumbnailGeneratingOptions Members

ThumbnailGeneratingOptions overview

Public Instance Constructors

ThumbnailGeneratingOptions Constructor Initializes a new instance of the ThumbnailGeneratingOptions class.

Public Instance Properties

GenerateFromFirstPage | Specifies whether to generate thumbnail from first page of the document or first image. Default is true, which means thumbnail will be generated from first page of the document. If value is false and there is no image in the document, thumbnail will be generated from first page of the document.
ThumbnailSize | Size of generated thumbnail in pixels. Default is 600x900.

See Also

ThumbnailGeneratingOptions Class | Aspose.Words.Rendering Namespace


ThumbnailGeneratingOptions Constructor

Initializes a new instance of the ThumbnailGeneratingOptions class.

[Visual Basic]
Public Sub New()
[C#]
public ThumbnailGeneratingOptions();

See Also

ThumbnailGeneratingOptions Class | Aspose.Words.Rendering Namespace


ThumbnailGeneratingOptions Properties

The properties of the ThumbnailGeneratingOptions class are listed below. For a complete list of ThumbnailGeneratingOptions class members, see the ThumbnailGeneratingOptions Members topic.

Public Instance Properties

GenerateFromFirstPage | Specifies whether to generate thumbnail from first page of the document or first image. Default is true, which means thumbnail will be generated from first page of the document. If value is false and there is no image in the document, thumbnail will be generated from first page of the document.
ThumbnailSize | Size of generated thumbnail in pixels. Default is 600x900.

See Also

ThumbnailGeneratingOptions Class | Aspose.Words.Rendering Namespace


GenerateFromFirstPage Property

Aspose.Words

ThumbnailGeneratingOptions.GenerateFromFirstPage Property

Specifies whether to generate thumbnail from first page of the document or first image. Default is true, which means thumbnail will be generated from first page of the document. If value is false and there is no image in the document, thumbnail will be generated from first page of the document.

[Visual Basic]
Public Property GenerateFromFirstPage As Boolean
[C#]
public bool GenerateFromFirstPage {get; set;}

See Also

ThumbnailGeneratingOptions Class | Aspose.Words.Rendering Namespace


ThumbnailSize Property

Aspose.Words

ThumbnailGeneratingOptions.ThumbnailSize Property

Size of generated thumbnail in pixels. Default is 600x900.

[Visual Basic]
Public Property ThumbnailSize As Size
[C#]
public Size ThumbnailSize {get; set;}

See Also

ThumbnailGeneratingOptions Class | Aspose.Words.Rendering Namespace


Aspose.Words.Replacing

Aspose.Words

Aspose.Words.Replacing Namespace

The Aspose.Words.Replacing namespace provides classes to manipulate with find/replace operations over the document tree.

Namespace hierarchy

Classes

Class | Description
FindReplaceOptions | Specifies options for find/replace operations.
ReplacingArgs | Provides data for a custom replace operation.

Interfaces

Interface | Description
IReplacingCallback | Implement this interface if you want to have your own custom method called during a find and replace operation.

Enumerations

Enumeration | Description
ReplaceAction | Allows the user to specify what happens to the current match during a replace operation.


FindReplaceOptions Class

Specifies options for find/replace operations.

For a list of all members of this type, see FindReplaceOptions Members.

System.Object
Aspose.Words.Replacing.FindReplaceOptions

[Visual Basic]
Public Class FindReplaceOptions
[C#]
public class FindReplaceOptions

Example

Simple find and replace operation.

[C#]

// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test.
Console.WriteLine(doc.FirstSection.Body.Paragraphs[0].GetText());

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = false;
options.FindWholeWordsOnly = false;

// Replace the text in the document.
doc.Range.Replace("_CustomerName_", "James Bond", options);

// Save the modified document.
doc.Save(ArtifactsDir + "Range.ReplaceSimple.docx");

Requirements

Namespace: Aspose.Words.Replacing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FindReplaceOptions Members | Aspose.Words.Replacing Namespace


FindReplaceOptions Members

FindReplaceOptions overview

Public Instance Constructors

FindReplaceOptions Overloaded. Initializes a new instance of the FindReplaceOptions class.

Public Instance Properties

ApplyFont | Text formatting applied to new content.
ApplyParagraphFormat | Paragraph formatting applied to new content.
Direction | Selects direction for replace. Default value is Forward.
FindWholeWordsOnly | True indicates the oldValue must be a standalone word.
MatchCase | True indicates case-sensitive comparison, false indicates case-insensitive comparison.
PreserveMetaCharacters | True indicates that meta-characters beginning with "&" are preserved. Default value is false.
ReplacingCallback | The user-defined method which is called before every replace occurrence.

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


FindReplaceOptions Constructor

Initializes a new instance of the FindReplaceOptions class.

Overload List

Initializes a new instance of the FindReplaceOptions class.

public FindReplaceOptions();

public FindReplaceOptions(FindReplaceDirection);

public FindReplaceOptions(FindReplaceDirection,IReplacingCallback);

public FindReplaceOptions(IReplacingCallback);

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


FindReplaceOptions Constructor ()

Initializes a new instance of the FindReplaceOptions class.

[Visual Basic]
Overloads Public Sub New()
[C#]
public FindReplaceOptions();

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace | FindReplaceOptions Constructor Overload List


FindReplaceOptions Constructor (FindReplaceDirection)

[Visual Basic]
Overloads Public Sub New( _
ByVal direction As FindReplaceDirection _
)
[C#]
public FindReplaceOptions(
FindReplaceDirection direction
);

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace | FindReplaceOptions Constructor Overload List


FindReplaceOptions Constructor (IReplacingCallback)

[Visual Basic]
Overloads Public Sub New( _
ByVal replacingCallback As IReplacingCallback _
)
[C#]
public FindReplaceOptions(
IReplacingCallback replacingCallback
);

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace | FindReplaceOptions Constructor Overload List


FindReplaceOptions Constructor (FindReplaceDirection, IReplacingCallback)

[Visual Basic]
Overloads Public Sub New( _
ByVal direction As FindReplaceDirection, _
ByVal replacingCallback As IReplacingCallback _
)
[C#]
public FindReplaceOptions(
FindReplaceDirection direction,
IReplacingCallback replacingCallback
);

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace | FindReplaceOptions Constructor Overload List


FindReplaceOptions Properties

The properties of the FindReplaceOptions class are listed below. For a complete list of FindReplaceOptions class members, see the FindReplaceOptions Members topic.

Public Instance Properties

ApplyFont | Text formatting applied to new content.
ApplyParagraphFormat | Paragraph formatting applied to new content.
Direction | Selects direction for replace. Default value is Forward.
FindWholeWordsOnly | True indicates the oldValue must be a standalone word.
MatchCase | True indicates case-sensitive comparison, false indicates case-insensitive comparison.
PreserveMetaCharacters | True indicates that meta-characters beginning with "&" are preserved. Default value is false.
ReplacingCallback | The user-defined method which is called before every replace occurrence.

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


ApplyFont Property

Aspose.Words

FindReplaceOptions.ApplyFont Property

Text formatting applied to new content.

[Visual Basic]
Public ReadOnly Property ApplyFont As Font
[C#]
public Font ApplyFont {get;}

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


ApplyParagraphFormat Property

Aspose.Words

FindReplaceOptions.ApplyParagraphFormat Property

Paragraph formatting applied to new content.

[Visual Basic]
Public ReadOnly Property ApplyParagraphFormat As ParagraphFormat
[C#]
public ParagraphFormat ApplyParagraphFormat {get;}

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


Direction Property

Aspose.Words

FindReplaceOptions.Direction Property

Selects direction for replace. Default value is Forward.

[Visual Basic]
Public Property Direction As FindReplaceDirection
[C#]
public FindReplaceDirection Direction {get; set;}

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


FindWholeWordsOnly Property

Aspose.Words

FindReplaceOptions.FindWholeWordsOnly Property

True indicates the oldValue must be a standalone word.

[Visual Basic]
Public Property FindWholeWordsOnly As Boolean
[C#]
public bool FindWholeWordsOnly {get; set;}

Example

Simple find and replace operation.

[C#]

// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test.
Console.WriteLine(doc.FirstSection.Body.Paragraphs[0].GetText());

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = false;
options.FindWholeWordsOnly = false;

// Replace the text in the document.
doc.Range.Replace("_CustomerName_", "James Bond", options);

// Save the modified document.
doc.Save(ArtifactsDir + "Range.ReplaceSimple.docx");

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


MatchCase Property

Aspose.Words

FindReplaceOptions.MatchCase Property

True indicates case-sensitive comparison, false indicates case-insensitive comparison.

[Visual Basic]
Public Property MatchCase As Boolean
[C#]
public bool MatchCase {get; set;}

Example

Simple find and replace operation.

[C#]

// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Hello _CustomerName_,");

// Check the document contains what we are about to test.
Console.WriteLine(doc.FirstSection.Body.Paragraphs[0].GetText());

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = false;
options.FindWholeWordsOnly = false;

// Replace the text in the document.
doc.Range.Replace("_CustomerName_", "James Bond", options);

// Save the modified document.
doc.Save(ArtifactsDir + "Range.ReplaceSimple.docx");

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


PreserveMetaCharacters Property

Aspose.Words

FindReplaceOptions.PreserveMetaCharacters Property

True indicates that meta-characters beginning with "&" are preserved. Default value is false.

[Visual Basic]
Public Property PreserveMetaCharacters As Boolean
[C#]
public bool PreserveMetaCharacters {get; set;}

Example

Shows how to preserved meta-characters that beginning with "&".

[C#]

Document doc = new Document(MyDir + "Range.FindAndReplaceWithPreserveMetaCharacters.docx");

FindReplaceOptions options = new FindReplaceOptions();
options.FindWholeWordsOnly = true;
options.PreserveMetaCharacters = true;

doc.Range.Replace("sad", "&ldquo; some text &rdquo;", options);

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


ReplacingCallback Property

Aspose.Words

FindReplaceOptions.ReplacingCallback Property

The user-defined method which is called before every replace occurrence.

[Visual Basic]
Public Property ReplacingCallback As IReplacingCallback
[C#]
public IReplacingCallback ReplacingCallback {get; set;}

See Also

FindReplaceOptions Class | Aspose.Words.Replacing Namespace


IReplacingCallback Interface

Implement this interface if you want to have your own custom method called during a find and replace operation.

For a list of all members of this type, see IReplacingCallback Members.

[Visual Basic]
Public Interface IReplacingCallback
[C#]
public interface IReplacingCallback

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
Replaces text specified with regular expression with HTML.
[C#]

// Open the document.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);

    doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);

    // Save the modified document.
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
    {
        mOptions = options;
    }

    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document) args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }

    private readonly FindReplaceOptions mOptions;
}
Show changes for headers and footers order
[C#]

Document doc = new Document(MyDir + "HeaderFooter.HeaderFooterOrder.docx");

            // Assert that we use special header and footer for the first page
            // The order for this: first header\footer, even header\footer, primary header\footer
            Section firstPageSection = doc.FirstSection;
            Assert.AreEqual(true, firstPageSection.PageSetup.DifferentFirstPageHeaderFooter);

            ReplaceLog logger = new ReplaceLog();
            FindReplaceOptions options = new FindReplaceOptions { ReplacingCallback = logger };

            doc.Range.Replace(new Regex("(header|footer)"), "", options);

            doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterOrder.docx");
#if __MOBILE__
            Assert.AreEqual("First header\nFirst footer\nSecond header\nSecond footer\nThird header\n" +
                            "Third footer\n", logger.Text);
#else
            Assert.AreEqual("First header\nFirst footer\nSecond header\nSecond footer\nThird header\n" +
                            "Third footer\n", logger.Text.Replace("\r", ""));
#endif
            // Prepare our string builder for assert results without "DifferentFirstPageHeaderFooter"
            logger.ClearText();

            // Remove special first page
            // The order for this: primary header, default header, primary footer, default footer, even header\footer
            firstPageSection.PageSetup.DifferentFirstPageHeaderFooter = false;

            doc.Range.Replace(new Regex("(header|footer)"), "", options);
#if __MOBILE__
            Assert.AreEqual("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\nSecond footer\n", logger.Text);
#else
            Assert.AreEqual("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\nSecond footer\n", logger.Text.Replace("\r", ""));
#endif
        }

        private class ReplaceLog : IReplacingCallback
        {
            public ReplaceAction Replacing(ReplacingArgs args)
            {
                _textBuilder.AppendLine(args.MatchNode.GetText());
                return ReplaceAction.Skip;
            }

            internal void ClearText()
            {
                _textBuilder.Clear();
            }

            internal string Text
            {
                get { return _textBuilder.ToString(); }
            }

            private readonly StringBuilder _textBuilder = new StringBuilder();
        }

Requirements

Namespace: Aspose.Words.Replacing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IReplacingCallback Members | Aspose.Words.Replacing Namespace


IReplacingCallback Members

IReplacingCallback overview

Public Instance Methods

Replacing A user defined method that is called during a replace operation for each match found just before a replace is made.

See Also

IReplacingCallback Interface | Aspose.Words.Replacing Namespace


IReplacingCallback Methods

The methods of the IReplacingCallback interface are listed below. For a complete list of IReplacingCallback interface members, see the IReplacingCallback Members topic.

Public Instance Methods

Replacing A user defined method that is called during a replace operation for each match found just before a replace is made.

See Also

IReplacingCallback Interface | Aspose.Words.Replacing Namespace


IReplacingCallback.Replacing Method

A user defined method that is called during a replace operation for each match found just before a replace is made.

[Visual Basic]
Function Replacing( _
ByVal args As ReplacingArgs _
) As ReplaceAction
[C#]
ReplaceAction Replacing(
ReplacingArgs args
);

Return Value

A ReplaceAction value that specifies the action to be taken for the current match.

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
Replaces text specified with regular expression with HTML.
[C#]

// Open the document.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);

    doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);

    // Save the modified document.
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
    {
        mOptions = options;
    }

    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document) args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }

    private readonly FindReplaceOptions mOptions;
}

See Also

IReplacingCallback Interface | Aspose.Words.Replacing Namespace


ReplaceAction Enumeration

Allows the user to specify what happens to the current match during a replace operation.

[Visual Basic]
Public Enum ReplaceAction
[C#]
public enum ReplaceAction

Remarks

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}

Members

Member Name | Description | Value
Replace | Replace the current match. | 0
Skip | Skip the current match. | 1
Stop | Terminate the replace operation. | 2

Requirements

Namespace: Aspose.Words.Replacing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Replacing Namespace | IReplacingCallback | Range | Replace


ReplacingArgs Class

Provides data for a custom replace operation.

For a list of all members of this type, see ReplacingArgs Members.

System.Object
Aspose.Words.Replacing.ReplacingArgs

[Visual Basic]
Public Class ReplacingArgs
[C#]
public class ReplacingArgs

Remarks

See and its overloads.

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
Replaces text specified with regular expression with HTML.
[C#]

// Open the document.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);

    doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);

    // Save the modified document.
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
    {
        mOptions = options;
    }

    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document) args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }

    private readonly FindReplaceOptions mOptions;
}

Requirements

Namespace: Aspose.Words.Replacing

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ReplacingArgs Members | Aspose.Words.Replacing Namespace | IReplacingCallback | Range | Replace


ReplacingArgs Members

ReplacingArgs overview

Public Instance Properties

GroupIndex | Identifies, by index, a captured group in the Match that is to be replaced with the Replacement string.
GroupName | Identifies, by name, a captured group in the Match that is to be replaced with the Replacement string.
Match | The Match resulting from a single regular expression match during a Replace.
MatchNode | Gets the node that contains the beginning of the match.
MatchOffset | Gets the zero-based starting position of the match from the start of the node that contains the beginning of the match.
Replacement | Gets or sets the replacement string.

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace | IReplacingCallback | Range | Replace


ReplacingArgs Properties

The properties of the ReplacingArgs class are listed below. For a complete list of ReplacingArgs class members, see the ReplacingArgs Members topic.

Public Instance Properties

GroupIndex | Identifies, by index, a captured group in the Match that is to be replaced with the Replacement string.
GroupName | Identifies, by name, a captured group in the Match that is to be replaced with the Replacement string.
Match | The Match resulting from a single regular expression match during a Replace.
MatchNode | Gets the node that contains the beginning of the match.
MatchOffset | Gets the zero-based starting position of the match from the start of the node that contains the beginning of the match.
Replacement | Gets or sets the replacement string.

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace | IReplacingCallback | Range | Replace


GroupIndex Property

Aspose.Words

ReplacingArgs.GroupIndex Property

Identifies, by index, a captured group in the Match that is to be replaced with the Replacement string.

[Visual Basic]
Public Property GroupIndex As Integer
[C#]
public int GroupIndex {get; set;}

Remarks

GroupIndex has effect only when GroupName is null.

Default is zero.

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace


GroupName Property

Aspose.Words

ReplacingArgs.GroupName Property

Identifies, by name, a captured group in the Match that is to be replaced with the Replacement string.

[Visual Basic]
Public Property GroupName As String
[C#]
public string GroupName {get; set;}

Remarks

When group name is null, GroupIndex is used to identify the group.

Default is null.

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace


Match Property

Aspose.Words

ReplacingArgs.Match Property

The Match resulting from a single regular expression match during a Replace.

[Visual Basic]
Public ReadOnly Property Match As Match
[C#]
public Match Match {get;}

Remarks

Match.Index" gets the zero-based starting position of the match from the start of the find and replace range.

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace


MatchNode Property

Aspose.Words

ReplacingArgs.MatchNode Property

Gets the node that contains the beginning of the match.

[Visual Basic]
Public ReadOnly Property MatchNode As Node
[C#]
public Node MatchNode {get;}

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

Document mainDoc = new Document(MyDir + "InsertDocument1.doc");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocumentAtReplace.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph) args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace


MatchOffset Property

Aspose.Words

ReplacingArgs.MatchOffset Property

Gets the zero-based starting position of the match from the start of the node that contains the beginning of the match.

[Visual Basic]
Public ReadOnly Property MatchOffset As Integer
[C#]
public int MatchOffset {get;}

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace


Replacement Property

Aspose.Words

ReplacingArgs.Replacement Property

Gets or sets the replacement string.

[Visual Basic]
Public Property Replacement As String
[C#]
public string Replacement {get; set;}

Example

Replaces text specified with regular expression with HTML.

[C#]

// Open the document.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator(options);

    doc.Range.Replace(new Regex(@" <CustomerName>,"), String.Empty, options);

    // Save the modified document.
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    internal ReplaceWithHtmlEvaluator(FindReplaceOptions options)
    {
        mOptions = options;
    }

    /// <summary>
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document) args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }

    private readonly FindReplaceOptions mOptions;
}

See Also

ReplacingArgs Class | Aspose.Words.Replacing Namespace


Aspose.Words.Reporting

Aspose.Words

Aspose.Words.Reporting Namespace

This namespace contains classes of the Aspose.Words' new reporting engine that supports report templates marked up with a language based on the LINQ Method Syntax.

This new reporting engine is more advanced than the original mail merge reporting engine Aspose.Words.MailMerging and allows to retrieve data from any .NET class, perform grouping, sorting, joining and interpret C# expressions.

Namespace hierarchy

Classes

Class | Description
KnownTypeSet | Represents an unordered set (i.e. a collection of unique items) containing Type objects which fully or partially qualified names can be used within report templates to invoke the corresponding types' static members, perform type casts, etc.
ReportingEngine | Provides routines to populate template documents with data and a set of settings to control these routines.

Enumerations

Enumeration | Description
ReportBuildOptions | Specifies options controlling behavior of ReportingEngine while building a report.


KnownTypeSet Class

Represents an unordered set (i.e. a collection of unique items) containing Type objects which fully or partially qualified names can be used within report templates to invoke the corresponding types' static members, perform type casts, etc.

For a list of all members of this type, see KnownTypeSet Members.

System.Object
Aspose.Words.Reporting.KnownTypeSet

[Visual Basic]
Public Class KnownTypeSet
Implements IEnumerable`1([System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), IEnumerable
[C#]
public class KnownTypeSet : 0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], IEnumerable

Requirements

Namespace: Aspose.Words.Reporting

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

KnownTypeSet Members | Aspose.Words.Reporting Namespace


KnownTypeSet Members

KnownTypeSet overview

Public Instance Properties

Count Gets the count of items in the set.

Public Instance Methods

Add | Adds the specified Type object to the set. Throws ArgumentException in the following cases: - type is null. - type represents a void type. - type represents an invisible type, i.e. a non-public type or a public nested type which has a non-public outer type. - type represents a generic type. - type represents an array type. - type has been added to the set already.
Clear | Removes all items from the set.
GetEnumerator | Returns An IEnumerator object to iterate over items of the set.
Remove | Removes the specified Type object from the set. Throws ArgumentException if type is null.

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


KnownTypeSet Properties

The properties of the KnownTypeSet class are listed below. For a complete list of KnownTypeSet class members, see the KnownTypeSet Members topic.

Public Instance Properties

Count Gets the count of items in the set.

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


Count Property

Aspose.Words

KnownTypeSet.Count Property

Gets the count of items in the set.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


KnownTypeSet Methods

The methods of the KnownTypeSet class are listed below. For a complete list of KnownTypeSet class members, see the KnownTypeSet Members topic.

Public Instance Methods

Add | Adds the specified Type object to the set. Throws ArgumentException in the following cases: - type is null. - type represents a void type. - type represents an invisible type, i.e. a non-public type or a public nested type which has a non-public outer type. - type represents a generic type. - type represents an array type. - type has been added to the set already.
Clear | Removes all items from the set.
GetEnumerator | Returns An IEnumerator object to iterate over items of the set.
Remove | Removes the specified Type object from the set. Throws ArgumentException if type is null.

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


KnownTypeSet.Add Method

Adds the specified Type object to the set. Throws ArgumentException in the following cases:

- type is null.

- type represents a void type.

- type represents an invisible type, i.e. a non-public type or a public nested type which has a non-public outer type.

- type represents a generic type.

- type represents an array type.

- type has been added to the set already.

[Visual Basic]
Public Sub Add( _
ByVal type As Type _
)
[C#]
public void Add(
Type type
);

Parameters

type
A Type object to add.

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


KnownTypeSet.Clear Method

Removes all items from the set.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


KnownTypeSet.GetEnumerator Method

Returns An IEnumerator object to iterate over items of the set.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of Type) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<Type> GetEnumerator();

Return Value

An IEnumerator object to iterate over items of the set.

Implements

IEnumerable`1.GetEnumerator

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


KnownTypeSet.Remove Method

Removes the specified Type object from the set. Throws ArgumentException if type is null.

[Visual Basic]
Public Sub Remove( _
ByVal type As Type _
)
[C#]
public void Remove(
Type type
);

Parameters

type
A Type object to remove.

See Also

KnownTypeSet Class | Aspose.Words.Reporting Namespace


ReportBuildOptions Enumeration

Specifies options controlling behavior of ReportingEngine while building a report.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum ReportBuildOptions
[C#]
public enum ReportBuildOptions

Members

Member Name | Description | Value
None | Specifies default options. | 0
AllowMissingMembers | Specifies that missing object members should be treated as null literals by the engine. This option affects only access to instance (that is, non-static) object members and extension methods. If this option is not set, the engine throws an exception when encounters a missing object member. | 1
RemoveEmptyParagraphs | Specifies that the engine should remove paragraphs becoming empty after template syntax tags are removed or replaced with empty values. | 2
InlineErrorMessages | Specifies that the engine should inline template syntax error messages into output documents. If this option is not set, the engine throws an exception when encounters a syntax error. | 4

Requirements

Namespace: Aspose.Words.Reporting

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Reporting Namespace


ReportingEngine Class

Provides routines to populate template documents with data and a set of settings to control these routines.

For a list of all members of this type, see ReportingEngine Members.

System.Object
Aspose.Words.Reporting.ReportingEngine

[Visual Basic]
Public Class ReportingEngine
[C#]
public class ReportingEngine

Requirements

Namespace: Aspose.Words.Reporting

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ReportingEngine Members | Aspose.Words.Reporting Namespace


ReportingEngine Members

ReportingEngine overview

Public Static (Shared) Properties

UseReflectionOptimization Gets or sets a value indicating whether invocations of custom type members performed via reflection API are optimized using dynamic class generation or not. The default value is true.

Public Instance Constructors

ReportingEngine Constructor Initializes a new instance of this class.

Public Instance Properties

KnownTypes | Gets an unordered set (i.e. a collection of unique items) containing Type objects which fully or partially qualified names can be used within report templates processed by this engine instance to invoke the corresponding types' static members, perform type casts, etc.
Options | Gets or sets a set of flags controlling behavior of this ReportingEngine instance while building a report.

Public Instance Methods

BuildReport | Overloaded. Populates the specified template document with data from the specified source making it a ready report.
Equals |
GetHashCode |

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


ReportingEngine Constructor

Initializes a new instance of this class.

[Visual Basic]
Public Sub New()
[C#]
public ReportingEngine();

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


ReportingEngine Properties

The properties of the ReportingEngine class are listed below. For a complete list of ReportingEngine class members, see the ReportingEngine Members topic.

Public Static (Shared) Properties

UseReflectionOptimization Gets or sets a value indicating whether invocations of custom type members performed via reflection API are optimized using dynamic class generation or not. The default value is true.

Public Instance Properties

KnownTypes | Gets an unordered set (i.e. a collection of unique items) containing Type objects which fully or partially qualified names can be used within report templates processed by this engine instance to invoke the corresponding types' static members, perform type casts, etc.
Options | Gets or sets a set of flags controlling behavior of this ReportingEngine instance while building a report.

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


KnownTypes Property

Aspose.Words

ReportingEngine.KnownTypes Property

Gets an unordered set (i.e. a collection of unique items) containing Type objects which fully or partially qualified names can be used within report templates processed by this engine instance to invoke the corresponding types' static members, perform type casts, etc.

[Visual Basic]
Public ReadOnly Property KnownTypes As KnownTypeSet
[C#]
public KnownTypeSet KnownTypes {get;}

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


Options Property

Aspose.Words

ReportingEngine.Options Property

Gets or sets a set of flags controlling behavior of this ReportingEngine instance while building a report.

[Visual Basic]
Public Property Options As ReportBuildOptions
[C#]
public ReportBuildOptions Options {get; set;}

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


UseReflectionOptimization Property

Aspose.Words

ReportingEngine.UseReflectionOptimization Property

Gets or sets a value indicating whether invocations of custom type members performed via reflection API are optimized using dynamic class generation or not. The default value is true.

[Visual Basic]
Public Shared Property UseReflectionOptimization As Boolean
[C#]
public static bool UseReflectionOptimization {get; set;}

Remarks

There are some scenarios where it is preferrable to disable this optimization. For example, if you are dealing with small collections of data items all the time, then an overhead of dynamic class generation can be more noticeable than an overhead of direct reflection API calls.

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


ReportingEngine Methods

The methods of the ReportingEngine class are listed below. For a complete list of ReportingEngine class members, see the ReportingEngine Members topic.

Public Instance Methods

BuildReport | Overloaded. Populates the specified template document with data from the specified source making it a ready report.
Equals |
GetHashCode |

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


BuildReport Method

Aspose.Words

ReportingEngine.BuildReport Method

Populates the specified template document with data from the specified source making it a ready report.

Overload List

Populates the specified template document with data from the specified source making it a ready report.

public bool BuildReport(Document,object);

Populates the specified template document with data from the specified source making it a ready report.

public bool BuildReport(Document,object,string);

Populates the specified template document with data from the specified sources making it a ready report.

public bool BuildReport(Document,object[],string[]);

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


ReportingEngine.BuildReport Method (Document, Object)

Populates the specified template document with data from the specified source making it a ready report.

[Visual Basic]
Overloads Public Function BuildReport( _
ByVal document As Document, _
ByVal dataSource As Object _
) As Boolean
[C#]
public bool BuildReport(
Document document,
object dataSource
);

Parameters

document
A template document to be populated with data.
dataSource
A data source object.

Return Value

A flag indicating whether parsing of the template document was successful. The returned flag makes sense only if a value of the Options property includes the InlineErrorMessages option.

Remarks

Using this overload you can reference the data source's members in the template document, but you can not reference the data source object itself. You should use the BuildReport overload to achieve this.

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace | ReportingEngine.BuildReport Overload List


ReportingEngine.BuildReport Method (Document, Object, String)

Populates the specified template document with data from the specified source making it a ready report.

[Visual Basic]
Overloads Public Function BuildReport( _
ByVal document As Document, _
ByVal dataSource As Object, _
ByVal dataSourceName As String _
) As Boolean
[C#]
public bool BuildReport(
Document document,
object dataSource,
string dataSourceName
);

Parameters

document
A template document to be populated with data.
dataSource
A data source object.
dataSourceName
A name to reference the data source object in the template.

Return Value

A flag indicating whether parsing of the template document was successful. The returned flag makes sense only if a value of the Options property includes the InlineErrorMessages option.

Remarks

Using this overload you can reference the data source's members and the data source object itself in the template. If you are not going to reference the data source object itself, you can omit dataSourceName passing null or use the BuildReport overload.

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace | ReportingEngine.BuildReport Overload List


ReportingEngine.BuildReport Method (Document, Object[], String[])

Populates the specified template document with data from the specified sources making it a ready report.

[Visual Basic]
Overloads Public Function BuildReport( _
ByVal document As Document, _
ByVal dataSources As Object(), _
ByVal dataSourceNames As String() _
) As Boolean
[C#]
public bool BuildReport(
Document document,
object[] dataSources,
string[] dataSourceNames
);

Parameters

document
A template document to be populated with data.
dataSources
An array of data source objects.
dataSourceNames
An array of names to reference the data source objects within the template.

Return Value

A flag indicating whether parsing of the template document was successful. The returned flag makes sense only if a value of the Options property includes the InlineErrorMessages option.

Remarks

Using this overload you can reference multiple data source objects and their members in the template. The name of the first data source can be omitted (i.e. be an empty string or null) if you are going to reference the data source's members but not the data source object itself. Names of the other data sources must be specified and unique.

If you are going to use a single data source, consider using of BuildReport and BuildReport overloads instead.

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace | ReportingEngine.BuildReport Overload List


ReportingEngine.Equals Method

[Visual Basic]
NotOverridable Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public bool Equals(
object obj
);

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


ReportingEngine.GetHashCode Method

[Visual Basic]
NotOverridable Public Function GetHashCode() As Integer
[C#]
public int GetHashCode();

See Also

ReportingEngine Class | Aspose.Words.Reporting Namespace


Aspose.Words.Saving

Aspose.Words

Aspose.Words.Saving Namespace

The Aspose.Words.Saving namespace provides classes and enumerations that allow to specify additional options for saving or converting documents.

Namespace hierarchy

Classes

Class | Description
BookmarksOutlineLevelCollection | A collection of individual bookmarks outline level.
CssSavingArgs | Provides data for the CssSaving event.
DocSaveOptions | Can be used to specify additional options when saving a document into the Doc or Dot format.
DocumentPartSavingArgs | Provides data for the DocumentPartSaving callback.
DownsampleOptions | Allows to specify downsample options.
FixedPageSaveOptions | Contains common options that can be specified when saving a document into fixed page formats (PDF, XPS, images etc).
FontSavingArgs | Provides data for the FontSaving event.
GraphicsQualityOptions | Allows to specify additional Graphics quality options.
HtmlFixedSaveOptions | Can be used to specify additional options when saving a document into the HtmlFixed format.
HtmlSaveOptions | Can be used to specify additional options when saving a document into the Html, Mhtml or Epub format.
ImageSaveOptions | Allows to specify additional options when rendering document pages or shapes to images.
ImageSavingArgs | Provides data for the ImageSaving event.
MetafileRenderingOptions | Allows to specify additional metafile rendering options.
OdtSaveOptions | Can be used to specify additional options when saving a document into the Odt or Ott format.
OoxmlSaveOptions | Can be used to specify additional options when saving a document into the Docx, Docm, Dotx, Dotm or FlatOpc format.
OutlineOptions | Allows to specify outline options.
PageSavingArgs | Provides data for the PageSaving event.
PclSaveOptions | Can be used to specify additional options when saving a document into the Pcl format.
PdfDigitalSignatureDetails | Contains details for signing a PDF document with a digital signature.
PdfDigitalSignatureTimestampSettings | Contains settings of the digital signature timestamp.
PdfEncryptionDetails | Contains details for encrypting and access permissions for a PDF document.
PdfSaveOptions | Can be used to specify additional options when saving a document into the Pdf format.
PsSaveOptions | Can be used to specify additional options when saving a document into the Ps format.
ResourceSavingArgs | Provides data for the ResourceSaving event.
RtfSaveOptions | Can be used to specify additional options when saving a document into the Rtf format.
SaveOptions | This is an abstract base class for classes that allow the user to specify additional options when saving a document into a particular format.
SaveOutputParameters | This object is returned to the caller after a document is saved and contains additional information that has been generated or calculated during the save operation. The caller can use or ignore this object.
SvgSaveOptions | Can be used to specify additional options when saving a document into the Svg format.
TxtListIndentation | Specifies how list levels are indented when document is exporting to Text format.
TxtSaveOptions | Can be used to specify additional options when saving a document into the Text format.
TxtSaveOptionsBase | The base class for specifying additional options when saving a document into a text based formats.
WordML2003SaveOptions | Can be used to specify additional options when saving a document into the WordML format.
XamlFixedSaveOptions | Can be used to specify additional options when saving a document into the XamlFixed format.
XamlFlowSaveOptions | Can be used to specify additional options when saving a document into the XamlFlow or XamlFlowPack format.
XpsSaveOptions | Can be used to specify additional options when saving a document into the Xps format.

Interfaces

Interface | Description
ICssSavingCallback | Implement this interface if you want to control how Aspose.Words saves CSS (Cascading Style Sheet) when saving a document to HTML.
IDocumentPartSavingCallback | Implement this interface if you want to receive notifications and control how Aspose.Words saves document parts when exporting a document to Html or Epub format.
IFontSavingCallback | Implement this interface if you want to receive notifications and control how Aspose.Words saves fonts when exporting a document to HTML format.
IImageSavingCallback | Implement this interface if you want to control how Aspose.Words saves images when saving a document to HTML. May be used by other formats.
IPageSavingCallback | Implement this interface if you want to control how Aspose.Words saves separate pages when saving a document to fixed page formats.
IResourceSavingCallback | Implement this interface if you want to control how Aspose.Words saves external resources (images, fonts and css) when saving a document to fixed page HTML or SVG.

Enumerations

Enumeration | Description
ColorMode | Specifies how colors are rendered.
CssStyleSheetType | Specifies how CSS (Cascading Style Sheet) styles are exported to HTML.
DmlEffectsRenderingMode | Specifies how DrawingML effects are rendered to fixed page formats.
DmlRenderingMode | Specifies how DrawingML shapes are rendered to fixed page formats.
DocumentSplitCriteria | Specifies how the document is split into parts when saving to Html or Epub format.
EmfPlusDualRenderingMode | Specifies how Aspose.Words should render EMF+ Dual metafiles.
ExportFontFormat | Indicates the format that is used to export fonts while rendering to HTML fixed format.
ExportHeadersFootersMode | Specifies how headers and footers are exported to HTML, MHTML or EPUB.
ExportListLabels | Specifies how list labels are exported to HTML, MHTML and EPUB.
HeaderFooterBookmarksExportMode | Specifies how bookmarks in headers/footers are exported.
HtmlElementSizeOutputMode | Specifies how Aspose.Words exports element widths and heights to HTML, MHTML and EPUB.
HtmlFixedPageHorizontalAlignment | Specifies the horizontal alignment for pages in output HTML document.
HtmlMetafileFormat | Indicates the format in which metafiles are saved to HTML documents.
HtmlOfficeMathOutputMode | Specifies how Aspose.Words exports OfficeMath to HTML, MHTML and EPUB.
HtmlVersion | Indicates the version of HTML is used when saving the document to Html and Mhtml formats.
ImageBinarizationMethod | Specifies the method used to binarize image.
ImageColorMode | Specifies the color mode for the generated images of document pages.
ImagePixelFormat | Specifies the pixel format for the generated images of document pages.
MetafileRenderingMode | Specifies how Aspose.Words should render WMF and EMF metafiles.
NumeralFormat | Indicates the symbol set that is used to represent numbers while rendering to fixed page formats.
OdtSaveMeasureUnit | Specified units of measure to apply to measurable document content such as shape, widths and other during saving.
OoxmlCompliance | Allows to specify which OOXML specification will be used when saving in the DOCX format.
PdfCompliance | Specifies the PDF standards compliance level.
PdfCustomPropertiesExport | Specifies the way CustomDocumentProperties are exported to PDF file.
PdfDigitalSignatureHashAlgorithm | Specifies a digital hash algorithm used by a digital signature.
PdfEncryptionAlgorithm | Specifies the encryption algorithm to use for encrypting a PDF document.
PdfFontEmbeddingMode | Specifies how Aspose.Words should embed fonts.
PdfImageColorSpaceExportMode | Specifies how the color space will be selected for the images in PDF document.
PdfImageCompression | Specifies the type of compression applied to images in the PDF file.
PdfPageMode | Specifies how the PDF document should be displayed when opened in the PDF reader.
PdfPermissions | Specifies the operations that are allowed to a user on an encrypted PDF document.
PdfTextCompression | Specifies a type of compression applied to all content in the PDF file except images.
PdfZoomBehavior | Specifies the type of zoom applied to a PDF document when it is opened in a PDF viewer.
SvgTextOutputMode |
TiffCompression | Specifies what type of compression to apply when saving page images into a TIFF file.
TxtExportHeadersFootersMode | Specifies the way headers and footers are exported to plain text format.


BookmarksOutlineLevelCollection Class

A collection of individual bookmarks outline level.

For a list of all members of this type, see BookmarksOutlineLevelCollection Members.

System.Object
Aspose.Words.Saving.BookmarksOutlineLevelCollection

[Visual Basic]
Public Class BookmarksOutlineLevelCollection
Implements IEnumerable`1([System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089),[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)), IEnumerable
[C#]
public class BookmarksOutlineLevelCollection : 0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], IEnumerable

Remarks

Key is a case-insensitive string bookmark name. Value is a int bookmark outline level.

Bookmark outline level may be a value from 0 to 9. Specify 0 and Word bookmark will not be displayed in the document outline. Specify 1 and Word bookmark will be displayed in the document outline at level 1; 2 for level 2 and so on.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BookmarksOutlineLevelCollection Members | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection Members

BookmarksOutlineLevelCollection overview

Public Instance Constructors

BookmarksOutlineLevelCollection Constructor Initializes a new instance of the BookmarksOutlineLevelCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Overloaded. Provides access to the collection items.

Public Instance Methods

Add | Adds a bookmark to the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains a bookmark with the given name.
GetEnumerator |
IndexOfKey | Returns the zero-based index of the specified bookmark in the collection.
Remove | Removes a bookmark with the specified name from the collection.
RemoveAt | Removes a bookmark at the specified index.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection Constructor

Initializes a new instance of the BookmarksOutlineLevelCollection class.

[Visual Basic]
Public Sub New()
[C#]
public BookmarksOutlineLevelCollection();

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection Properties

The properties of the BookmarksOutlineLevelCollection class are listed below. For a complete list of BookmarksOutlineLevelCollection class members, see the BookmarksOutlineLevelCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Overloaded. Provides access to the collection items.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


Count Property

Aspose.Words

BookmarksOutlineLevelCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


Item Property

Aspose.Words

BookmarksOutlineLevelCollection.Item Property

Provides access to the collection items.

Overload List

Gets or sets a bookmark outline level at the specified index.

public int this[int] {get; set;}

Gets or a sets a bookmark outline level by the bookmark name.

public int this[string] {get; set;}

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


Item Property (Int32)

Aspose.Words

BookmarksOutlineLevelCollection.Item Property (Int32)

Gets or sets a bookmark outline level at the specified index.

[Visual Basic]
Overloads Public Default Property Item( _
ByVal index As Integer _
) As Integer
[C#]
public int this[
int index
] {get; set;}

Parameters

index
Zero-based index of the bookmark.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace | BookmarksOutlineLevelCollection.Item Overload List


Item Property (String)

Aspose.Words

BookmarksOutlineLevelCollection.Item Property (String)

Gets or a sets a bookmark outline level by the bookmark name.

[Visual Basic]
Overloads Public Default Property Item( _
ByVal name As String _
) As Integer
[C#]
public int this[
string name
] {get; set;}

Parameters

name
Case-insensitive name of the bookmark.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace | BookmarksOutlineLevelCollection.Item Overload List


BookmarksOutlineLevelCollection Methods

The methods of the BookmarksOutlineLevelCollection class are listed below. For a complete list of BookmarksOutlineLevelCollection class members, see the BookmarksOutlineLevelCollection Members topic.

Public Instance Methods

Add | Adds a bookmark to the collection.
Clear | Removes all elements from the collection.
Contains | Determines whether the collection contains a bookmark with the given name.
GetEnumerator |
IndexOfKey | Returns the zero-based index of the specified bookmark in the collection.
Remove | Removes a bookmark with the specified name from the collection.
RemoveAt | Removes a bookmark at the specified index.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.Add Method

Adds a bookmark to the collection.

[Visual Basic]
Public Sub Add( _
ByVal name As String, _
ByVal outlineLevel As Integer _
)
[C#]
public void Add(
string name,
int outlineLevel
);

Parameters

name
The case-insensitive name of the bookmark to add.
outlineLevel
The outline level of the bookmark. Valid range is 0 to 9.

Example

Shows how adding bookmarks outlines with whitespaces(pdf, xps)

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add bookmarks with whitespaces. MS Word formats (like doc, docx) does not support bookmarks with whitespaces by default
// and all whitespaces in the bookmarks were replaced with underscores. If you need to use bookmarks in PDF or XPS outlines, you can use them with whitespaces.
builder.StartBookmark("My Bookmark");
builder.Writeln("Text inside a bookmark.");

builder.StartBookmark("Nested Bookmark");
builder.Writeln("Text inside a NestedBookmark.");
builder.EndBookmark("Nested Bookmark");

builder.Writeln("Text after Nested Bookmark.");
builder.EndBookmark("My Bookmark");

// Specify bookmarks outline level. If you are using xps format, just use XpsSaveOptions.
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.OutlineOptions.BookmarksOutlineLevels.Add("My Bookmark", 1);
pdfSaveOptions.OutlineOptions.BookmarksOutlineLevels.Add("Nested Bookmark", 2);

doc.Save(ArtifactsDir + "Bookmarks.WhiteSpaces.pdf", pdfSaveOptions);

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.Clear Method

Removes all elements from the collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.Contains Method

Determines whether the collection contains a bookmark with the given name.

[Visual Basic]
Public Function Contains( _
ByVal name As String _
) As Boolean
[C#]
public bool Contains(
string name
);

Parameters

name
Case-insensitive name of the bookmark to locate.

Return Value

True if item is found in the collection; otherwise, false.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.GetEnumerator Method

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of KeyValuePair`2([System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089),[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089))) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.IndexOfKey Method

Returns the zero-based index of the specified bookmark in the collection.

[Visual Basic]
Public Function IndexOfKey( _
ByVal name As String _
) As Integer
[C#]
public int IndexOfKey(
string name
);

Parameters

name
The case-insensitive name of the bookmark.

Return Value

The zero based index. Negative value if not found.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.Remove Method

Removes a bookmark with the specified name from the collection.

[Visual Basic]
Public Sub Remove( _
ByVal name As String _
)
[C#]
public void Remove(
string name
);

Parameters

name
The case-insensitive name of the bookmark.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevelCollection.RemoveAt Method

Removes a bookmark at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero based index.

See Also

BookmarksOutlineLevelCollection Class | Aspose.Words.Saving Namespace


ColorMode Enumeration

Specifies how colors are rendered.

[Visual Basic]
Public Enum ColorMode
[C#]
public enum ColorMode

Members

Member Name | Description | Value
Normal | Rendering with unmodified colors. | 0
Grayscale | Rendering with colors in a range of gray shades from white to black. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


CssSavingArgs Class

Provides data for the CssSaving event.

For a list of all members of this type, see CssSavingArgs Members.

System.Object
Aspose.Words.Saving.CssSavingArgs

[Visual Basic]
Public Class CssSavingArgs
[C#]
public class CssSavingArgs

Remarks

By default, when Aspose.Words saves a document to HTML, it saves CSS information inline (as a value of the style attribute on every element).

CssSavingArgs allows to save CSS information into file by providing your own stream object.

To save CSS into stream, use the CssStream property.

To suppress saving CSS into a file and embedding to HTML document use the IsExportNeeded property.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CssSavingArgs Members | Aspose.Words.Saving Namespace


CssSavingArgs Members

CssSavingArgs overview

Public Instance Properties

CssStream | Allows to specify the stream where the CSS information will be saved to.
Document | Gets the document object that is currently being saved.
IsExportNeeded | Allows to specify whether the CSS will be exported to file and embedded to HTML document. Default is true. When this property is false, the CSS information will not be saved to a CSS file and will not be embedded to HTML document.
KeepCssStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving an CSS information.

See Also

CssSavingArgs Class | Aspose.Words.Saving Namespace


CssSavingArgs Properties

The properties of the CssSavingArgs class are listed below. For a complete list of CssSavingArgs class members, see the CssSavingArgs Members topic.

Public Instance Properties

CssStream | Allows to specify the stream where the CSS information will be saved to.
Document | Gets the document object that is currently being saved.
IsExportNeeded | Allows to specify whether the CSS will be exported to file and embedded to HTML document. Default is true. When this property is false, the CSS information will not be saved to a CSS file and will not be embedded to HTML document.
KeepCssStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving an CSS information.

See Also

CssSavingArgs Class | Aspose.Words.Saving Namespace


CssStream Property

Aspose.Words

CssSavingArgs.CssStream Property

Allows to specify the stream where the CSS information will be saved to.

[Visual Basic]
Public Property CssStream As Stream
[C#]
public Stream CssStream {get; set;}

Remarks

This property allows you to save CSS information to a stream.

The default value is null. This property doesn't suppress saving CSS information to a file or embedding to HTML document. To suppress exporting CSS use the IsExportNeeded property.

Using ICssSavingCallback you cannot substitute CSS with another. It is intended only for saving CSS to a stream.

See Also

CssSavingArgs Class | Aspose.Words.Saving Namespace | KeepCssStreamOpen


Document Property

Aspose.Words

CssSavingArgs.Document Property

Gets the document object that is currently being saved.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

See Also

CssSavingArgs Class | Aspose.Words.Saving Namespace


IsExportNeeded Property

Aspose.Words

CssSavingArgs.IsExportNeeded Property

Allows to specify whether the CSS will be exported to file and embedded to HTML document. Default is true. When this property is false, the CSS information will not be saved to a CSS file and will not be embedded to HTML document.

[Visual Basic]
Public Property IsExportNeeded As Boolean
[C#]
public bool IsExportNeeded {get; set;}

See Also

CssSavingArgs Class | Aspose.Words.Saving Namespace


KeepCssStreamOpen Property

Aspose.Words

CssSavingArgs.KeepCssStreamOpen Property

Specifies whether Aspose.Words should keep the stream open or close it after saving an CSS information.

[Visual Basic]
Public Property KeepCssStreamOpen As Boolean
[C#]
public bool KeepCssStreamOpen {get; set;}

Remarks

Default is false and Aspose.Words will close the stream you provided in the CssStream property after writing an CSS information into it. Specify true to keep the stream open.

See Also

CssSavingArgs Class | Aspose.Words.Saving Namespace | CssStream


CssStyleSheetType Enumeration

Specifies how CSS (Cascading Style Sheet) styles are exported to HTML.

[Visual Basic]
Public Enum CssStyleSheetType
[C#]
public enum CssStyleSheetType

Remarks

Members

Member Name | Description | Value
Inline | CSS styles are written inline (as a value of the style attribute on every element). | 0
Embedded | CSS styles are written separately from the content in a style sheet embedded in the HTML file. | 1
External | CSS styles are written separately from the content in a style sheet in an external file. The HTML file links the style sheet. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace | CssStyleSheetType


DmlEffectsRenderingMode Enumeration

Specifies how DrawingML effects are rendered to fixed page formats.

[Visual Basic]
Public Enum DmlEffectsRenderingMode
[C#]
public enum DmlEffectsRenderingMode

Members

Member Name | Description | Value
Simplified | Rendering of DrawingML effects are simplified. | 0
None | No DrawingML effects are rendered. | 1
Fine | DrawingML effects are rendered in fine mode which involves advanced processing. In this mode rendering of effects gives better results but at a higher performance cost than Simplified mode. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


DmlRenderingMode Enumeration

Specifies how DrawingML shapes are rendered to fixed page formats.

[Visual Basic]
Public Enum DmlRenderingMode
[C#]
public enum DmlRenderingMode

Example

Shows how to define rendering for DML shapes

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { DmlRenderingMode = DmlRenderingMode.DrawingML };

doc.Save(ArtifactsDir + "DrawingMl.pdf", pdfSaveOptions);

Members

Member Name | Description | Value
Fallback | If fall-back shape is available for DrawingML, Aspose.Words renders fall-back shape instead of the DrawingML. | 0
DrawingML | Aspose.Words ignores fall-back shape of DrawingML and renders DrawingML itself. This is the default mode. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


DocSaveOptions Class

Can be used to specify additional options when saving a document into the Doc or Dot format.

For a list of all members of this type, see DocSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.DocSaveOptions

[Visual Basic]
Public Class DocSaveOptions
Inherits SaveOptions
[C#]
public class DocSaveOptions : SaveOptions

Remarks

At the moment provides only the SaveFormat property, but in the future will have other options added, such as an encryption password or digital signature settings.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocSaveOptions Members | Aspose.Words.Saving Namespace


DocSaveOptions Members

DocSaveOptions overview

Public Instance Constructors

DocSaveOptions Overloaded. Initializes a new instance of the DocSaveOptions class.

Public Instance Properties

AlwaysCompressMetafiles | When false, small metafiles are not compressed for performance reason. Default value is true, all metafiles are compressed regardless of its size.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
Password | Gets/sets a password to encrypt document using RC4 encryption method.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Doc or Dot.
SaveRoutingSlip | When false, RoutingSlip data is not saved to output document. Default value is true.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


DocSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Doc format.

Overload List

Initializes a new instance of this class that can be used to save a document in the Doc format.

public DocSaveOptions();

Initializes a new instance of this class that can be used to save a document in the Doc or Dot format.

public DocSaveOptions(SaveFormat);

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


DocSaveOptions Constructor ()

Initializes a new instance of this class that can be used to save a document in the Doc format.

[Visual Basic]
Overloads Public Sub New()
[C#]
public DocSaveOptions();

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace | DocSaveOptions Constructor Overload List


DocSaveOptions Constructor (SaveFormat)

Initializes a new instance of this class that can be used to save a document in the Doc or Dot format.

[Visual Basic]
Overloads Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public DocSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be Doc or Dot.

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace | DocSaveOptions Constructor Overload List


DocSaveOptions Properties

The properties of the DocSaveOptions class are listed below. For a complete list of DocSaveOptions class members, see the DocSaveOptions Members topic.

Public Instance Properties

AlwaysCompressMetafiles | When false, small metafiles are not compressed for performance reason. Default value is true, all metafiles are compressed regardless of its size.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
Password | Gets/sets a password to encrypt document using RC4 encryption method.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Doc or Dot.
SaveRoutingSlip | When false, RoutingSlip data is not saved to output document. Default value is true.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


AlwaysCompressMetafiles Property

Aspose.Words

DocSaveOptions.AlwaysCompressMetafiles Property

When false, small metafiles are not compressed for performance reason. Default value is true, all metafiles are compressed regardless of its size.

[Visual Basic]
Public Property AlwaysCompressMetafiles As Boolean
[C#]
public bool AlwaysCompressMetafiles {get; set;}

Example

Shows how to change metafiles compression in a document while saving.

[C#]

// The document has a mathematical formula
Document doc = new Document(MyDir + "Document.AlwaysCompressMetafiles.doc");

// Large metafiles are always compressed when exporting a document in Aspose.Words, but small metafiles are not
// compressed for performance reason. Some other document editors, such as LibreOffice, cannot read uncompressed
// metafiles. The following option 'AlwaysCompressMetafiles' was introduced to choose appropriate behavior
DocSaveOptions saveOptions = new DocSaveOptions();
// False - small metafiles are not compressed for performance reason
// True - all metafiles are compressed regardless of its size
saveOptions.AlwaysCompressMetafiles = isAlwaysCompressMetafiles;

doc.Save(ArtifactsDir + "Document.AlwaysCompressMetafiles.doc", saveOptions);

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


Password Property

Aspose.Words

DocSaveOptions.Password Property

Gets/sets a password to encrypt document using RC4 encryption method.

[Visual Basic]
Public Property Password As String
[C#]
public string Password {get; set;}

Remarks

In order to save document without encryption this property should be null or empty string.

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

DocSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can be Doc or Dot.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


SaveRoutingSlip Property

Aspose.Words

DocSaveOptions.SaveRoutingSlip Property

When false, RoutingSlip data is not saved to output document. Default value is true.

[Visual Basic]
Public Property SaveRoutingSlip As Boolean
[C#]
public bool SaveRoutingSlip {get; set;}

See Also

DocSaveOptions Class | Aspose.Words.Saving Namespace


DocumentPartSavingArgs Class

Provides data for the DocumentPartSaving callback.

For a list of all members of this type, see DocumentPartSavingArgs Members.

System.Object
Aspose.Words.Saving.DocumentPartSavingArgs

[Visual Basic]
Public Class DocumentPartSavingArgs
[C#]
public class DocumentPartSavingArgs

Remarks

When Aspose.Words saves a document to HTML or related formats and DocumentSplitCriteria is specified, the document is split into parts and by default, each document part is saved into a separate file.

Class DocumentPartSavingArgs allows you to control how each document part will be saved. It allows to redefine how file names are generated or to completely circumvent saving of document parts into files by providing your own stream objects.

To save document parts into streams instead of files, use the DocumentPartStream property.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DocumentPartSavingArgs Members | Aspose.Words.Saving Namespace


DocumentPartSavingArgs Members

DocumentPartSavingArgs overview

Public Instance Properties

Document | Gets the document object that is being saved.
DocumentPartFileName | Gets or sets the file name (without path) where the document part will be saved to.
DocumentPartStream | Allows to specify the stream where the document part will be saved to.
KeepDocumentPartStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a document part.

See Also

DocumentPartSavingArgs Class | Aspose.Words.Saving Namespace


DocumentPartSavingArgs Properties

The properties of the DocumentPartSavingArgs class are listed below. For a complete list of DocumentPartSavingArgs class members, see the DocumentPartSavingArgs Members topic.

Public Instance Properties

Document | Gets the document object that is being saved.
DocumentPartFileName | Gets or sets the file name (without path) where the document part will be saved to.
DocumentPartStream | Allows to specify the stream where the document part will be saved to.
KeepDocumentPartStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a document part.

See Also

DocumentPartSavingArgs Class | Aspose.Words.Saving Namespace


Document Property

Aspose.Words

DocumentPartSavingArgs.Document Property

Gets the document object that is being saved.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

See Also

DocumentPartSavingArgs Class | Aspose.Words.Saving Namespace


DocumentPartFileName Property

Aspose.Words

DocumentPartSavingArgs.DocumentPartFileName Property

Gets or sets the file name (without path) where the document part will be saved to.

[Visual Basic]
Public Property DocumentPartFileName As String
[C#]
public string DocumentPartFileName {get; set;}

Remarks

This property allows you to redefine how the document part file names are generated during export to HTML or EPUB.

When the callback is invoked, this property contains the file name that was generated by Aspose.Words. You can change the value of this property to save the document part into a different file. Note that the file name for each part must be unique.

DocumentPartFileName must contain only the file name without the path. Aspose.Words determines the path for saving using the document file name. If output document file name was not specified, for instance when saving to a stream, this file name is used only for referencing document parts. The same is true when saving to EPUB format.

See Also

DocumentPartSavingArgs Class | Aspose.Words.Saving Namespace | DocumentPartStream


DocumentPartStream Property

Aspose.Words

DocumentPartSavingArgs.DocumentPartStream Property

Allows to specify the stream where the document part will be saved to.

[Visual Basic]
Public Property DocumentPartStream As Stream
[C#]
public Stream DocumentPartStream {get; set;}

Remarks

This property allows you to save document parts to streams instead of files during HTML export.

The default value is null. When this property is null, the document part will be saved to a file specified in the DocumentPartFileName property.

When saving to a stream in HTML format is requested by Save or Save and first document part is about to be saved, Aspose.Words suggests here the main output stream initially passed by the caller.

When saving to EPUB format that is a container format based on HTML, DocumentPartStream cannot be specified because all subsidiary parts will be encapsulated into a single output package.

See Also

DocumentPartSavingArgs Class | Aspose.Words.Saving Namespace | KeepDocumentPartStreamOpen


KeepDocumentPartStreamOpen Property

Aspose.Words

DocumentPartSavingArgs.KeepDocumentPartStreamOpen Property

Specifies whether Aspose.Words should keep the stream open or close it after saving a document part.

[Visual Basic]
Public Property KeepDocumentPartStreamOpen As Boolean
[C#]
public bool KeepDocumentPartStreamOpen {get; set;}

Remarks

Default is false and Aspose.Words will close the stream you provided in the DocumentPartStream property after writing a document part into it. Specify true to keep the stream open. Please note that the main output stream provided in the call to Save or Save will never be closed by Aspose.Words even if KeepDocumentPartStreamOpen is set to false.

See Also

DocumentPartSavingArgs Class | Aspose.Words.Saving Namespace | DocumentPartStream


DocumentSplitCriteria Enumeration

Specifies how the document is split into parts when saving to Html or Epub format.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum DocumentSplitCriteria
[C#]
public enum DocumentSplitCriteria

Remarks

DocumentSplitCriteria is a set of flags which can be combined. For instance you can split the document at page breaks and heading paragraphs in the same export operation.

Different criteria can partially overlap. For instance, Heading 1 style is frequently given PageBreakBefore property so it falls under two criteria: PageBreak and HeadingParagraph. Some section breaks can cause page breaks and so on. In typical cases specifying only one flag is the most practical option.

Members

Member Name | Description | Value
None | The document is not split. | 0
PageBreak | The document is split into parts at explicit page breaks. A page break can be specified by a PageBreak character, a section break specifying start of new section on a new page, or a paragraph that has its PageBreakBefore property set to true. | 1
ColumnBreak | The document is split into parts at column breaks. A column break can be specified by a ColumnBreak character or a section break specifying start of new section in a new column. | 2
SectionBreak | The document is split into parts at a section break of any type. | 4
HeadingParagraph | The document is split into parts at a paragraph formatted using a heading style Heading 1, Heading 2 etc. Use together with DocumentSplitHeadingLevel to specify the heading levels (from 1 to the specified level) at which to split. | 8

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace | DocumentSplitCriteria


DownsampleOptions Class

Allows to specify downsample options.

For a list of all members of this type, see DownsampleOptions Members.

System.Object
Aspose.Words.Saving.DownsampleOptions

[Visual Basic]
Public Class DownsampleOptions
[C#]
public class DownsampleOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

DownsampleOptions Members | Aspose.Words.Saving Namespace


DownsampleOptions Members

DownsampleOptions overview

Public Instance Constructors

DownsampleOptions Constructor Initializes a new instance of the DownsampleOptions class.

Public Instance Properties

DownsampleImages | Specifies whether images should be downsampled.
Resolution | Specifies the resolution in pixels per inch which the images should be downsampled to.
ResolutionThreshold | Specifies the threshold resolution in pixels per inch. If resolution of an image in the document is less than threshold value, the downsampling algorithm will not be applied. A value of 0 means the threshold check is not used and all images that can be reduced in size are downsampled.

See Also

DownsampleOptions Class | Aspose.Words.Saving Namespace


DownsampleOptions Constructor

Initializes a new instance of the DownsampleOptions class.

[Visual Basic]
Public Sub New()
[C#]
public DownsampleOptions();

See Also

DownsampleOptions Class | Aspose.Words.Saving Namespace


DownsampleOptions Properties

The properties of the DownsampleOptions class are listed below. For a complete list of DownsampleOptions class members, see the DownsampleOptions Members topic.

Public Instance Properties

DownsampleImages | Specifies whether images should be downsampled.
Resolution | Specifies the resolution in pixels per inch which the images should be downsampled to.
ResolutionThreshold | Specifies the threshold resolution in pixels per inch. If resolution of an image in the document is less than threshold value, the downsampling algorithm will not be applied. A value of 0 means the threshold check is not used and all images that can be reduced in size are downsampled.

See Also

DownsampleOptions Class | Aspose.Words.Saving Namespace


DownsampleImages Property

Aspose.Words

DownsampleOptions.DownsampleImages Property

Specifies whether images should be downsampled.

[Visual Basic]
Public Property DownsampleImages As Boolean
[C#]
public bool DownsampleImages {get; set;}

Remarks

The default value is true.

See Also

DownsampleOptions Class | Aspose.Words.Saving Namespace


Resolution Property

Aspose.Words

DownsampleOptions.Resolution Property

Specifies the resolution in pixels per inch which the images should be downsampled to.

[Visual Basic]
Public Property Resolution As Integer
[C#]
public int Resolution {get; set;}

Remarks

The default value is 220 ppi.

See Also

DownsampleOptions Class | Aspose.Words.Saving Namespace


ResolutionThreshold Property

Aspose.Words

DownsampleOptions.ResolutionThreshold Property

Specifies the threshold resolution in pixels per inch. If resolution of an image in the document is less than threshold value, the downsampling algorithm will not be applied. A value of 0 means the threshold check is not used and all images that can be reduced in size are downsampled.

[Visual Basic]
Public Property ResolutionThreshold As Integer
[C#]
public int ResolutionThreshold {get; set;}

Remarks

The default value is 0.

See Also

DownsampleOptions Class | Aspose.Words.Saving Namespace


EmfPlusDualRenderingMode Enumeration

Specifies how Aspose.Words should render EMF+ Dual metafiles.

[Visual Basic]
Public Enum EmfPlusDualRenderingMode
[C#]
public enum EmfPlusDualRenderingMode

Members

Member Name | Description | Value
EmfPlusWithFallback | Aspose.Words tries to render EMF+ part of EMF+ Dual metafile. If some of the EMF+ records are not supported then Aspose.Words renders EMF part of EMF+ Dual metafile. | 0
EmfPlus | Aspose.Words renders EMF+ part of EMF+ Dual metafile. | 1
Emf | Aspose.Words renders EMF part of EMF+ Dual metafile. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


ExportFontFormat Enumeration

Indicates the format that is used to export fonts while rendering to HTML fixed format.

[Visual Basic]
Public Enum ExportFontFormat
[C#]
public enum ExportFontFormat

Remarks

Members

Member Name | Description | Value
Woff | WOFF (Web Open Font Format). | 0
Ttf | TTF (TrueType Font format). | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace | FontFormat


ExportHeadersFootersMode Enumeration

Specifies how headers and footers are exported to HTML, MHTML or EPUB.

[Visual Basic]
Public Enum ExportHeadersFootersMode
[C#]
public enum ExportHeadersFootersMode

Remarks

Example

Demonstrates how to disable the export of headers and footers when saving to HTML based formats.

[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

// Disables exporting headers and footers.
HtmlSaveOptions saveOptions =
    new HtmlSaveOptions(SaveFormat.Html) { ExportHeadersFootersMode = ExportHeadersFootersMode.None };

doc.Save(ArtifactsDir + "HeaderFooter.DisableHeadersFooters.html", saveOptions);

Members

Member Name | Description | Value
None | Headers and footers are not exported. | 0
PerSection | Primary headers and footers are exported at the beginning and the end of each section. | 1
FirstSectionHeaderLastSectionFooter | Primary header of the first section is exported at the beginning of the document and primary footer is at the end. | 2
FirstPageHeaderFooterPerSection | First page header and footer are exported at the beginning and the end of each section. | 3

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace | ExportHeadersFootersMode


ExportListLabels Enumeration

Specifies how list labels are exported to HTML, MHTML and EPUB.

[Visual Basic]
Public Enum ExportListLabels
[C#]
public enum ExportListLabels

Remarks

Members

Member Name | Description | Value
Auto | Outputs list labels in auto mode. Uses HTML native elements when possible. | 0
AsInlineText | Outputs all list labels as inline text. | 1
ByHtmlTags | Outputs all list labels as HTML native elements. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace | ExportListLabels


FixedPageSaveOptions Class

Contains common options that can be specified when saving a document into fixed page formats (PDF, XPS, images etc).

For a list of all members of this type, see FixedPageSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Derived types

[Visual Basic]
MustInherit Public Class FixedPageSaveOptions
Inherits SaveOptions
[C#]
public abstract class FixedPageSaveOptions : SaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FixedPageSaveOptions Members | Aspose.Words.Saving Namespace


FixedPageSaveOptions Members

FixedPageSaveOptions overview

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat (inherited from SaveOptions) | Specifies the format in which the document will be saved if this save options object is used.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Public Instance Methods

Equals

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


FixedPageSaveOptions Properties

The properties of the FixedPageSaveOptions class are listed below. For a complete list of FixedPageSaveOptions class members, see the FixedPageSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat (inherited from SaveOptions) | Specifies the format in which the document will be saved if this save options object is used.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


JpegQuality Property

Aspose.Words

FixedPageSaveOptions.JpegQuality Property

Gets or sets a value determining the quality of the JPEG images inside Html document.

[Visual Basic]
Public Property JpegQuality As Integer
[C#]
public int JpegQuality {get; set;}

Remarks

Has effect only when a document contains JPEG images.

Use this property to get or set the quality of the images inside a document when saving in fixed page format. The value may vary from 0 to 100 where 0 means worst quality but maximum compression and 100 means best quality but minimum compression.

The default value is 95.

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

FixedPageSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

[Visual Basic]
Public Property MetafileRenderingOptions As MetafileRenderingOptions
[C#]
public MetafileRenderingOptions MetafileRenderingOptions {get; set;}

Example

Shows added fallback to bitmap rendering and changing type of warnings about unsupported metafile records

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.HandleRasterWarnings.doc");

    MetafileRenderingOptions metafileRenderingOptions =
        new MetafileRenderingOptions
        {
            EmulateRasterOperations = false,
            RenderingMode = MetafileRenderingMode.VectorWithFallback
        };

    // If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
    HandleDocumentWarnings callback = new HandleDocumentWarnings();
    doc.WarningCallback = callback;

    PdfSaveOptions saveOptions = new PdfSaveOptions();
    saveOptions.MetafileRenderingOptions = metafileRenderingOptions;

    doc.Save(ArtifactsDir + "PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);

    Assert.AreEqual(1, callback.mWarnings.Count);
    Assert.True(callback.mWarnings[0].Description.Contains("R2_XORPEN"));
}

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        //For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
        if (info.WarningType == WarningType.MinorFormattingLoss)
        {
            Console.WriteLine("Unsupported operation: " + info.Description);
            mWarnings.Warning(info);
        }
    }

    public WarningInfoCollection mWarnings = new WarningInfoCollection();
}

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

FixedPageSaveOptions.NumeralFormat Property

Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.

[Visual Basic]
Public Property NumeralFormat As NumeralFormat
[C#]
public NumeralFormat NumeralFormat {get; set;}

Remarks

If the value of this property is changed and page layout is already built then UpdatePageLayout is invoked automatically to update any changes.

Example

Demonstrates how to set the numeral format used when saving to PDF.

[C#]

PdfSaveOptions options = new PdfSaveOptions();
options.NumeralFormat = NumeralFormat.Context;

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


OptimizeOutput Property

Aspose.Words

FixedPageSaveOptions.OptimizeOutput Property

Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.

[Visual Basic]
Overridable Public Property OptimizeOutput As Boolean
[C#]
public virtual bool OptimizeOutput {get; set;}

Example

Shows how to optimize document objects while saving to xps.

[C#]

Document doc = new Document(MyDir + "XPSOutputOptimize.docx");

XpsSaveOptions saveOptions = new XpsSaveOptions { OptimizeOutput = true };

doc.Save(ArtifactsDir + "XPSOutputOptimize.xps", saveOptions);
Shows how to optimize document objects while saving to html.
[C#]

Document doc = new Document(MyDir + "HtmlFixedSaveOptions.OptimizeGraphicsOutput.doc");

HtmlFixedSaveOptions saveOptions = new HtmlFixedSaveOptions { OptimizeOutput = false };

doc.Save(ArtifactsDir + "HtmlFixedPageMargins.html", saveOptions);

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

FixedPageSaveOptions.PageCount Property

Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.

[Visual Basic]
Public Property PageCount As Integer
[C#]
public int PageCount {get; set;}

Example

Converts just one page (third page in this example) of the document to PDF.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

using (Stream stream = File.Create(ArtifactsDir + "Rendering.SaveToPdfStreamOnePage.pdf"))
{
    PdfSaveOptions options = new PdfSaveOptions();
    options.PageIndex = 2;
    options.PageCount = 1;
    doc.Save(stream, options);
}

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

FixedPageSaveOptions.PageIndex Property

Gets or sets the 0-based index of the first page to save. Default is 0.

[Visual Basic]
Public Property PageIndex As Integer
[C#]
public int PageIndex {get; set;}

Example

Converts just one page (third page in this example) of the document to PDF.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

using (Stream stream = File.Create(ArtifactsDir + "Rendering.SaveToPdfStreamOnePage.pdf"))
{
    PdfSaveOptions options = new PdfSaveOptions();
    options.PageIndex = 2;
    options.PageCount = 1;
    doc.Save(stream, options);
}

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


PageSavingCallback Property

Aspose.Words

FixedPageSaveOptions.PageSavingCallback Property

Allows to control how separate pages are saved when a document is exported to fixed page format.

[Visual Basic]
Public Property PageSavingCallback As IPageSavingCallback
[C#]
public IPageSavingCallback PageSavingCallback {get; set;}

Example

Shows how separate pages are saved when a document is exported to fixed page format.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

    HtmlFixedSaveOptions htmlFixedSaveOptions =
        new HtmlFixedSaveOptions { PageIndex = 0, PageCount = doc.PageCount };
    htmlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback();

    doc.Save(ArtifactsDir + "Rendering.html", htmlFixedSaveOptions);

    string[] filePaths = Directory.GetFiles(ArtifactsDir + "", "Page_*.html");

    for (int i = 0; i < doc.PageCount; i++)
    {
        string file = string.Format(ArtifactsDir + "Page_{0}.html", i);
    }
}

/// <summary>
/// Custom PageFileName is specified.
/// </summary>
private class CustomPageFileNamePageSavingCallback : IPageSavingCallback
{
    public void PageSaving(PageSavingArgs args)
    {
        // Specify name of the output file for the current page.
        args.PageFileName = string.Format(ArtifactsDir + "Page_{0}.html", args.PageIndex);
    }
}

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


FixedPageSaveOptions Methods

The methods of the FixedPageSaveOptions class are listed below. For a complete list of FixedPageSaveOptions class members, see the FixedPageSaveOptions Members topic.

Public Instance Methods

Equals

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


FixedPageSaveOptions.Equals Method

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

See Also

FixedPageSaveOptions Class | Aspose.Words.Saving Namespace


FontSavingArgs Class

Provides data for the FontSaving event.

For a list of all members of this type, see FontSavingArgs Members.

System.Object
Aspose.Words.Saving.FontSavingArgs

[Visual Basic]
Public Class FontSavingArgs
[C#]
public class FontSavingArgs

Remarks

When Aspose.Words saves a document to HTML or related formats and ExportFontResources is set to true, it saves each font subject for export into a separate file.

FontSavingArgs controls whether particular font resource should be exported and how.

FontSavingArgs also allows to redefine how font file names are generated or to completely circumvent saving of fonts into files by providing your own stream objects.

To decide whether to save a particular font resource, use the IsExportNeeded property.

To save fonts into streams instead of files, use the FontStream property.

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

FontSavingArgs Members | Aspose.Words.Saving Namespace


FontSavingArgs Members

FontSavingArgs overview

Public Instance Properties

Bold | Indicates whether the current font is bold.
Document | Gets the document object that is being saved.
FontFamilyName | Indicates the current font family name.
FontFileName | Gets or sets the file name (without path) where the font will be saved to.
FontStream | Allows to specify the stream where the font will be saved to.
IsExportNeeded | Allows to specify whether the current font will be exported as a font resource. Default is true.
IsSubsettingNeeded | Allows to specify whether the current font will be subsetted before exporting as a font resource.
Italic | Indicates whether the current font is italic.
KeepFontStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a font.
OriginalFileName | Gets the original font file name with an extension.
OriginalFileSize | Gets the original font file size.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


FontSavingArgs Properties

The properties of the FontSavingArgs class are listed below. For a complete list of FontSavingArgs class members, see the FontSavingArgs Members topic.

Public Instance Properties

Bold | Indicates whether the current font is bold.
Document | Gets the document object that is being saved.
FontFamilyName | Indicates the current font family name.
FontFileName | Gets or sets the file name (without path) where the font will be saved to.
FontStream | Allows to specify the stream where the font will be saved to.
IsExportNeeded | Allows to specify whether the current font will be exported as a font resource. Default is true.
IsSubsettingNeeded | Allows to specify whether the current font will be subsetted before exporting as a font resource.
Italic | Indicates whether the current font is italic.
KeepFontStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a font.
OriginalFileName | Gets the original font file name with an extension.
OriginalFileSize | Gets the original font file size.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


Bold Property

Aspose.Words

FontSavingArgs.Bold Property

Indicates whether the current font is bold.

[Visual Basic]
Public ReadOnly Property Bold As Boolean
[C#]
public bool Bold {get;}

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


Document Property

Aspose.Words

FontSavingArgs.Document Property

Gets the document object that is being saved.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


FontFamilyName Property

Aspose.Words

FontSavingArgs.FontFamilyName Property

Indicates the current font family name.

[Visual Basic]
Public ReadOnly Property FontFamilyName As String
[C#]
public string FontFamilyName {get;}

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


FontFileName Property

Aspose.Words

FontSavingArgs.FontFileName Property

Gets or sets the file name (without path) where the font will be saved to.

[Visual Basic]
Public Property FontFileName As String
[C#]
public string FontFileName {get; set;}

Remarks

This property allows you to redefine how the font file names are generated during export to HTML.

When the event is fired, this property contains the file name that was generated by Aspose.Words. You can change the value of this property to save the font into a different file. Note that file names must be unique.

Aspose.Words automatically generates a unique file name for every embedded font when exporting to HTML format. How the font file name is generated depends on whether you save the document to a file or to a stream.

When saving a document to a file, the generated font file name looks like <document base file name>.<original file name><optional suffix>.<extension>.

When saving a document to a stream, the generated font file name looks like Aspose.Words.<document guid>.<original file name><optional suffix>.<extension>.

FontFileName must contain only the file name without the path. Aspose.Words determines the path for saving using the document file name, the FontsFolder and FontsFolderAlias properties.

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace | FontStream | FontsFolder | FontsFolderAlias


FontStream Property

Aspose.Words

FontSavingArgs.FontStream Property

Allows to specify the stream where the font will be saved to.

[Visual Basic]
Public Property FontStream As Stream
[C#]
public Stream FontStream {get; set;}

Remarks

This property allows you to save fonts to streams instead of files during HTML export.

The default value is null. When this property is null, the font will be saved to a file specified in the FontFileName property.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace | FontFileName | KeepFontStreamOpen


IsExportNeeded Property

Aspose.Words

FontSavingArgs.IsExportNeeded Property

Allows to specify whether the current font will be exported as a font resource. Default is true.

[Visual Basic]
Public Property IsExportNeeded As Boolean
[C#]
public bool IsExportNeeded {get; set;}

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


IsSubsettingNeeded Property

Aspose.Words

FontSavingArgs.IsSubsettingNeeded Property

Allows to specify whether the current font will be subsetted before exporting as a font resource.

[Visual Basic]
Public Property IsSubsettingNeeded As Boolean
[C#]
public bool IsSubsettingNeeded {get; set;}

Remarks

Fonts can be exported as complete original font files or subsetted to include only the characters that are used in the document. Subsetting allows to reduce the resulting font resource size.

By default, Aspose.Words decides whether to perform subsetting or not by comparing the original font file size with the one specified in FontResourcesSubsettingSizeThreshold. You can override this behavior for individual fonts by setting the IsSubsettingNeeded property.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


Italic Property

Aspose.Words

FontSavingArgs.Italic Property

Indicates whether the current font is italic.

[Visual Basic]
Public ReadOnly Property Italic As Boolean
[C#]
public bool Italic {get;}

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace


KeepFontStreamOpen Property

Aspose.Words

FontSavingArgs.KeepFontStreamOpen Property

Specifies whether Aspose.Words should keep the stream open or close it after saving a font.

[Visual Basic]
Public Property KeepFontStreamOpen As Boolean
[C#]
public bool KeepFontStreamOpen {get; set;}

Remarks

Default is false and Aspose.Words will close the stream you provided in the FontStream property after writing a font into it. Specify true to keep the stream open.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace | FontStream


OriginalFileName Property

Aspose.Words

FontSavingArgs.OriginalFileName Property

Gets the original font file name with an extension.

[Visual Basic]
Public ReadOnly Property OriginalFileName As String
[C#]
public string OriginalFileName {get;}

Remarks

This property contains the original file name of the current font if it is known. Otherwise it can be an empty string.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace | OriginalFileSize


OriginalFileSize Property

Aspose.Words

FontSavingArgs.OriginalFileSize Property

Gets the original font file size.

[Visual Basic]
Public ReadOnly Property OriginalFileSize As Integer
[C#]
public int OriginalFileSize {get;}

Remarks

This property contains the original file size of the current font if it is known. Otherwise it can be zero.

See Also

FontSavingArgs Class | Aspose.Words.Saving Namespace | OriginalFileName | IsSubsettingNeeded


GraphicsQualityOptions Class

Allows to specify additional Graphics quality options.

For a list of all members of this type, see GraphicsQualityOptions Members.

System.Object
Aspose.Words.Saving.GraphicsQualityOptions

[Visual Basic]
Public Class GraphicsQualityOptions
[C#]
public class GraphicsQualityOptions

Example

Shows how to set render quality options.

[C#]

Document doc = new Document(MyDir + "SaveOptions.MyraidPro.docx");

GraphicsQualityOptions qualityOptions = new GraphicsQualityOptions
{
    SmoothingMode = SmoothingMode.AntiAlias,
    TextRenderingHint = TextRenderingHint.ClearTypeGridFit
};

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg);
saveOptions.GraphicsQualityOptions = qualityOptions;

doc.Save(ArtifactsDir + "SaveOptions.QualityOptions.jpeg", saveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

GraphicsQualityOptions Members | Aspose.Words.Saving Namespace


GraphicsQualityOptions Members

GraphicsQualityOptions overview

Public Instance Constructors

GraphicsQualityOptions Constructor Initializes a new instance of the GraphicsQualityOptions class.

Public Instance Properties

CompositingMode | Gets or sets a value that specifies how composited images are drawn to this Graphics.
CompositingQuality | Gets or sets the rendering quality of composited images drawn to this Graphics.
InterpolationMode | Gets or sets the interpolation mode associated with this Graphics.
SmoothingMode | Gets or sets the rendering quality for this Graphics.
StringFormat | Gets or sets text layout information (such as alignment, orientation and tab stops) display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features.
TextRenderingHint | Gets or sets the rendering mode for text associated with this Graphics.

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


GraphicsQualityOptions Constructor

Initializes a new instance of the GraphicsQualityOptions class.

[Visual Basic]
Public Sub New()
[C#]
public GraphicsQualityOptions();

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


GraphicsQualityOptions Properties

The properties of the GraphicsQualityOptions class are listed below. For a complete list of GraphicsQualityOptions class members, see the GraphicsQualityOptions Members topic.

Public Instance Properties

CompositingMode | Gets or sets a value that specifies how composited images are drawn to this Graphics.
CompositingQuality | Gets or sets the rendering quality of composited images drawn to this Graphics.
InterpolationMode | Gets or sets the interpolation mode associated with this Graphics.
SmoothingMode | Gets or sets the rendering quality for this Graphics.
StringFormat | Gets or sets text layout information (such as alignment, orientation and tab stops) display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features.
TextRenderingHint | Gets or sets the rendering mode for text associated with this Graphics.

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


CompositingMode Property

Aspose.Words

GraphicsQualityOptions.CompositingMode Property

Gets or sets a value that specifies how composited images are drawn to this Graphics.

[Visual Basic]
Public Property CompositingMode As CompositingMode}
[C#]
public CompositingMode} CompositingMode {get; set;}

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


CompositingQuality Property

Aspose.Words

GraphicsQualityOptions.CompositingQuality Property

Gets or sets the rendering quality of composited images drawn to this Graphics.

[Visual Basic]
Public Property CompositingQuality As CompositingQuality}
[C#]
public CompositingQuality} CompositingQuality {get; set;}

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


InterpolationMode Property

Aspose.Words

GraphicsQualityOptions.InterpolationMode Property

Gets or sets the interpolation mode associated with this Graphics.

[Visual Basic]
Public Property InterpolationMode As InterpolationMode}
[C#]
public InterpolationMode} InterpolationMode {get; set;}

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


SmoothingMode Property

Aspose.Words

GraphicsQualityOptions.SmoothingMode Property

Gets or sets the rendering quality for this Graphics.

[Visual Basic]
Public Property SmoothingMode As SmoothingMode}
[C#]
public SmoothingMode} SmoothingMode {get; set;}

Example

Shows how to set render quality options.

[C#]

Document doc = new Document(MyDir + "SaveOptions.MyraidPro.docx");

GraphicsQualityOptions qualityOptions = new GraphicsQualityOptions
{
    SmoothingMode = SmoothingMode.AntiAlias,
    TextRenderingHint = TextRenderingHint.ClearTypeGridFit
};

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg);
saveOptions.GraphicsQualityOptions = qualityOptions;

doc.Save(ArtifactsDir + "SaveOptions.QualityOptions.jpeg", saveOptions);

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


StringFormat Property

Aspose.Words

GraphicsQualityOptions.StringFormat Property

Gets or sets text layout information (such as alignment, orientation and tab stops) display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features.

[Visual Basic]
Public Property StringFormat As StringFormat
[C#]
public StringFormat StringFormat {get; set;}

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


TextRenderingHint Property

Aspose.Words

GraphicsQualityOptions.TextRenderingHint Property

Gets or sets the rendering mode for text associated with this Graphics.

[Visual Basic]
Public Property TextRenderingHint As TextRenderingHint}
[C#]
public TextRenderingHint} TextRenderingHint {get; set;}

Example

Shows how to set render quality options.

[C#]

Document doc = new Document(MyDir + "SaveOptions.MyraidPro.docx");

GraphicsQualityOptions qualityOptions = new GraphicsQualityOptions
{
    SmoothingMode = SmoothingMode.AntiAlias,
    TextRenderingHint = TextRenderingHint.ClearTypeGridFit
};

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg);
saveOptions.GraphicsQualityOptions = qualityOptions;

doc.Save(ArtifactsDir + "SaveOptions.QualityOptions.jpeg", saveOptions);

See Also

GraphicsQualityOptions Class | Aspose.Words.Saving Namespace


HeaderFooterBookmarksExportMode Enumeration

Specifies how bookmarks in headers/footers are exported.

[Visual Basic]
Public Enum HeaderFooterBookmarksExportMode
[C#]
public enum HeaderFooterBookmarksExportMode

Example

Shows how bookmarks in headers/footers are exported to pdf

[C#]

Document doc = new Document(MyDir + "PdfSaveOption.HeaderFooterBookmarksExportMode.docx");

// You can specify how bookmarks in headers/footers are exported.
// There is a several options for this:
// "None" - Bookmarks in headers/footers are not exported.
// "First" - Only bookmark in first header/footer of the section is exported.
// "All" - Bookmarks in all headers/footers are exported.
PdfSaveOptions saveOptions = new PdfSaveOptions
{
    HeaderFooterBookmarksExportMode = headerFooterBookmarksExportMode,
    OutlineOptions = { DefaultBookmarksOutlineLevel = 1 }
};
doc.Save(ArtifactsDir + "PdfSaveOption.HeaderFooterBookmarksExportMode.pdf", saveOptions);

Members

Member Name | Description | Value
None | Bookmarks in headers/footers are not exported. | 0
First | Only bookmark in first header/footer of the section is exported. | 1
All | Bookmarks in all headers/footers are exported. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


HtmlElementSizeOutputMode Enumeration

Specifies how Aspose.Words exports element widths and heights to HTML, MHTML and EPUB.

[Visual Basic]
Public Enum HtmlElementSizeOutputMode
[C#]
public enum HtmlElementSizeOutputMode

Remarks

Members

Member Name | Description | Value
All | All element sizes, both in absolute and relative units, specified in the document are exported. | 0
RelativeOnly | Element sizes are exported only if they are specified in relative units in the document. Fixed sizes are not exported in this mode. Visual agents will calculate missing sizes to make document layout more natural. | 1
None | Element sizes are not exported. Visual agents will build layout automatically according to relationship between elements. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace | TableWidthOutputMode


HtmlFixedPageHorizontalAlignment Enumeration

Specifies the horizontal alignment for pages in output HTML document.

[Visual Basic]
Public Enum HtmlFixedPageHorizontalAlignment
[C#]
public enum HtmlFixedPageHorizontalAlignment

Example

Shows how to set the horizontal alignment of pages in HTML file.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    PageHorizontalAlignment = HtmlFixedPageHorizontalAlignment.Left
};

doc.Save(ArtifactsDir + "HtmlFixedPageHorizontalAlignment.html", htmlFixedSaveOptions);

Members

Member Name | Description | Value
Left | Align pages to the left. | 0
Center | Center pages. This is the default value. | 1
Right | Align pages to the right. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


HtmlFixedSaveOptions Class

Can be used to specify additional options when saving a document into the HtmlFixed format.

For a list of all members of this type, see HtmlFixedSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.HtmlFixedSaveOptions

[Visual Basic]
Public Class HtmlFixedSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class HtmlFixedSaveOptions : FixedPageSaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

HtmlFixedSaveOptions Members | Aspose.Words.Saving Namespace


HtmlFixedSaveOptions Members

HtmlFixedSaveOptions overview

Public Instance Constructors

HtmlFixedSaveOptions Constructor Initializes a new instance of the HtmlFixedSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
CssClassNamesPrefix | Specifies prefix which is added to all class names in style.css file. Default value is "aw".
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
Encoding | Specifies the encoding to use when exporting to HTML. Default value is new UTF8Encoding(true) (UTF-8 with BOM).
ExportEmbeddedCss | Specifies whether the CSS (Cascading Style Sheet) should be embedded into Html document.
ExportEmbeddedFonts | Specifies whether fonts should be embedded into Html document in Base64 format. Note setting this flag can significantly increase size of output Html file.
ExportEmbeddedImages | Specifies whether images should be embedded into Html document in Base64 format. Note setting this flag can significantly increase size of output Html file.
ExportEmbeddedSvg | Specifies whether SVG resources should be embedded into Html document. Default value is true.
ExportFormFields | Gets or sets indication of whether form fields are exported as interactive items (as 'input' tag) rather than converted to text or graphics.
FontFormat | Gets or sets ExportFontFormat used for font exporting. Default value is Woff.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formating are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is true.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageHorizontalAlignment | Specifies the horizontal alignment of pages in an HTML document. Default value is HtmlFixedHorizontalPageAlignment.Center.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageMargins | Specifies the margins around pages in an HTML document. The margins value is measured in points and should be equal to or greater than 0. Default value is 10 points.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResourceSavingCallback | Allows to control how resources (images, fonts and css) are saved when a document is exported to fixed page Html format.
ResourcesFolder | Specifies the physical folder where resources (images, fonts, css) are saved when exporting a document to Html format. Default is null.
ResourcesFolderAlias | Specifies the name of the folder used to construct image URIs written into an Html document. Default is null.
SaveFontFaceCssSeparately | Flag indicates whether "@font-face" CSS rules should be placed into a separate file "fontFaces.css" when a document is being saved with external stylesheet (that is, when ExportEmbeddedCss is false). Default value is false, all CSS rules are written into single file "styles.css".
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be HtmlFixed.
ShowPageBorder | Specifies whether border around pages should be shown. Default is true.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
UseTargetMachineFonts | Flag indicates whether fonts from target machine must be used to display the document. If this flag is set to true, FontFormat and ExportEmbeddedFonts properties do not have effect, also ResourceSavingCallback is not fired for fonts. Default is false.

Public Instance Methods

Equals (inherited from FixedPageSaveOptions)

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


HtmlFixedSaveOptions Constructor

Initializes a new instance of the HtmlFixedSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public HtmlFixedSaveOptions();

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


HtmlFixedSaveOptions Properties

The properties of the HtmlFixedSaveOptions class are listed below. For a complete list of HtmlFixedSaveOptions class members, see the HtmlFixedSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
CssClassNamesPrefix | Specifies prefix which is added to all class names in style.css file. Default value is "aw".
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
Encoding | Specifies the encoding to use when exporting to HTML. Default value is new UTF8Encoding(true) (UTF-8 with BOM).
ExportEmbeddedCss | Specifies whether the CSS (Cascading Style Sheet) should be embedded into Html document.
ExportEmbeddedFonts | Specifies whether fonts should be embedded into Html document in Base64 format. Note setting this flag can significantly increase size of output Html file.
ExportEmbeddedImages | Specifies whether images should be embedded into Html document in Base64 format. Note setting this flag can significantly increase size of output Html file.
ExportEmbeddedSvg | Specifies whether SVG resources should be embedded into Html document. Default value is true.
ExportFormFields | Gets or sets indication of whether form fields are exported as interactive items (as 'input' tag) rather than converted to text or graphics.
FontFormat | Gets or sets ExportFontFormat used for font exporting. Default value is Woff.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formating are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is true.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageHorizontalAlignment | Specifies the horizontal alignment of pages in an HTML document. Default value is HtmlFixedHorizontalPageAlignment.Center.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageMargins | Specifies the margins around pages in an HTML document. The margins value is measured in points and should be equal to or greater than 0. Default value is 10 points.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResourceSavingCallback | Allows to control how resources (images, fonts and css) are saved when a document is exported to fixed page Html format.
ResourcesFolder | Specifies the physical folder where resources (images, fonts, css) are saved when exporting a document to Html format. Default is null.
ResourcesFolderAlias | Specifies the name of the folder used to construct image URIs written into an Html document. Default is null.
SaveFontFaceCssSeparately | Flag indicates whether "@font-face" CSS rules should be placed into a separate file "fontFaces.css" when a document is being saved with external stylesheet (that is, when ExportEmbeddedCss is false). Default value is false, all CSS rules are written into single file "styles.css".
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be HtmlFixed.
ShowPageBorder | Specifies whether border around pages should be shown. Default is true.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
UseTargetMachineFonts | Flag indicates whether fonts from target machine must be used to display the document. If this flag is set to true, FontFormat and ExportEmbeddedFonts properties do not have effect, also ResourceSavingCallback is not fired for fonts. Default is false.

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


CssClassNamesPrefix Property

Aspose.Words

HtmlFixedSaveOptions.CssClassNamesPrefix Property

Specifies prefix which is added to all class names in style.css file. Default value is "aw".

[Visual Basic]
Public Property CssClassNamesPrefix As String
[C#]
public string CssClassNamesPrefix {get; set;}

Example

Shows how to add prefix to all class names in css file.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    CssClassNamesPrefix = "test",
    SaveFontFaceCssSeparately = true
};

doc.Save(ArtifactsDir + "cssPrefix_Out.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


Encoding Property

Aspose.Words

HtmlFixedSaveOptions.Encoding Property

Specifies the encoding to use when exporting to HTML. Default value is new UTF8Encoding(true) (UTF-8 with BOM).

[Visual Basic]
Public Property Encoding As Encoding
[C#]
public Encoding Encoding {get; set;}

Example

Shows how to set encoding while exporting to HTML.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Writeln("Hello World!");

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    Encoding = new ASCIIEncoding()
};

doc.Save(ArtifactsDir + "UseEncoding.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ExportEmbeddedCss Property

Aspose.Words

HtmlFixedSaveOptions.ExportEmbeddedCss Property

Specifies whether the CSS (Cascading Style Sheet) should be embedded into Html document.

[Visual Basic]
Public Property ExportEmbeddedCss As Boolean
[C#]
public bool ExportEmbeddedCss {get; set;}

Example

Shows how to export embedded objects into HTML file.

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    ExportEmbeddedCss = true,
    ExportEmbeddedFonts = true,
    ExportEmbeddedImages = true,
    ExportEmbeddedSvg = true
};

doc.Save(ArtifactsDir + "ExportEmbeddedObjects.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ExportEmbeddedFonts Property

Aspose.Words

HtmlFixedSaveOptions.ExportEmbeddedFonts Property

Specifies whether fonts should be embedded into Html document in Base64 format. Note setting this flag can significantly increase size of output Html file.

[Visual Basic]
Public Property ExportEmbeddedFonts As Boolean
[C#]
public bool ExportEmbeddedFonts {get; set;}

Example

Shows how to export embedded objects into HTML file.

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    ExportEmbeddedCss = true,
    ExportEmbeddedFonts = true,
    ExportEmbeddedImages = true,
    ExportEmbeddedSvg = true
};

doc.Save(ArtifactsDir + "ExportEmbeddedObjects.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ExportEmbeddedImages Property

Aspose.Words

HtmlFixedSaveOptions.ExportEmbeddedImages Property

Specifies whether images should be embedded into Html document in Base64 format. Note setting this flag can significantly increase size of output Html file.

[Visual Basic]
Public Property ExportEmbeddedImages As Boolean
[C#]
public bool ExportEmbeddedImages {get; set;}

Example

Shows how to export embedded objects into HTML file.

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    ExportEmbeddedCss = true,
    ExportEmbeddedFonts = true,
    ExportEmbeddedImages = true,
    ExportEmbeddedSvg = true
};

doc.Save(ArtifactsDir + "ExportEmbeddedObjects.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ExportEmbeddedSvg Property

Aspose.Words

HtmlFixedSaveOptions.ExportEmbeddedSvg Property

Specifies whether SVG resources should be embedded into Html document. Default value is true.

[Visual Basic]
Public Property ExportEmbeddedSvg As Boolean
[C#]
public bool ExportEmbeddedSvg {get; set;}

Example

Shows how to export embedded objects into HTML file.

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    ExportEmbeddedCss = true,
    ExportEmbeddedFonts = true,
    ExportEmbeddedImages = true,
    ExportEmbeddedSvg = true
};

doc.Save(ArtifactsDir + "ExportEmbeddedObjects.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ExportFormFields Property

Aspose.Words

HtmlFixedSaveOptions.ExportFormFields Property

Gets or sets indication of whether form fields are exported as interactive items (as 'input' tag) rather than converted to text or graphics.

[Visual Basic]
Public Property ExportFormFields As Boolean
[C#]
public bool ExportFormFields {get; set;}

Example

Show how to exporting form fields from a document into HTML file.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCheckBox("CheckBox", false, 15);

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    ExportFormFields = true
};

doc.Save(ArtifactsDir + "ExportFormFields.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


FontFormat Property

Aspose.Words

HtmlFixedSaveOptions.FontFormat Property

Gets or sets ExportFontFormat used for font exporting. Default value is Woff.

[Visual Basic]
Public Property FontFormat As ExportFontFormat
[C#]
public ExportFontFormat FontFormat {get; set;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


OptimizeOutput Property

Aspose.Words

HtmlFixedSaveOptions.OptimizeOutput Property

Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formating are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is true.

[Visual Basic]
Overrides Public Property OptimizeOutput As Boolean
[C#]
public override bool OptimizeOutput {get; set;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


PageHorizontalAlignment Property

Aspose.Words

HtmlFixedSaveOptions.PageHorizontalAlignment Property

Specifies the horizontal alignment of pages in an HTML document. Default value is HtmlFixedHorizontalPageAlignment.Center.

[Visual Basic]
Public Property PageHorizontalAlignment As HtmlFixedPageHorizontalAlignment
[C#]
public HtmlFixedPageHorizontalAlignment PageHorizontalAlignment {get; set;}

Example

Shows how to set the horizontal alignment of pages in HTML file.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    PageHorizontalAlignment = HtmlFixedPageHorizontalAlignment.Left
};

doc.Save(ArtifactsDir + "HtmlFixedPageHorizontalAlignment.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


PageMargins Property

Aspose.Words

HtmlFixedSaveOptions.PageMargins Property

Specifies the margins around pages in an HTML document. The margins value is measured in points and should be equal to or greater than 0. Default value is 10 points.

[Visual Basic]
Public Property PageMargins As Double
[C#]
public double PageMargins {get; set;}

Remarks

Depends on the value of PageHorizontalAlignment property:

  • Defines top, bottom and left page margins if the value is Left.
  • Defines top, bottom and right page margins if the value is Right.
  • Defines top and bottom page margins if the value is Center.

Example

Shows how to set the margins around pages in HTML file.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

HtmlFixedSaveOptions saveOptions = new HtmlFixedSaveOptions
{
    PageMargins = 10
};

doc.Save(ArtifactsDir + "HtmlFixedPageMargins.html", saveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ResourceSavingCallback Property

Aspose.Words

HtmlFixedSaveOptions.ResourceSavingCallback Property

Allows to control how resources (images, fonts and css) are saved when a document is exported to fixed page Html format.

[Visual Basic]
Public Property ResourceSavingCallback As IResourceSavingCallback
[C#]
public IResourceSavingCallback ResourceSavingCallback {get; set;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ResourcesFolder Property

Aspose.Words

HtmlFixedSaveOptions.ResourcesFolder Property

Specifies the physical folder where resources (images, fonts, css) are saved when exporting a document to Html format. Default is null.

[Visual Basic]
Public Property ResourcesFolder As String
[C#]
public string ResourcesFolder {get; set;}

Remarks

Has effect only if ExportEmbeddedImages property is false.

When you save a Document in Html format, Aspose.Words needs to save all images embedded in the document as standalone files. ResourcesFolder allows you to specify where the images will be saved and ResourcesFolderAlias allows to specify how the image URIs will be constructed.

If you save a document into a file and provide a file name, Aspose.Words, by default, saves the images in the same folder where the document file is saved. Use ResourcesFolder to override this behavior.

If you save a document into a stream, Aspose.Words does not have a folder where to save the images, but still needs to save the images somewhere. In this case, you need to specify an accessible folder by using the ResourcesFolder property

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace | ResourcesFolderAlias


ResourcesFolderAlias Property

Aspose.Words

HtmlFixedSaveOptions.ResourcesFolderAlias Property

Specifies the name of the folder used to construct image URIs written into an Html document. Default is null.

[Visual Basic]
Public Property ResourcesFolderAlias As String
[C#]
public string ResourcesFolderAlias {get; set;}

Remarks

When you save a Document in Html format, Aspose.Words needs to save all images embedded in the document as standalone files. ResourcesFolder allows you to specify where the images will be saved and ResourcesFolderAlias allows to specify how the image URIs will be constructed.

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace | ResourcesFolder


SaveFontFaceCssSeparately Property

Aspose.Words

HtmlFixedSaveOptions.SaveFontFaceCssSeparately Property

Flag indicates whether "@font-face" CSS rules should be placed into a separate file "fontFaces.css" when a document is being saved with external stylesheet (that is, when ExportEmbeddedCss is false). Default value is false, all CSS rules are written into single file "styles.css".

[Visual Basic]
Public Property SaveFontFaceCssSeparately As Boolean
[C#]
public bool SaveFontFaceCssSeparately {get; set;}

Remarks

Setting this property to true restores the old behavior (separate files) for compatibility with legacy code.

Example

Shows how to add prefix to all class names in css file.

[C#]

Document doc = new Document(MyDir + "Bookmark.doc");

HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
{
    CssClassNamesPrefix = "test",
    SaveFontFaceCssSeparately = true
};

doc.Save(ArtifactsDir + "cssPrefix_Out.html", htmlFixedSaveOptions);

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

HtmlFixedSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be HtmlFixed.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ShowPageBorder Property

Aspose.Words

HtmlFixedSaveOptions.ShowPageBorder Property

Specifies whether border around pages should be shown. Default is true.

[Visual Basic]
Public Property ShowPageBorder As Boolean
[C#]
public bool ShowPageBorder {get; set;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


UseTargetMachineFonts Property

Aspose.Words

HtmlFixedSaveOptions.UseTargetMachineFonts Property

Flag indicates whether fonts from target machine must be used to display the document. If this flag is set to true, FontFormat and ExportEmbeddedFonts properties do not have effect, also ResourceSavingCallback is not fired for fonts. Default is false.

[Visual Basic]
Public Property UseTargetMachineFonts As Boolean
[C#]
public bool UseTargetMachineFonts {get; set;}

Example

Shows how used target machine fonts to display the document.

[C#]

public void UsingMachineFonts()
{
    Document doc = new Document(MyDir + "Font.DisappearingBulletPoints.doc");

    HtmlFixedSaveOptions saveOptions = new HtmlFixedSaveOptions
    {
        UseTargetMachineFonts = true,
        FontFormat = ExportFontFormat.Ttf,
        ExportEmbeddedFonts = false,
        ResourceSavingCallback = new ResourceSavingCallback()
    };

    doc.Save(ArtifactsDir + "UseMachineFonts.html", saveOptions);
}

private class ResourceSavingCallback : IResourceSavingCallback
{
    /// <summary>
    /// Called when Aspose.Words saves an external resource to fixed page HTML or SVG.
    /// </summary>
    public void ResourceSaving(ResourceSavingArgs args)
    {
        args.ResourceStream = new MemoryStream();
        args.KeepResourceStreamOpen = true;

        string extension = Path.GetExtension(args.ResourceFileName);
        switch (extension)
        {
            case ".ttf":
            case ".woff":
            {
                Assert.Fail(
                    "'ResourceSavingCallback' is not fired for fonts when 'UseTargetMachineFonts' is true");
                break;
            }
        }
    }
}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


HtmlMetafileFormat Enumeration

Indicates the format in which metafiles are saved to HTML documents.

[Visual Basic]
Public Enum HtmlMetafileFormat
[C#]
public enum HtmlMetafileFormat

Members

Member Name | Description | Value
Png | Metafiles are rendered to raster PNG images. | 0
Svg | Metafiles are converted to vector SVG images. | 1
EmfOrWmf | Metafiles are saved as is, without conversion. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


HtmlOfficeMathOutputMode Enumeration

Specifies how Aspose.Words exports OfficeMath to HTML, MHTML and EPUB.

[Visual Basic]
Public Enum HtmlOfficeMathOutputMode
[C#]
public enum HtmlOfficeMathOutputMode

Members

Member Name | Description | Value
Image | OfficeMath is converted to HTML as image specified by <img> tag. | 0
MathML | OfficeMath is converted to HTML using MathML. | 1
Text | OfficeMath is converted to HTML as sequence of runs specified by <span> tags. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


HtmlSaveOptions Class

Can be used to specify additional options when saving a document into the Html, Mhtml or Epub format.

For a list of all members of this type, see HtmlSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.HtmlSaveOptions

[Visual Basic]
Public Class HtmlSaveOptions
Inherits SaveOptions
[C#]
public class HtmlSaveOptions : SaveOptions

Example

Shows how to set save options before saving a document to HTML.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// This is the directory we want the exported images to be saved to.
String imagesDir = Path.Combine(ArtifactsDir, "SaveHtmlWithOptions");

// The folder specified needs to exist and should be empty.
if (Directory.Exists(imagesDir))
    Directory.Delete(imagesDir, true);

Directory.CreateDirectory(imagesDir);

// Set an option to export form fields as plain text, not as HTML input elements.
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
options.ExportTextInputFormFieldAsText = true;
options.ImagesFolder = imagesDir;

doc.Save(ArtifactsDir + "Document.SaveWithOptions.html", options);
Shows how to define custom logic for controlling how images are saved when exporting to HTML based formats.
[C#]

public void SaveHtmlExportImages()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Create and pass the object which implements the handler methods.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
    options.ImageSavingCallback = new HandleImageSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithCustomImagesExport.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (args.ImageFileName.EndsWith(".jpeg"))
            args.ImageFileName = args.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
Converts a document to EPUB with save options specified.
[C#]

// Open an existing document from disk.
Document doc = new Document(MyDir + "Document.EpubConversion.doc");

// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();

// Specify the desired encoding.
saveOptions.Encoding = Encoding.UTF8;

// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;

// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;

// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;

// Export the document as an EPUB file.
doc.Save(ArtifactsDir + "Document.EpubConversion.epub", saveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

HtmlSaveOptions Members | Aspose.Words.Saving Namespace


HtmlSaveOptions Members

HtmlSaveOptions overview

Public Instance Constructors

HtmlSaveOptions Overloaded. Initializes a new instance of the HtmlSaveOptions class.

Public Instance Properties

AllowNegativeIndent | Specifies whether negative left and right indents of paragraphs are normalized when saving to HTML, MHTML or EPUB. Default value is false.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
CssClassNamePrefix | Specifies a prefix which is added to all CSS class names. Default value is an empty string and generated CSS class names have no common prefix.
CssSavingCallback | Allows to control how CSS styles are saved when a document is saved to HTML, MHTML or EPUB.
CssStyleSheetFileName | Specifies the path and the name of the Cascading Style Sheet (CSS) file written when a document is exported to HTML. Default is an empty string.
CssStyleSheetType | Specifies how CSS (Cascading Style Sheet) styles are exported to HTML, MHTML or EPUB. Default value is Inline for HTML/MHTML and External for EPUB.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
DocumentPartSavingCallback | Allows to control how document parts are saved when a document is saved to HTML or EPUB.
DocumentSplitCriteria | Specifies how the document should be split when saving to Html or Epub format. Default is None for HTML and HeadingParagraph for EPUB.
DocumentSplitHeadingLevel | Specifies the maximum level of headings at which to split the document. Default value is 2.
Encoding | Specifies the encoding to use when exporting to HTML, MHTML or EPUB. Default value is new UTF8Encoding(false) (UTF-8 without BOM).
EpubNavigationMapLevel | Specifies the maximum level of headings populated to the navigation map when exporting to IDPF EPUB format. Default value is 3.
ExportCidUrlsForMhtmlResources | Specifies whether to use CID (Content-ID) URLs to reference resources (images, fonts, CSS) included in MHTML documents. Default value is false.
ExportDocumentProperties | Specifies whether to export built-in and custom document properties to HTML, MHTML or EPUB. Default value is false.
ExportDropDownFormFieldAsText | Controls how drop-down form fields are saved to HTML or MHTML. Default value is false.
ExportFontResources | Specifies whether font resources should be exported to HTML, MHTML or EPUB. Default is false.
ExportFontsAsBase64 | Specifies whether fonts resources should be embedded to HTML in Base64 encoding. Default is false.
ExportHeadersFootersMode | Specifies how headers and footers are output to HTML, MHTML or EPUB. Default value is PerSection for HTML/MHTML and None for EPUB.
ExportImagesAsBase64 | Specifies whether images are saved in Base64 format to HTML, MHTML or EPUB. Default is false.
ExportLanguageInformation | Specifies whether language information is exported to HTML, MHTML or EPUB. Default is false.
ExportListLabels | Controls how list labels are output to HTML, MHTML or EPUB. Default value is Auto.
ExportOriginalUrlForLinkedImages | Specifies whether original URL should be used as the URL of the linked images. Default value is false.
ExportPageMargins | Specifies whether page margins is exported to HTML, MHTML or EPUB. Default is false.
ExportPageSetup | Specifies whether page setup is exported to HTML, MHTML or EPUB. Default is false.
ExportRelativeFontSize | Specifies whether font sizes should be output in relative units when saving to HTML, MHTML or EPUB. Default is false.
ExportRoundtripInformation | Specifies whether to write the roundtrip information when saving to HTML, MHTML or EPUB. Default value is true for HTML and false for MHTML and EPUB.
ExportTextBoxAsSvg | Controls how textboxes represented by Shape are saved to HTML, MHTML or EPUB. Default value is false.
ExportTextInputFormFieldAsText | Controls how text input form fields are saved to HTML or MHTML. Default value is false.
ExportTocPageNumbers | Specifies whether to write page numbers to table of contents when saving HTML, MHTML and EPUB. Default value is false.
ExportXhtmlTransitional | Specifies whether to write the DOCTYPE declaration when saving to HTML or MHTML. When true, writes a DOCTYPE declaration in the document prior to the root element. Default value is false. When saving to EPUB or HTML5 (Html5) the DOCTYPE declaration is always written.
FontResourcesSubsettingSizeThreshold | Controls which font resources need subsetting when saving to HTML, MHTML or EPUB. Default is 0.
FontSavingCallback | Allows to control how fonts are saved when a document is saved to HTML, MHTML or EPUB.
FontsFolder | Specifies the physical folder where fonts are saved when exporting a document to HTML. Default is an empty string.
FontsFolderAlias | Specifies the name of the folder used to construct font URIs written into an HTML document. Default is an empty string.
HtmlVersion | Specifies version of HTML standard that should be used when saving the document to HTML or MHTML. Default value is Xhtml.
ImageResolution | Specifies the output resolution for images when exporting to HTML, MHTML or EPUB. Default is 96 dpi.
ImageSavingCallback | Allows to control how images are saved when a document is saved to HTML, MHTML or EPUB.
ImagesFolder | Specifies the physical folder where images are saved when exporting a document to HTML format. Default is an empty string.
ImagesFolderAlias | Specifies the name of the folder used to construct image URIs written into an HTML document. Default is an empty string.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileFormat | Specifies in what format metafiles are saved when exporting to HTML, MHTML, or EPUB. Default value is Png, meaning that metafiles are rendered to raster PNG images.
OfficeMathOutputMode | Controls how OfficeMath objects are exported to HTML, MHTML or EPUB. Default value is HtmlOfficeMathOutputMode.Image.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResolveFontNames | Specifies whether font family names used in the document are resolved and substituted according to FontSettings when being written into HTML-based formats.
ResourceFolder | Specifies a physical folder where all resources like images, fonts, and external CSS are saved when a document is exported to HTML. Default is an empty string.
ResourceFolderAlias | Specifies the name of the folder used to construct URIs of all resources written into an HTML document. Default is an empty string.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Html, Mhtml or Epub.
ScaleImageToShapeSize | Specifies whether images are scaled by Aspose.Words to the bounding shape size when exporting to HTML, MHTML or EPUB. Default value is true.
TableWidthOutputMode | Controls how table, row and cell widths are exported to HTML, MHTML or EPUB. Default value is All.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


HtmlSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Html format.

Overload List

Initializes a new instance of this class that can be used to save a document in the Html format.

public HtmlSaveOptions();

Initializes a new instance of this class that can be used to save a document in the Html, Mhtml or Epub format.

public HtmlSaveOptions(SaveFormat);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


HtmlSaveOptions Constructor ()

Initializes a new instance of this class that can be used to save a document in the Html format.

[Visual Basic]
Overloads Public Sub New()
[C#]
public HtmlSaveOptions();

Example

Converts a document to EPUB with save options specified.

[C#]

// Open an existing document from disk.
Document doc = new Document(MyDir + "Document.EpubConversion.doc");

// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();

// Specify the desired encoding.
saveOptions.Encoding = Encoding.UTF8;

// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;

// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;

// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;

// Export the document as an EPUB file.
doc.Save(ArtifactsDir + "Document.EpubConversion.epub", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | HtmlSaveOptions Constructor Overload List


HtmlSaveOptions Constructor (SaveFormat)

Initializes a new instance of this class that can be used to save a document in the Html, Mhtml or Epub format.

[Visual Basic]
Overloads Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public HtmlSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be Html, Mhtml or Epub.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | HtmlSaveOptions Constructor Overload List


HtmlSaveOptions Properties

The properties of the HtmlSaveOptions class are listed below. For a complete list of HtmlSaveOptions class members, see the HtmlSaveOptions Members topic.

Public Instance Properties

AllowNegativeIndent | Specifies whether negative left and right indents of paragraphs are normalized when saving to HTML, MHTML or EPUB. Default value is false.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
CssClassNamePrefix | Specifies a prefix which is added to all CSS class names. Default value is an empty string and generated CSS class names have no common prefix.
CssSavingCallback | Allows to control how CSS styles are saved when a document is saved to HTML, MHTML or EPUB.
CssStyleSheetFileName | Specifies the path and the name of the Cascading Style Sheet (CSS) file written when a document is exported to HTML. Default is an empty string.
CssStyleSheetType | Specifies how CSS (Cascading Style Sheet) styles are exported to HTML, MHTML or EPUB. Default value is Inline for HTML/MHTML and External for EPUB.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
DocumentPartSavingCallback | Allows to control how document parts are saved when a document is saved to HTML or EPUB.
DocumentSplitCriteria | Specifies how the document should be split when saving to Html or Epub format. Default is None for HTML and HeadingParagraph for EPUB.
DocumentSplitHeadingLevel | Specifies the maximum level of headings at which to split the document. Default value is 2.
Encoding | Specifies the encoding to use when exporting to HTML, MHTML or EPUB. Default value is new UTF8Encoding(false) (UTF-8 without BOM).
EpubNavigationMapLevel | Specifies the maximum level of headings populated to the navigation map when exporting to IDPF EPUB format. Default value is 3.
ExportCidUrlsForMhtmlResources | Specifies whether to use CID (Content-ID) URLs to reference resources (images, fonts, CSS) included in MHTML documents. Default value is false.
ExportDocumentProperties | Specifies whether to export built-in and custom document properties to HTML, MHTML or EPUB. Default value is false.
ExportDropDownFormFieldAsText | Controls how drop-down form fields are saved to HTML or MHTML. Default value is false.
ExportFontResources | Specifies whether font resources should be exported to HTML, MHTML or EPUB. Default is false.
ExportFontsAsBase64 | Specifies whether fonts resources should be embedded to HTML in Base64 encoding. Default is false.
ExportHeadersFootersMode | Specifies how headers and footers are output to HTML, MHTML or EPUB. Default value is PerSection for HTML/MHTML and None for EPUB.
ExportImagesAsBase64 | Specifies whether images are saved in Base64 format to HTML, MHTML or EPUB. Default is false.
ExportLanguageInformation | Specifies whether language information is exported to HTML, MHTML or EPUB. Default is false.
ExportListLabels | Controls how list labels are output to HTML, MHTML or EPUB. Default value is Auto.
ExportOriginalUrlForLinkedImages | Specifies whether original URL should be used as the URL of the linked images. Default value is false.
ExportPageMargins | Specifies whether page margins is exported to HTML, MHTML or EPUB. Default is false.
ExportPageSetup | Specifies whether page setup is exported to HTML, MHTML or EPUB. Default is false.
ExportRelativeFontSize | Specifies whether font sizes should be output in relative units when saving to HTML, MHTML or EPUB. Default is false.
ExportRoundtripInformation | Specifies whether to write the roundtrip information when saving to HTML, MHTML or EPUB. Default value is true for HTML and false for MHTML and EPUB.
ExportTextBoxAsSvg | Controls how textboxes represented by Shape are saved to HTML, MHTML or EPUB. Default value is false.
ExportTextInputFormFieldAsText | Controls how text input form fields are saved to HTML or MHTML. Default value is false.
ExportTocPageNumbers | Specifies whether to write page numbers to table of contents when saving HTML, MHTML and EPUB. Default value is false.
ExportXhtmlTransitional | Specifies whether to write the DOCTYPE declaration when saving to HTML or MHTML. When true, writes a DOCTYPE declaration in the document prior to the root element. Default value is false. When saving to EPUB or HTML5 (Html5) the DOCTYPE declaration is always written.
FontResourcesSubsettingSizeThreshold | Controls which font resources need subsetting when saving to HTML, MHTML or EPUB. Default is 0.
FontSavingCallback | Allows to control how fonts are saved when a document is saved to HTML, MHTML or EPUB.
FontsFolder | Specifies the physical folder where fonts are saved when exporting a document to HTML. Default is an empty string.
FontsFolderAlias | Specifies the name of the folder used to construct font URIs written into an HTML document. Default is an empty string.
HtmlVersion | Specifies version of HTML standard that should be used when saving the document to HTML or MHTML. Default value is Xhtml.
ImageResolution | Specifies the output resolution for images when exporting to HTML, MHTML or EPUB. Default is 96 dpi.
ImageSavingCallback | Allows to control how images are saved when a document is saved to HTML, MHTML or EPUB.
ImagesFolder | Specifies the physical folder where images are saved when exporting a document to HTML format. Default is an empty string.
ImagesFolderAlias | Specifies the name of the folder used to construct image URIs written into an HTML document. Default is an empty string.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileFormat | Specifies in what format metafiles are saved when exporting to HTML, MHTML, or EPUB. Default value is Png, meaning that metafiles are rendered to raster PNG images.
OfficeMathOutputMode | Controls how OfficeMath objects are exported to HTML, MHTML or EPUB. Default value is HtmlOfficeMathOutputMode.Image.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResolveFontNames | Specifies whether font family names used in the document are resolved and substituted according to FontSettings when being written into HTML-based formats.
ResourceFolder | Specifies a physical folder where all resources like images, fonts, and external CSS are saved when a document is exported to HTML. Default is an empty string.
ResourceFolderAlias | Specifies the name of the folder used to construct URIs of all resources written into an HTML document. Default is an empty string.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Html, Mhtml or Epub.
ScaleImageToShapeSize | Specifies whether images are scaled by Aspose.Words to the bounding shape size when exporting to HTML, MHTML or EPUB. Default value is true.
TableWidthOutputMode | Controls how table, row and cell widths are exported to HTML, MHTML or EPUB. Default value is All.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


AllowNegativeIndent Property

Aspose.Words

HtmlSaveOptions.AllowNegativeIndent Property

Specifies whether negative left and right indents of paragraphs are normalized when saving to HTML, MHTML or EPUB. Default value is false.

[Visual Basic]
Public Property AllowNegativeIndent As Boolean
[C#]
public bool AllowNegativeIndent {get; set;}

Remarks

When negative indent is not allowed, it is exported as zero margin to HTML. When negative indent is allowed, a paragraph might appear partially outside of the browser window.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


CssClassNamePrefix Property

Aspose.Words

HtmlSaveOptions.CssClassNamePrefix Property

Specifies a prefix which is added to all CSS class names. Default value is an empty string and generated CSS class names have no common prefix.

[Visual Basic]
Public Property CssClassNamePrefix As String
[C#]
public string CssClassNamePrefix {get; set;}

Remarks

If this value is not empty, all CSS classes generated by Aspose.Words will start with the specified prefix. This might be useful, for example, if you add custom CSS to generated documents and want to prevent class name conflicts.

If the value is not null or empty, it must be a valid CSS identifier.

Exceptions

Exception Type | Condition
ArgumentException | The value is not empty and is not a valid CSS identifier.

Example

Shows how to specifies a prefix which is added to all CSS class names

[C#]

Document doc = new Document(MyDir + "HtmlSaveOptions.CssClassNamePrefix.docx");

HtmlSaveOptions saveOptions = new HtmlSaveOptions
{
    CssStyleSheetType = CssStyleSheetType.Embedded,
    CssClassNamePrefix = "aspose-"
};

doc.Save(ArtifactsDir + "HtmlSaveOptions.CssClassNamePrefix.html", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


CssSavingCallback Property

Aspose.Words

HtmlSaveOptions.CssSavingCallback Property

Allows to control how CSS styles are saved when a document is saved to HTML, MHTML or EPUB.

[Visual Basic]
Public Property CssSavingCallback As ICssSavingCallback
[C#]
public ICssSavingCallback CssSavingCallback {get; set;}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


CssStyleSheetFileName Property

Aspose.Words

HtmlSaveOptions.CssStyleSheetFileName Property

Specifies the path and the name of the Cascading Style Sheet (CSS) file written when a document is exported to HTML. Default is an empty string.

[Visual Basic]
Public Property CssStyleSheetFileName As String
[C#]
public string CssStyleSheetFileName {get; set;}

Remarks

This property has effect only when saving a document to HTML format and external CSS style sheet is requested using CssStyleSheetType.

If this property is empty, the CSS file will be saved into the same folder and with the same name as the HTML document but with the ".css" extension.

If only path but no file name is specified in this property, the CSS file will be saved into the specified folder and will have the same name as the HTML document but with the ".css" extension.

If the folder specified by this property doesn't exist, it will be created automatically before the CSS file is saved.

Another way to specify a folder where external CSS file is saved is to use ResourceFolder.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ResourceFolder | ResourceFolderAlias | CssStyleSheetType


CssStyleSheetType Property

Aspose.Words

HtmlSaveOptions.CssStyleSheetType Property

Specifies how CSS (Cascading Style Sheet) styles are exported to HTML, MHTML or EPUB. Default value is Inline for HTML/MHTML and External for EPUB.

[Visual Basic]
Public Property CssStyleSheetType As CssStyleSheetType
[C#]
public CssStyleSheetType CssStyleSheetType {get; set;}

Remarks

Saving CSS style sheet into an external file is only supported when saving to HTML. When you are exporting to one of the container formats (EPUB or MHTML) and specifying External, CSS file will be encapsulated into the output package.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | CssStyleSheetFileName


DocumentPartSavingCallback Property

Aspose.Words

HtmlSaveOptions.DocumentPartSavingCallback Property

Allows to control how document parts are saved when a document is saved to HTML or EPUB.

[Visual Basic]
Public Property DocumentPartSavingCallback As IDocumentPartSavingCallback
[C#]
public IDocumentPartSavingCallback DocumentPartSavingCallback {get; set;}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


DocumentSplitCriteria Property

Aspose.Words

HtmlSaveOptions.DocumentSplitCriteria Property

Specifies how the document should be split when saving to Html or Epub format. Default is None for HTML and HeadingParagraph for EPUB.

[Visual Basic]
Public Property DocumentSplitCriteria As DocumentSplitCriteria
[C#]
public DocumentSplitCriteria DocumentSplitCriteria {get; set;}

Remarks

Normally you would want a document saved to HTML as a single file. But in some cases it is preferable to split the output into several smaller HTML pages. When saving to HTML format these pages will be output to individual files or streams. When saving to EPUB format they will be incorporated into corresponding packages.

A document cannot be split when saving in the MHTML format.

Example

Converts a document to EPUB with save options specified.

[C#]

// Open an existing document from disk.
Document doc = new Document(MyDir + "Document.EpubConversion.doc");

// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();

// Specify the desired encoding.
saveOptions.Encoding = Encoding.UTF8;

// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;

// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;

// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;

// Export the document as an EPUB file.
doc.Save(ArtifactsDir + "Document.EpubConversion.epub", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | DocumentSplitHeadingLevel | DocumentPartSavingCallback


DocumentSplitHeadingLevel Property

Aspose.Words

HtmlSaveOptions.DocumentSplitHeadingLevel Property

Specifies the maximum level of headings at which to split the document. Default value is 2.

[Visual Basic]
Public Property DocumentSplitHeadingLevel As Integer
[C#]
public int DocumentSplitHeadingLevel {get; set;}

Remarks

When DocumentSplitCriteria includes HeadingParagraph and this property is set to a value from 1 to 9, the document will be split at paragraphs formatted using Heading 1, Heading 2 , Heading 3 etc. styles up to the specified heading level.

By default, only Heading 1 and Heading 2 paragraphs cause the document to be split. Setting this property to zero will cause the document not to be split at heading paragraphs at all.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | DocumentSplitCriteria | DocumentPartSavingCallback


Encoding Property

Aspose.Words

HtmlSaveOptions.Encoding Property

Specifies the encoding to use when exporting to HTML, MHTML or EPUB. Default value is new UTF8Encoding(false) (UTF-8 without BOM).

[Visual Basic]
Public Property Encoding As Encoding
[C#]
public Encoding Encoding {get; set;}

Example

Converts a document to EPUB with save options specified.

[C#]

// Open an existing document from disk.
Document doc = new Document(MyDir + "Document.EpubConversion.doc");

// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();

// Specify the desired encoding.
saveOptions.Encoding = Encoding.UTF8;

// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;

// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;

// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;

// Export the document as an EPUB file.
doc.Save(ArtifactsDir + "Document.EpubConversion.epub", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


EpubNavigationMapLevel Property

Aspose.Words

HtmlSaveOptions.EpubNavigationMapLevel Property

Specifies the maximum level of headings populated to the navigation map when exporting to IDPF EPUB format. Default value is 3.

[Visual Basic]
Public Property EpubNavigationMapLevel As Integer
[C#]
public int EpubNavigationMapLevel {get; set;}

Remarks

Navigation map in IDPF EPUB format allows user agents to provide easy way of navigation through the document structure. Usually navigation points correspond to headings in the document. To populate headings up to level N assign this value to EpubNavigationMapLevel.

By default, three levels of headings are populated: paragraphs of styles Heading 1, Heading 2 and Heading 3. You can set this property to a value from 1 to 9 to request corresponding maximum level. Setting it to zero will reduce navigation map to only document root or roots of document parts.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportCidUrlsForMhtmlResources Property

Aspose.Words

HtmlSaveOptions.ExportCidUrlsForMhtmlResources Property

Specifies whether to use CID (Content-ID) URLs to reference resources (images, fonts, CSS) included in MHTML documents. Default value is false.

[Visual Basic]
Public Property ExportCidUrlsForMhtmlResources As Boolean
[C#]
public bool ExportCidUrlsForMhtmlResources {get; set;}

Remarks

This option affects only documents being saved to MHTML.

By default, resources in MHTML documents are referenced by file name (for example, "image.png"), which are matched against "Content-Location" headers of MIME parts.

This option enables an alternative method, where references to resource files are written as CID (Content-ID) URLs (for example, "cid:image.png") and are matched against "Content-ID" headers.

In theory, there should be no difference between the two referencing methods and either of them should work fine in any browser or mail agent. In practice, however, some agents fail to fetch resources by file name. If your browser or mail agent refuses to load resources included in an MTHML document (doesn't show images or doesn't load CSS styles), try exporting the document with CID URLs.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportDocumentProperties Property

Aspose.Words

HtmlSaveOptions.ExportDocumentProperties Property

Specifies whether to export built-in and custom document properties to HTML, MHTML or EPUB. Default value is false.

[Visual Basic]
Public Property ExportDocumentProperties As Boolean
[C#]
public bool ExportDocumentProperties {get; set;}

Example

Converts a document to EPUB with save options specified.

[C#]

// Open an existing document from disk.
Document doc = new Document(MyDir + "Document.EpubConversion.doc");

// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();

// Specify the desired encoding.
saveOptions.Encoding = Encoding.UTF8;

// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;

// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;

// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;

// Export the document as an EPUB file.
doc.Save(ArtifactsDir + "Document.EpubConversion.epub", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportDropDownFormFieldAsText Property

Aspose.Words

HtmlSaveOptions.ExportDropDownFormFieldAsText Property

Controls how drop-down form fields are saved to HTML or MHTML. Default value is false.

[Visual Basic]
Public Property ExportDropDownFormFieldAsText As Boolean
[C#]
public bool ExportDropDownFormFieldAsText {get; set;}

Remarks

When set to true, exports drop-down form fields as normal text. When false, exports drop-down form fields as SELECT element in HTML.

When exporting to EPUB, text drop-down form fields are always saved as text due to requirements of this format.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportFontResources Property

Aspose.Words

HtmlSaveOptions.ExportFontResources Property

Specifies whether font resources should be exported to HTML, MHTML or EPUB. Default is false.

[Visual Basic]
Public Property ExportFontResources As Boolean
[C#]
public bool ExportFontResources {get; set;}

Remarks

Exporting font resources allows for consistent document rendering independent of the fonts available in a given user's environment.

If ExportFontResources is set to true, main HTML document will refer to every font via the CSS 3 @font-face at-rule and fonts will be output as separate files. When exporting to IDPF EPUB or MHTML formats, fonts will be embedded into the corresponding package along with other subsidiary files.

If ExportFontsAsBase64 is set to true, fonts will not be saved to separate files. Instead, they will be embedded into @font-face at-rules in Base64 encoding.

Important! When exporting font resources, font licensing issues should be considered. Authors who want to use specific fonts via a downloadable font mechanism must always carefully verify that their intended use is within the scope of the font license. Many commercial fonts presently do not allow web downloading of their fonts in any form. License agreements that cover some fonts specifically note that usage via @font-face rules in CSS style sheets is not allowed. Font subsetting can also violate license terms.

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | FontResourcesSubsettingSizeThreshold


ExportFontsAsBase64 Property

Aspose.Words

HtmlSaveOptions.ExportFontsAsBase64 Property

Specifies whether fonts resources should be embedded to HTML in Base64 encoding. Default is false.

[Visual Basic]
Public Property ExportFontsAsBase64 As Boolean
[C#]
public bool ExportFontsAsBase64 {get; set;}

Remarks

By default, fonts are written to separate files. If this option is set to true, fonts will be embedded into the document's CSS in Base64 encoding.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportHeadersFootersMode Property

Aspose.Words

HtmlSaveOptions.ExportHeadersFootersMode Property

Specifies how headers and footers are output to HTML, MHTML or EPUB. Default value is PerSection for HTML/MHTML and None for EPUB.

[Visual Basic]
Public Property ExportHeadersFootersMode As ExportHeadersFootersMode
[C#]
public ExportHeadersFootersMode ExportHeadersFootersMode {get; set;}

Remarks

It is hard to meaningfully output headers and footers to HTML because HTML is not paginated.

When this property is PerSection, Aspose.Words exports only primary headers and footers at the beginning and the end of each section.

When it is FirstSectionHeaderLastSectionFooter only first primary header and the last primary footer (including linked to previous) are exported.

You can disable export of headers and footers altogether by setting this property to None.

Example

Demonstrates how to disable the export of headers and footers when saving to HTML based formats.

[C#]

Document doc = new Document(MyDir + "HeaderFooter.RemoveFooters.doc");

// Disables exporting headers and footers.
HtmlSaveOptions saveOptions =
    new HtmlSaveOptions(SaveFormat.Html) { ExportHeadersFootersMode = ExportHeadersFootersMode.None };

doc.Save(ArtifactsDir + "HeaderFooter.DisableHeadersFooters.html", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportImagesAsBase64 Property

Aspose.Words

HtmlSaveOptions.ExportImagesAsBase64 Property

Specifies whether images are saved in Base64 format to HTML, MHTML or EPUB. Default is false.

[Visual Basic]
Public Property ExportImagesAsBase64 As Boolean
[C#]
public bool ExportImagesAsBase64 {get; set;}

Remarks

When this property is set to true image data is exported directly on the img elements and separate files are not created.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportLanguageInformation Property

Aspose.Words

HtmlSaveOptions.ExportLanguageInformation Property

Specifies whether language information is exported to HTML, MHTML or EPUB. Default is false.

[Visual Basic]
Public Property ExportLanguageInformation As Boolean
[C#]
public bool ExportLanguageInformation {get; set;}

Remarks

When this property is set to true Aspose.Words outputs lang HTML attribute on the document elements that specify language. This can be needed to preserve language related semantics.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportListLabels Property

Aspose.Words

HtmlSaveOptions.ExportListLabels Property

Controls how list labels are output to HTML, MHTML or EPUB. Default value is Auto.

[Visual Basic]
Public Property ExportListLabels As ExportListLabels
[C#]
public ExportListLabels ExportListLabels {get; set;}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportOriginalUrlForLinkedImages Property

Aspose.Words

HtmlSaveOptions.ExportOriginalUrlForLinkedImages Property

Specifies whether original URL should be used as the URL of the linked images. Default value is false.

[Visual Basic]
Public Property ExportOriginalUrlForLinkedImages As Boolean
[C#]
public bool ExportOriginalUrlForLinkedImages {get; set;}

Remarks

If value is set to true SourceFullName value is used as the URL of linked images and linked images are not loaded into document's folder or ImagesFolder.

If value is set to false linked images are loaded into document's folder or ImagesFolder and URL of each linked image is constructed depending on document's folder, ImagesFolder and ImagesFolderAlias properties.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportPageMargins Property

Aspose.Words

HtmlSaveOptions.ExportPageMargins Property

Specifies whether page margins is exported to HTML, MHTML or EPUB. Default is false.

[Visual Basic]
Public Property ExportPageMargins As Boolean
[C#]
public bool ExportPageMargins {get; set;}

Remarks

Aspose.Words does not show area of page margins by default. If any elements are completely or partially clipped by the document edge the displayed area can be extended with this option.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportPageSetup Property

Aspose.Words

HtmlSaveOptions.ExportPageSetup Property

Specifies whether page setup is exported to HTML, MHTML or EPUB. Default is false.

[Visual Basic]
Public Property ExportPageSetup As Boolean
[C#]
public bool ExportPageSetup {get; set;}

Remarks

Each Section in Aspose.Words document model provides page setup information via PageSetup class. When you export a document to HTML format you might need to keep this information for further usage. In particular, page setup might be important for rendering to paged media (printing) or subsequent conversion to the native Microsoft Word file formats (DOCX, DOC, RTF, WML).

In most cases HTML is intended for viewing in browsers where pagination is not performed. So this feature is inactive by default.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportRelativeFontSize Property

Aspose.Words

HtmlSaveOptions.ExportRelativeFontSize Property

Specifies whether font sizes should be output in relative units when saving to HTML, MHTML or EPUB. Default is false.

[Visual Basic]
Public Property ExportRelativeFontSize As Boolean
[C#]
public bool ExportRelativeFontSize {get; set;}

Remarks

In many existing documents (HTML, IDPF EPUB) font sizes are specified in relative units. This allows applications to adjust text size when viewing/processing documents. For instance, Microsoft Internet Explorer has "View->Text Size" submenu, Adobe Digital Editions has two buttons: Increase/Decrease Text Size. If you expect this functionality to work then set ExportRelativeFontSize property to true.

Aspose Words document model contains and operates only with absolute font size units. Relative units need additional logic to be recalculated from some initial (standard) size. Font size of Normal document style is taken as standard. For instance, if Normal has 12pt font and some text is 18pt then it will be output as 1.5em. to the HTML.

When this option is enabled, document elements other than text will still have absolute sizes. Also some text-related attributes might be expressed absolutely. In particular, line spacing specified with "exactly" rule might produce unwanted results when scaling text. So the source documents should be properly designed and tested when exporting with ExportRelativeFontSize set to true.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportRoundtripInformation Property

Aspose.Words

HtmlSaveOptions.ExportRoundtripInformation Property

Specifies whether to write the roundtrip information when saving to HTML, MHTML or EPUB. Default value is true for HTML and false for MHTML and EPUB.

[Visual Basic]
Public Property ExportRoundtripInformation As Boolean
[C#]
public bool ExportRoundtripInformation {get; set;}

Remarks

Saving of the roundtrip information allows to restore document properties such as tab stops, comments, headers and footers during the HTML documents loading back into a Document object.

When true, the roundtrip information is exported as -aw-* CSS properties of the corresponding HTML elements.

When false, causes no roundtrip information to be output into produced files.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportTextBoxAsSvg Property

Aspose.Words

HtmlSaveOptions.ExportTextBoxAsSvg Property

Controls how textboxes represented by Shape are saved to HTML, MHTML or EPUB. Default value is false.

[Visual Basic]
Public Property ExportTextBoxAsSvg As Boolean
[C#]
public bool ExportTextBoxAsSvg {get; set;}

Remarks

When set to true, exports textboxes as inline <svg> elements. When false, exports as <img> elements.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportTextInputFormFieldAsText Property

Aspose.Words

HtmlSaveOptions.ExportTextInputFormFieldAsText Property

Controls how text input form fields are saved to HTML or MHTML. Default value is false.

[Visual Basic]
Public Property ExportTextInputFormFieldAsText As Boolean
[C#]
public bool ExportTextInputFormFieldAsText {get; set;}

Remarks

When set to true, exports text input form fields as normal text. When false, exports Word text input form fields as INPUT elements in HTML.

When exporting to EPUB, text input form fields are always saved as text due to requirements of this format.

Example

Shows how to set save options before saving a document to HTML.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// This is the directory we want the exported images to be saved to.
String imagesDir = Path.Combine(ArtifactsDir, "SaveHtmlWithOptions");

// The folder specified needs to exist and should be empty.
if (Directory.Exists(imagesDir))
    Directory.Delete(imagesDir, true);

Directory.CreateDirectory(imagesDir);

// Set an option to export form fields as plain text, not as HTML input elements.
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
options.ExportTextInputFormFieldAsText = true;
options.ImagesFolder = imagesDir;

doc.Save(ArtifactsDir + "Document.SaveWithOptions.html", options);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportTocPageNumbers Property

Aspose.Words

HtmlSaveOptions.ExportTocPageNumbers Property

Specifies whether to write page numbers to table of contents when saving HTML, MHTML and EPUB. Default value is false.

[Visual Basic]
Public Property ExportTocPageNumbers As Boolean
[C#]
public bool ExportTocPageNumbers {get; set;}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ExportXhtmlTransitional Property

Aspose.Words

HtmlSaveOptions.ExportXhtmlTransitional Property

Specifies whether to write the DOCTYPE declaration when saving to HTML or MHTML. When true, writes a DOCTYPE declaration in the document prior to the root element. Default value is false. When saving to EPUB or HTML5 (Html5) the DOCTYPE declaration is always written.

[Visual Basic]
Public Property ExportXhtmlTransitional As Boolean
[C#]
public bool ExportXhtmlTransitional {get; set;}

Remarks

Aspose.Words always writes well formed HTML regardless of this setting.

When true, the beginning of the HTML output document will look like this:

Aspose.Words aims to output XHTML according to the XHTML 1.0 Transitional specification, but the output will not always validate against the DTD. Some structures inside a Microsoft Word document are hard or impossible to map to a document that will validate against the XHTML schema. For example, XHTML does not allow nested lists (UL cannot be nested inside another UL element), but in Microsoft Word document multilevel lists occur quite often.

See Also
HtmlSaveOptions Class | Aspose.Words.Saving Namespace


FontResourcesSubsettingSizeThreshold Property

Aspose.Words

HtmlSaveOptions.FontResourcesSubsettingSizeThreshold Property

Controls which font resources need subsetting when saving to HTML, MHTML or EPUB. Default is 0.

[Visual Basic]
Public Property FontResourcesSubsettingSizeThreshold As Integer
[C#]
public int FontResourcesSubsettingSizeThreshold {get; set;}

Remarks

ExportFontResources allows exporting fonts as subsidiary files or as parts of the output package. If the document uses many fonts, especially with large number of glyphs, then output size can grow significantly. Font subsetting reduces the size of the exported font resource by filtering out glyphs that are not used by the current document.

Font subsetting works as follows:

  • By default, all exported fonts are subsetted.
  • Setting FontResourcesSubsettingSizeThreshold to a positive value instructs Aspose.Words to subset fonts which file size is larger than the specified value.
  • Setting the property to MaxValue suppresses font subsetting.

Important! When exporting font resources, font licensing issues should be considered. Authors who want to use specific fonts via a downloadable font mechanism must always carefully verify that their intended use is within the scope of the font license. Many commercial fonts presently do not allow web downloading of their fonts in any form. License agreements that cover some fonts specifically note that usage via @font-face rules in CSS style sheets is not allowed. Font subsetting can also violate license terms.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ExportFontResources


FontSavingCallback Property

Aspose.Words

HtmlSaveOptions.FontSavingCallback Property

Allows to control how fonts are saved when a document is saved to HTML, MHTML or EPUB.

[Visual Basic]
Public Property FontSavingCallback As IFontSavingCallback
[C#]
public IFontSavingCallback FontSavingCallback {get; set;}

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


FontsFolder Property

Aspose.Words

HtmlSaveOptions.FontsFolder Property

Specifies the physical folder where fonts are saved when exporting a document to HTML. Default is an empty string.

[Visual Basic]
Public Property FontsFolder As String
[C#]
public string FontsFolder {get; set;}

Remarks

When you save a Document in HTML format and ExportFontResources is set to true, Aspose.Words needs to save fonts used in the document as standalone files. FontsFolder allows you to specify where the fonts will be saved and FontsFolderAlias allows to specify how the font URIs will be constructed.

If you save a document into a file and provide a file name, Aspose.Words, by default, saves the fonts in the same folder where the document file is saved. Use FontsFolder to override this behavior.

If you save a document into a stream, Aspose.Words does not have a folder where to save the fonts, but still needs to save the fonts somewhere. In this case, you need to specify an accessible folder in the FontsFolder property or provide custom streams via the FontSavingCallback event handler.

If the folder specified by FontsFolder doesn't exist, it will be created automatically.

ResourceFolder is another way to specify a folder where fonts should be saved.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ResourceFolder | ExportFontResources | FontsFolderAlias | FontSavingCallback


FontsFolderAlias Property

Aspose.Words

HtmlSaveOptions.FontsFolderAlias Property

Specifies the name of the folder used to construct font URIs written into an HTML document. Default is an empty string.

[Visual Basic]
Public Property FontsFolderAlias As String
[C#]
public string FontsFolderAlias {get; set;}

Remarks

When you save a Document in HTML format and ExportFontResources is set to true, Aspose.Words needs to save fonts used in the document as standalone files. FontsFolder allows you to specify where the fonts will be saved and FontsFolderAlias allows to specify how the font URIs will be constructed.

If FontsFolderAlias is not an empty string, then the font URI written to HTML will be FontsFolderAlias + <font file name>.

If FontsFolderAlias is an empty string, then the font URI written to HTML will be FontsFolder + <font file name>.

If FontsFolderAlias is set to '.' (dot), then the font file name will be written to HTML without path regardless of other options.

Alternative way to specify the name of the folder to construct font URIs is to use ResourceFolderAlias.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ResourceFolderAlias | ExportFontResources | FontsFolder | FontSavingCallback


HtmlVersion Property

Aspose.Words

HtmlSaveOptions.HtmlVersion Property

Specifies version of HTML standard that should be used when saving the document to HTML or MHTML. Default value is Xhtml.

[Visual Basic]
Public Property HtmlVersion As HtmlVersion
[C#]
public HtmlVersion HtmlVersion {get; set;}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ImageResolution Property

Aspose.Words

HtmlSaveOptions.ImageResolution Property

Specifies the output resolution for images when exporting to HTML, MHTML or EPUB. Default is 96 dpi.

[Visual Basic]
Public Property ImageResolution As Integer
[C#]
public int ImageResolution {get; set;}

Remarks

This property effects raster images when ScaleImageToShapeSize is true and effects metafiles exported as raster images. Some image properties such as cropping or rotation require saving transformed images and in this case transformed images are created in the given resolution.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ScaleImageToShapeSize


ImageSavingCallback Property

Aspose.Words

HtmlSaveOptions.ImageSavingCallback Property

Allows to control how images are saved when a document is saved to HTML, MHTML or EPUB.

[Visual Basic]
Public Property ImageSavingCallback As IImageSavingCallback
[C#]
public IImageSavingCallback ImageSavingCallback {get; set;}

Example

Shows how to define custom logic for controlling how images are saved when exporting to HTML based formats.

[C#]

public void SaveHtmlExportImages()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Create and pass the object which implements the handler methods.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
    options.ImageSavingCallback = new HandleImageSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithCustomImagesExport.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (args.ImageFileName.EndsWith(".jpeg"))
            args.ImageFileName = args.ImageFileName.Replace(".jpeg", ".jpg");
    }
}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ImagesFolder Property

Aspose.Words

HtmlSaveOptions.ImagesFolder Property

Specifies the physical folder where images are saved when exporting a document to HTML format. Default is an empty string.

[Visual Basic]
Public Property ImagesFolder As String
[C#]
public string ImagesFolder {get; set;}

Remarks

When you save a Document in HTML format, Aspose.Words needs to save all images embedded in the document as standalone files. ImagesFolder allows you to specify where the images will be saved and ImagesFolderAlias allows to specify how the image URIs will be constructed.

If you save a document into a file and provide a file name, Aspose.Words, by default, saves the images in the same folder where the document file is saved. Use ImagesFolder to override this behavior.

If you save a document into a stream, Aspose.Words does not have a folder where to save the images, but still needs to save the images somewhere. In this case, you need to specify an accessible folder in the ImagesFolder property or provide custom streams via the ImageSavingCallback event handler.

If the folder specified by ImagesFolder doesn't exist, it will be created automatically.

ResourceFolder is another way to specify a folder where images should be saved.

Example

Shows how to set save options before saving a document to HTML.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

// This is the directory we want the exported images to be saved to.
String imagesDir = Path.Combine(ArtifactsDir, "SaveHtmlWithOptions");

// The folder specified needs to exist and should be empty.
if (Directory.Exists(imagesDir))
    Directory.Delete(imagesDir, true);

Directory.CreateDirectory(imagesDir);

// Set an option to export form fields as plain text, not as HTML input elements.
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
options.ExportTextInputFormFieldAsText = true;
options.ImagesFolder = imagesDir;

doc.Save(ArtifactsDir + "Document.SaveWithOptions.html", options);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ResourceFolder | ImagesFolderAlias | ImageSavingCallback


ImagesFolderAlias Property

Aspose.Words

HtmlSaveOptions.ImagesFolderAlias Property

Specifies the name of the folder used to construct image URIs written into an HTML document. Default is an empty string.

[Visual Basic]
Public Property ImagesFolderAlias As String
[C#]
public string ImagesFolderAlias {get; set;}

Remarks

When you save a Document in HTML format, Aspose.Words needs to save all images embedded in the document as standalone files. ImagesFolder allows you to specify where the images will be saved and ImagesFolderAlias allows to specify how the image URIs will be constructed.

If ImagesFolderAlias is not an empty string, then the image URI written to HTML will be ImagesFolderAlias + <image file name>.

If ImagesFolderAlias is an empty string, then the image URI written to HTML will be ImagesFolder + <image file name>.

If ImagesFolderAlias is set to '.' (dot), then the image file name will be written to HTML without path regardless of other options.

Alternative way to specify the name of the folder to construct image URIs is to use ResourceFolderAlias.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ResourceFolderAlias | ImagesFolder | ImageSavingCallback


MetafileFormat Property

Aspose.Words

HtmlSaveOptions.MetafileFormat Property

Specifies in what format metafiles are saved when exporting to HTML, MHTML, or EPUB. Default value is Png, meaning that metafiles are rendered to raster PNG images.

[Visual Basic]
Public Property MetafileFormat As HtmlMetafileFormat
[C#]
public HtmlMetafileFormat MetafileFormat {get; set;}

Remarks

Metafiles are not natively displayed by HTML browsers. By default, Aspose.Words converts WMF and EMF images into PNG files when exporting to HTML. Other options are to convert metafiles to SVG images or to export them as is without conversion.

Some image transforms, in particular image cropping, will not be applied to metafile images if they are exported to HTML without conversion.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ImageResolution | ScaleImageToShapeSize


OfficeMathOutputMode Property

Aspose.Words

HtmlSaveOptions.OfficeMathOutputMode Property

Controls how OfficeMath objects are exported to HTML, MHTML or EPUB. Default value is HtmlOfficeMathOutputMode.Image.

[Visual Basic]
Public Property OfficeMathOutputMode As HtmlOfficeMathOutputMode
[C#]
public HtmlOfficeMathOutputMode OfficeMathOutputMode {get; set;}

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ResolveFontNames Property

Aspose.Words

HtmlSaveOptions.ResolveFontNames Property

Specifies whether font family names used in the document are resolved and substituted according to FontSettings when being written into HTML-based formats.

[Visual Basic]
Public Property ResolveFontNames As Boolean
[C#]
public bool ResolveFontNames {get; set;}

Remarks

By default, this option is set to false and font family names are written to HTML as specified in source documents. That is, FontSettings are ignored and no resolution or substitution of font family names is performed.

If this option is set to true, Aspose.Words uses FontSettings to resolve each font family name specified in a source document into the name of an available font family, performing font subsitution as required.

Example

Shows how to resolve all font names before writing them to HTML.

[C#]

Document document = new Document(MyDir + "HtmlSaveOptions.ResolveFontNames.docx");

FontSettings fontSettings = new FontSettings
{
    SubstitutionSettings =
    {
        DefaultFontSubstitution =
        {
            DefaultFontName = "Arial",
            Enabled = true
        }
    }
};

document.FontSettings = fontSettings;

HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.Html)
{
    // By default this option is set to 'False' and Aspose.Words writes font names as specified in the source document.
    ResolveFontNames = true
};

document.Save(ArtifactsDir + "HtmlSaveOptions.ResolveFontNames.html", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ResourceFolder Property

Aspose.Words

HtmlSaveOptions.ResourceFolder Property

Specifies a physical folder where all resources like images, fonts, and external CSS are saved when a document is exported to HTML. Default is an empty string.

[Visual Basic]
Public Property ResourceFolder As String
[C#]
public string ResourceFolder {get; set;}

Remarks

ResourceFolder is the simplest way to specify a folder where all resources should be written. Another way is to use individual properties FontsFolder, ImagesFolder, and CssStyleSheetFileName.

ResourceFolder has a lower priority than folders specified via FontsFolder, ImagesFolder, and CssStyleSheetFileName. For example, if both ResourceFolder and FontsFolder are specified, fonts will be saved to FontsFolder, while images and CSS will be saved to ResourceFolder.

If the folder specified by ResourceFolder doesn't exist, it will be created automatically.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | FontsFolder | ImagesFolder | CssStyleSheetFileName


ResourceFolderAlias Property

Aspose.Words

HtmlSaveOptions.ResourceFolderAlias Property

Specifies the name of the folder used to construct URIs of all resources written into an HTML document. Default is an empty string.

[Visual Basic]
Public Property ResourceFolderAlias As String
[C#]
public string ResourceFolderAlias {get; set;}

Remarks

ResourceFolderAlias is the simplest way to specify how URIs for all resource files should be constructed. Same information can be specified for images and fonts separately via ImagesFolderAlias and FontsFolderAlias properties, respectively. However, there is no individual property for CSS.

ResourceFolderAlias has lower priority than FontsFolderAlias and ImagesFolderAlias. For example, if both ResourceFolderAlias and FontsFolderAlias are specified, fonts' URIs will be constructed using FontsFolderAlias, while URIs of images and CSS will be constructed using ResourceFolderAlias.

If ResourceFolderAlias is empty, the ResourceFolder property value will be used to construct resource URIs.

If ResourceFolderAlias is set to '.' (dot), resource URIs will contain file names only, without any path.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ResourceFolder | FontsFolderAlias | ImagesFolderAlias


SaveFormat Property

Aspose.Words

HtmlSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can be Html, Mhtml or Epub.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

Example

Converts a document to EPUB with save options specified.

[C#]

// Open an existing document from disk.
Document doc = new Document(MyDir + "Document.EpubConversion.doc");

// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();

// Specify the desired encoding.
saveOptions.Encoding = Encoding.UTF8;

// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;

// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;

// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;

// Export the document as an EPUB file.
doc.Save(ArtifactsDir + "Document.EpubConversion.epub", saveOptions);

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


ScaleImageToShapeSize Property

Aspose.Words

HtmlSaveOptions.ScaleImageToShapeSize Property

Specifies whether images are scaled by Aspose.Words to the bounding shape size when exporting to HTML, MHTML or EPUB. Default value is true.

[Visual Basic]
Public Property ScaleImageToShapeSize As Boolean
[C#]
public bool ScaleImageToShapeSize {get; set;}

Remarks

An image in a Microsoft Word document is a shape. The shape has a size and the image has its own size. The sizes are not directly linked. For example, the image can be 1024x786 pixels, but shape that displays this image can be 400x300 points.

In order to display an image in the browser, it must be scaled to the shape size. The ScaleImageToShapeSize property controls where the scaling of the image takes place: in Aspose.Words during export to HTML or in the browser when displaying the document.

When ScaleImageToShapeSize is true, the image is scaled by Aspose.Words using high quality scaling during export to HTML. When ScaleImageToShapeSize is false, the image is output with its original size and the browser has to scale it.

In general, browsers do quick and poor quality scaling. As a result, you will normally get better display quality in the browser and smaller file size when ScaleImageToShapeSize is true, but better printing quality and faster conversion when ScaleImageToShapeSize is false.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ImageResolution


TableWidthOutputMode Property

Aspose.Words

HtmlSaveOptions.TableWidthOutputMode Property

Controls how table, row and cell widths are exported to HTML, MHTML or EPUB. Default value is All.

[Visual Basic]
Public Property TableWidthOutputMode As HtmlElementSizeOutputMode
[C#]
public HtmlElementSizeOutputMode TableWidthOutputMode {get; set;}

Remarks

In the HTML format, table, row and cell elements (<table>, <tr>, <th>, <td>) can have their widths specified either in relative (percentage) or in absolute units. In a document in Aspose.Words, tables, rows and cells can have their widths specified using either relative or absolute units too.

When you convert a document to HTML using Aspose.Words, you might want to control how table, row and cell widths are exported to affect how the resulting document is displayed in the visual agent (e.g. a browser or viewer).

Use this property as a filter to specify what table widths values are exported into the destination document. For example, if you are converting a document to EPUB and intend to view the document on a mobile reading device, then you probably want to avoid exporting absolute width values. To do this you need to specify the output mode RelativeOnly or None so the viewer on the mobile device can layout the table to fit the width of the screen as best as it can.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace


HtmlVersion Enumeration

Indicates the version of HTML is used when saving the document to Html and Mhtml formats.

[Visual Basic]
Public Enum HtmlVersion
[C#]
public enum HtmlVersion

Members

Member Name | Description | Value
Xhtml | Saves the document in compliance with the XHTML 1.0 Transitional standard. | 0
Html5 | Saves the document in compliance with the HTML 5 standard. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


ICssSavingCallback Interface

Implement this interface if you want to control how Aspose.Words saves CSS (Cascading Style Sheet) when saving a document to HTML.

For a list of all members of this type, see ICssSavingCallback Members.

[Visual Basic]
Public Interface ICssSavingCallback
[C#]
public interface ICssSavingCallback

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ICssSavingCallback Members | Aspose.Words.Saving Namespace


ICssSavingCallback Members

ICssSavingCallback overview

Public Instance Methods

CssSaving Called when Aspose.Words saves an CSS (Cascading Style Sheet).

See Also

ICssSavingCallback Interface | Aspose.Words.Saving Namespace


ICssSavingCallback Methods

The methods of the ICssSavingCallback interface are listed below. For a complete list of ICssSavingCallback interface members, see the ICssSavingCallback Members topic.

Public Instance Methods

CssSaving Called when Aspose.Words saves an CSS (Cascading Style Sheet).

See Also

ICssSavingCallback Interface | Aspose.Words.Saving Namespace


ICssSavingCallback.CssSaving Method

Called when Aspose.Words saves an CSS (Cascading Style Sheet).

[Visual Basic]
Sub CssSaving( _
ByVal args As CssSavingArgs _
)
[C#]
void CssSaving(
CssSavingArgs args
);

See Also

ICssSavingCallback Interface | Aspose.Words.Saving Namespace


IDocumentPartSavingCallback Interface

Implement this interface if you want to receive notifications and control how Aspose.Words saves document parts when exporting a document to Html or Epub format.

For a list of all members of this type, see IDocumentPartSavingCallback Members.

[Visual Basic]
Public Interface IDocumentPartSavingCallback
[C#]
public interface IDocumentPartSavingCallback

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IDocumentPartSavingCallback Members | Aspose.Words.Saving Namespace


IDocumentPartSavingCallback Members

IDocumentPartSavingCallback overview

Public Instance Methods

DocumentPartSaving Called when Aspose.Words is about to save a document part.

See Also

IDocumentPartSavingCallback Interface | Aspose.Words.Saving Namespace


IDocumentPartSavingCallback Methods

The methods of the IDocumentPartSavingCallback interface are listed below. For a complete list of IDocumentPartSavingCallback interface members, see the IDocumentPartSavingCallback Members topic.

Public Instance Methods

DocumentPartSaving Called when Aspose.Words is about to save a document part.

See Also

IDocumentPartSavingCallback Interface | Aspose.Words.Saving Namespace


IDocumentPartSavingCallback.DocumentPartSaving Method

Called when Aspose.Words is about to save a document part.

[Visual Basic]
Sub DocumentPartSaving( _
ByVal args As DocumentPartSavingArgs _
)
[C#]
void DocumentPartSaving(
DocumentPartSavingArgs args
);

See Also

IDocumentPartSavingCallback Interface | Aspose.Words.Saving Namespace


IFontSavingCallback Interface

Implement this interface if you want to receive notifications and control how Aspose.Words saves fonts when exporting a document to HTML format.

For a list of all members of this type, see IFontSavingCallback Members.

[Visual Basic]
Public Interface IFontSavingCallback
[C#]
public interface IFontSavingCallback

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IFontSavingCallback Members | Aspose.Words.Saving Namespace


IFontSavingCallback Members

IFontSavingCallback overview

Public Instance Methods

FontSaving Called when Aspose.Words is about to save a font resource.

See Also

IFontSavingCallback Interface | Aspose.Words.Saving Namespace


IFontSavingCallback Methods

The methods of the IFontSavingCallback interface are listed below. For a complete list of IFontSavingCallback interface members, see the IFontSavingCallback Members topic.

Public Instance Methods

FontSaving Called when Aspose.Words is about to save a font resource.

See Also

IFontSavingCallback Interface | Aspose.Words.Saving Namespace


IFontSavingCallback.FontSaving Method

Called when Aspose.Words is about to save a font resource.

[Visual Basic]
Sub FontSaving( _
ByVal args As FontSavingArgs _
)
[C#]
void FontSaving(
FontSavingArgs args
);

Example

Shows how to define custom logic for handling font exporting when saving to HTML based formats.

[C#]

public void SaveHtmlExportFonts()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Set the option to export font resources.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Mhtml);
    options.ExportFontResources = true;
    // Create and pass the object which implements the handler methods.
    options.FontSavingCallback = new HandleFontSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithFontsExport.html", options);
}

public class HandleFontSaving : IFontSavingCallback
{
    void IFontSavingCallback.FontSaving(FontSavingArgs args)
    {
        // You can implement logic here to rename fonts, save to file etc. For this example just print some details about the current font being handled.
        Console.WriteLine("Font Name = {0}, Font Filename = {1}", args.FontFamilyName, args.FontFileName);
    }
}

See Also

IFontSavingCallback Interface | Aspose.Words.Saving Namespace


IImageSavingCallback Interface

Implement this interface if you want to control how Aspose.Words saves images when saving a document to HTML. May be used by other formats.

For a list of all members of this type, see IImageSavingCallback Members.

[Visual Basic]
Public Interface IImageSavingCallback
[C#]
public interface IImageSavingCallback

Example

Shows how to define custom logic for controlling how images are saved when exporting to HTML based formats.

[C#]

public void SaveHtmlExportImages()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Create and pass the object which implements the handler methods.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
    options.ImageSavingCallback = new HandleImageSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithCustomImagesExport.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (args.ImageFileName.EndsWith(".jpeg"))
            args.ImageFileName = args.ImageFileName.Replace(".jpeg", ".jpg");
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IImageSavingCallback Members | Aspose.Words.Saving Namespace


IImageSavingCallback Members

IImageSavingCallback overview

Public Instance Methods

ImageSaving Called when Aspose.Words saves an image to HTML.

See Also

IImageSavingCallback Interface | Aspose.Words.Saving Namespace


IImageSavingCallback Methods

The methods of the IImageSavingCallback interface are listed below. For a complete list of IImageSavingCallback interface members, see the IImageSavingCallback Members topic.

Public Instance Methods

ImageSaving Called when Aspose.Words saves an image to HTML.

See Also

IImageSavingCallback Interface | Aspose.Words.Saving Namespace


IImageSavingCallback.ImageSaving Method

Called when Aspose.Words saves an image to HTML.

[Visual Basic]
Sub ImageSaving( _
ByVal args As ImageSavingArgs _
)
[C#]
void ImageSaving(
ImageSavingArgs args
);

Example

Shows how to define custom logic for controlling how images are saved when exporting to HTML based formats.

[C#]

public void SaveHtmlExportImages()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Create and pass the object which implements the handler methods.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
    options.ImageSavingCallback = new HandleImageSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithCustomImagesExport.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (args.ImageFileName.EndsWith(".jpeg"))
            args.ImageFileName = args.ImageFileName.Replace(".jpeg", ".jpg");
    }
}

See Also

IImageSavingCallback Interface | Aspose.Words.Saving Namespace


ImageBinarizationMethod Enumeration

Specifies the method used to binarize image.

[Visual Basic]
Public Enum ImageBinarizationMethod
[C#]
public enum ImageBinarizationMethod

Members

Member Name | Description | Value
Threshold | Specifies threshold method. | 0
FloydSteinbergDithering | Specifies dithering using Floyd-Steinberg error diffusion method. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


ImageColorMode Enumeration

Specifies the color mode for the generated images of document pages.

[Visual Basic]
Public Enum ImageColorMode
[C#]
public enum ImageColorMode

Members

Member Name | Description | Value
None | The pages of the document will be rendered as color images. | 0
Grayscale | The pages of the document will be rendered as grayscale images. | 1
BlackAndWhite | The pages of the document will be rendered as black and white images. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


ImagePixelFormat Enumeration

Specifies the pixel format for the generated images of document pages.

[Visual Basic]
Public Enum ImagePixelFormat
[C#]
public enum ImagePixelFormat

Members

Member Name | Description | Value
Format16BppRgb555 | 16 bits per pixel, RGB. | 0
Format16BppRgb565 | 16 bits per pixel, RGB. | 1
Format16BppArgb1555 | 16 bits per pixel, ARGB. | 2
Format24BppRgb | 24 bits per pixel, RGB. | 3
Format32BppRgb | 32 bits per pixel, RGB. | 4
Format32BppArgb | 32 bits per pixel, ARGB. | 5
Format32BppPArgb | 32 bits per pixel, ARGB, premultiplied alpha. | 6
Format48BppRgb | 48 bits per pixel, RGB. | 7
Format64BppArgb | 64 bits per pixel, ARGB. | 8
Format64BppPArgb | 64 bits per pixel, ARGB, premultiplied alpha. | 9
Format1bppIndexed | 1 bit per pixel, Indexed. | 10

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


ImageSaveOptions Class

Allows to specify additional options when rendering document pages or shapes to images.

For a list of all members of this type, see ImageSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.ImageSaveOptions

[Visual Basic]
Public Class ImageSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class ImageSaveOptions : FixedPageSaveOptions

Example

Renders a page of a Word document into a PNG image at a specific resolution.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png)
{
    Resolution = 300,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToImageResolution.png", options);
Renders a page of a Word document into an image with transparent or colored background.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions imgOptions = new ImageSaveOptions(SaveFormat.Png);

imgOptions.PaperColor = Color.Transparent;
doc.Save(ArtifactsDir + "Rendering.SaveToImagePaperColorTransparent.png", imgOptions);

imgOptions.PaperColor = Color.LightCoral;
doc.Save(ArtifactsDir + "Rendering.SaveToImagePaperColorCoral.png", imgOptions);
Converts a page of a Word document into JPEG images of different qualities.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg);

// Try worst quality.
saveOptions.JpegQuality = 0;
doc.Save(ArtifactsDir + "Rendering.SaveToImageJpegQuality0.jpeg", saveOptions);

// Try best quality.
saveOptions.JpegQuality = 100;
doc.Save(ArtifactsDir + "Rendering.SaveToImageJpegQuality100.jpeg", saveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ImageSaveOptions Members | Aspose.Words.Saving Namespace


ImageSaveOptions Members

ImageSaveOptions overview

Public Instance Constructors

ImageSaveOptions Constructor Initializes a new instance of this class that can be used to save rendered images in the Tiff, Png, Bmp, Emf, Jpeg or Svg format. Png, Bmp, Jpeg or Svg format.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
GraphicsQualityOptions | Allows to specify rendering mode and quality for the Graphics object.
HorizontalResolution | Gets or sets the horizontal resolution for the generated images, in dots per inch.
ImageBrightness | Gets or sets the brightness for the generated images.
ImageColorMode | Gets or sets the color mode for the generated images.
ImageContrast | Gets or sets the contrast for the generated images.
JpegQuality | Gets or sets a value determining the quality of the generated JPEG images.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions | Allows to specify how metafiles are treated in the rendered output.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount | Gets or sets the number of pages to render when saving to a multipage TIFF file. Default is MaxValue which means all pages of the document will be rendered.
PageIndex | Gets or sets the 0-based index of the first page to render. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PaperColor | Gets or sets the background (paper) color for the generated images. The default value is White.
PixelFormat | Gets or sets the pixel format for the generated images.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
Resolution | Sets both horizontal and vertical resolution for the generated images, in dots per inch.
SaveFormat | Specifies the format in which the rendered document pages or shapes will be saved if this save options object is used. Can be Tiff, Png, Bmp, Emf, Jpeg or Svg.
Scale | Gets or sets the zoom factor for the generated images.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
ThresholdForFloydSteinbergDithering | Gets or sets the threshold that determines the value of the binarization error in the Floyd-Steinberg method. when ImageBinarizationMethod is ImageBinarizationMethod.FloydSteinbergDithering.
TiffBinarizationMethod | Gets or sets method used while converting images to 1 bpp format when SaveFormat is SaveFormat.Tiff and TiffCompression is equal to TiffCompression.Ccitt3 or TiffCompression.Ccitt4.
TiffCompression | Gets or sets the type of compression to apply when saving generated images to the TIFF format.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseGdiEmfRenderer | Gets or sets a value determining whether to use GDI+ or Aspose.Words metafile renderer when saving to EMF.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
VerticalResolution | Gets or sets the vertical resolution for the generated images, in dots per inch.

Public Instance Methods

Clone | Creates a deep clone of this object.
Equals (inherited from FixedPageSaveOptions) |

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageSaveOptions Constructor

Initializes a new instance of this class that can be used to save rendered images in the Tiff, Png, Bmp, Emf, Jpeg or Svg format. Png, Bmp, Jpeg or Svg format.

[Visual Basic]
Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public ImageSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be Tiff, Png, Bmp, Emf, Jpeg or Svg. Png, Bmp, Jpeg or Svg.

Example

Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.

[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save as a JPEG image file with default options
doc.Save(ArtifactsDir + "Rendering.JpegDefaultOptions.jpg");

// Save document to stream as a JPEG with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to a JPEG image with specified options.
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg);
imageOptions.PageIndex = 2;
imageOptions.PageCount = 1;
imageOptions.JpegQuality = 80;
doc.Save(ArtifactsDir + "Rendering.JpegCustomOptions.jpg", imageOptions);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageSaveOptions Properties

The properties of the ImageSaveOptions class are listed below. For a complete list of ImageSaveOptions class members, see the ImageSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
GraphicsQualityOptions | Allows to specify rendering mode and quality for the Graphics object.
HorizontalResolution | Gets or sets the horizontal resolution for the generated images, in dots per inch.
ImageBrightness | Gets or sets the brightness for the generated images.
ImageColorMode | Gets or sets the color mode for the generated images.
ImageContrast | Gets or sets the contrast for the generated images.
JpegQuality | Gets or sets a value determining the quality of the generated JPEG images.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions | Allows to specify how metafiles are treated in the rendered output.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount | Gets or sets the number of pages to render when saving to a multipage TIFF file. Default is MaxValue which means all pages of the document will be rendered.
PageIndex | Gets or sets the 0-based index of the first page to render. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PaperColor | Gets or sets the background (paper) color for the generated images. The default value is White.
PixelFormat | Gets or sets the pixel format for the generated images.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
Resolution | Sets both horizontal and vertical resolution for the generated images, in dots per inch.
SaveFormat | Specifies the format in which the rendered document pages or shapes will be saved if this save options object is used. Can be Tiff, Png, Bmp, Emf, Jpeg or Svg.
Scale | Gets or sets the zoom factor for the generated images.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
ThresholdForFloydSteinbergDithering | Gets or sets the threshold that determines the value of the binarization error in the Floyd-Steinberg method. when ImageBinarizationMethod is ImageBinarizationMethod.FloydSteinbergDithering.
TiffBinarizationMethod | Gets or sets method used while converting images to 1 bpp format when SaveFormat is SaveFormat.Tiff and TiffCompression is equal to TiffCompression.Ccitt3 or TiffCompression.Ccitt4.
TiffCompression | Gets or sets the type of compression to apply when saving generated images to the TIFF format.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseGdiEmfRenderer | Gets or sets a value determining whether to use GDI+ or Aspose.Words metafile renderer when saving to EMF.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
VerticalResolution | Gets or sets the vertical resolution for the generated images, in dots per inch.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


GraphicsQualityOptions Property

Aspose.Words

ImageSaveOptions.GraphicsQualityOptions Property

Allows to specify rendering mode and quality for the Graphics object.

[Visual Basic]
Public Property GraphicsQualityOptions As GraphicsQualityOptions
[C#]
public GraphicsQualityOptions GraphicsQualityOptions {get; set;}

Remarks

Use this property to override the Graphics settings provided by Aspose.Words engine by default.

It will take effect only when a document is being saved to an image-like format.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


HorizontalResolution Property

Aspose.Words

ImageSaveOptions.HorizontalResolution Property

Gets or sets the horizontal resolution for the generated images, in dots per inch.

[Visual Basic]
Public Property HorizontalResolution As Single
[C#]
public float HorizontalResolution {get; set;}

Remarks

This property has effect only when saving to raster image formats.

The default value is 96.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageBrightness Property

Aspose.Words

ImageSaveOptions.ImageBrightness Property

Gets or sets the brightness for the generated images.

[Visual Basic]
Public Property ImageBrightness As Single
[C#]
public float ImageBrightness {get; set;}

Remarks

This property has effect only when saving to raster image formats.

The default value is 0.5. The value must be in the range between 0 and 1.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageColorMode Property

Aspose.Words

ImageSaveOptions.ImageColorMode Property

Gets or sets the color mode for the generated images.

[Visual Basic]
Public Property ImageColorMode As ImageColorMode
[C#]
public ImageColorMode ImageColorMode {get; set;}

Remarks

This property has effect only when saving to raster image formats.

The default value is None.

Example

Show how to convert document images to black and white with 1 bit per pixel

[C#]

Document doc = new Document(MyDir + "ImageSaveOptions.BlackAndWhite.docx");

ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.Png);
imageSaveOptions.ImageColorMode = ImageColorMode.BlackAndWhite;
imageSaveOptions.PixelFormat = ImagePixelFormat.Format1bppIndexed;

doc.Save(ArtifactsDir + "ImageSaveOptions.BlackAndWhite.png", imageSaveOptions);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageContrast Property

Aspose.Words

ImageSaveOptions.ImageContrast Property

Gets or sets the contrast for the generated images.

[Visual Basic]
Public Property ImageContrast As Single
[C#]
public float ImageContrast {get; set;}

Remarks

This property has effect only when saving to raster image formats.

The default value is 0.5. The value must be in the range between 0 and 1.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


JpegQuality Property

Aspose.Words

ImageSaveOptions.JpegQuality Property

Gets or sets a value determining the quality of the generated JPEG images.

[Visual Basic]
Public Property JpegQuality As Integer
[C#]
new public int JpegQuality {get; set;}

Remarks

Has effect only when saving to JPEG.

Use this property to get or set the quality of generated images when saving in JPEG format. The value may vary from 0 to 100 where 0 means worst quality but maximum compression and 100 means best quality but minimum compression.

The default value is 95.

Example

Converts a page of a Word document into JPEG images of different qualities.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg);

// Try worst quality.
saveOptions.JpegQuality = 0;
doc.Save(ArtifactsDir + "Rendering.SaveToImageJpegQuality0.jpeg", saveOptions);

// Try best quality.
saveOptions.JpegQuality = 100;
doc.Save(ArtifactsDir + "Rendering.SaveToImageJpegQuality100.jpeg", saveOptions);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

ImageSaveOptions.MetafileRenderingOptions Property

Allows to specify how metafiles are treated in the rendered output.

[Visual Basic]
Public ReadOnly Property MetafileRenderingOptions As MetafileRenderingOptions
[C#]
new public MetafileRenderingOptions MetafileRenderingOptions {get;}

Remarks

When Vector is specified, Aspose.Words renders metafile to vector graphics using its own metafile rendering engine first and then renders vector graphics to the image.

When Bitmap is specified, Aspose.Words renders metafile directly to the image using the GDI+ metafile rendering engine.

GDI+ metafile rendering engine works faster, supports almost all metafile features but on low resolutions may produce inconsistent result when compared to the rest of vector graphics (especially for text) on the page. Aspose.Words metafile rendering engine will produce more consistent result even on low resolutions but works slower and may inaccurately render complex metafiles.

The default value for MetafileRenderingMode is Bitmap.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

ImageSaveOptions.PageCount Property

Gets or sets the number of pages to render when saving to a multipage TIFF file. Default is MaxValue which means all pages of the document will be rendered.

[Visual Basic]
Public Property PageCount As Integer
[C#]
new public int PageCount {get; set;}

Remarks

This property has effect only when rendering document pages. This property is ignored when rendering shapes to images.

Example

Converts a page of a Word document into a TIFF image and uses the CCITT compression.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff)
{
    TiffCompression = TiffCompression.Ccitt3,
    PageIndex = 0,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToTiffCompression.tiff", options);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

ImageSaveOptions.PageIndex Property

Gets or sets the 0-based index of the first page to render. Default is 0.

[Visual Basic]
Public Property PageIndex As Integer
[C#]
new public int PageIndex {get; set;}

Remarks

This property has effect only when rendering document pages. This property is ignored when rendering shapes to images.

Example

Shows how to save specific document page as image file.

[C#]

Document doc = new Document(MyDir + "SaveOptions.MyraidPro.docx");

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Gif)
{
    PageIndex = 0 // Define which page will save
};

doc.Save(ArtifactsDir + "SaveOptions.MyraidPro.gif", saveOptions);
Converts a page of a Word document into a TIFF image and uses the CCITT compression.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff)
{
    TiffCompression = TiffCompression.Ccitt3,
    PageIndex = 0,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToTiffCompression.tiff", options);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


PaperColor Property

Aspose.Words

ImageSaveOptions.PaperColor Property

Gets or sets the background (paper) color for the generated images.

The default value is White.

[Visual Basic]
Public Property PaperColor As Color
[C#]
public Color PaperColor {get; set;}

Remarks

When rendering pages of a document that specifies its own background color, then the document background color will override the color specified by this property.

Example

Renders a page of a Word document into an image with transparent or colored background.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions imgOptions = new ImageSaveOptions(SaveFormat.Png);

imgOptions.PaperColor = Color.Transparent;
doc.Save(ArtifactsDir + "Rendering.SaveToImagePaperColorTransparent.png", imgOptions);

imgOptions.PaperColor = Color.LightCoral;
doc.Save(ArtifactsDir + "Rendering.SaveToImagePaperColorCoral.png", imgOptions);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


PixelFormat Property

Aspose.Words

ImageSaveOptions.PixelFormat Property

Gets or sets the pixel format for the generated images.

[Visual Basic]
Public Property PixelFormat As ImagePixelFormat
[C#]
public ImagePixelFormat PixelFormat {get; set;}

Remarks

The default value is Format32BppArgb.

Pixel format of the output image may differ from the set value because of work of GDI+.

Example

Show how to convert document images to black and white with 1 bit per pixel

[C#]

Document doc = new Document(MyDir + "ImageSaveOptions.BlackAndWhite.docx");

ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.Png);
imageSaveOptions.ImageColorMode = ImageColorMode.BlackAndWhite;
imageSaveOptions.PixelFormat = ImagePixelFormat.Format1bppIndexed;

doc.Save(ArtifactsDir + "ImageSaveOptions.BlackAndWhite.png", imageSaveOptions);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


Resolution Property

Aspose.Words

ImageSaveOptions.Resolution Property

Sets both horizontal and vertical resolution for the generated images, in dots per inch.

[Visual Basic]
Public Property Resolution As Single
[C#]
public float Resolution {set;}

Remarks

This property has effect only when saving to raster image formats.

Example

Renders a page of a Word document into a PNG image at a specific resolution.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png)
{
    Resolution = 300,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToImageResolution.png", options);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

ImageSaveOptions.SaveFormat Property

Specifies the format in which the rendered document pages or shapes will be saved if this save options object is used. Can be Tiff, Png, Bmp, Emf, Jpeg or Svg.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


Scale Property

Aspose.Words

ImageSaveOptions.Scale Property

Gets or sets the zoom factor for the generated images.

[Visual Basic]
Public Property Scale As Single
[C#]
public float Scale {get; set;}

Remarks

The default value is 1.0. The value must be greater than 0.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ThresholdForFloydSteinbergDithering Property

Aspose.Words

ImageSaveOptions.ThresholdForFloydSteinbergDithering Property

Gets or sets the threshold that determines the value of the binarization error in the Floyd-Steinberg method. when ImageBinarizationMethod is ImageBinarizationMethod.FloydSteinbergDithering.

[Visual Basic]
Public Property ThresholdForFloydSteinbergDithering As Byte
[C#]
public byte ThresholdForFloydSteinbergDithering {get; set;}

Remarks

The default value is 128.

Example

Shows how to control the threshold for TIFF binarization in the Floyd-Steinberg method

[C#]

Document doc = new Document (MyDir + "ImagesSaveOptions.ThresholdForFloydSteinbergDithering.docx");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff)
{
    TiffCompression = TiffCompression.Ccitt3,
    ImageColorMode = ImageColorMode.Grayscale,
    TiffBinarizationMethod = ImageBinarizationMethod.FloydSteinbergDithering,
    ThresholdForFloydSteinbergDithering = 254 // The default value of this property is 128. The higher value, the darker image.
};

doc.Save(ArtifactsDir + "ImagesSaveOptions.ThresholdForFloydSteinbergDithering.tiff", options);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


TiffBinarizationMethod Property

Aspose.Words

ImageSaveOptions.TiffBinarizationMethod Property

Gets or sets method used while converting images to 1 bpp format when SaveFormat is SaveFormat.Tiff and TiffCompression is equal to TiffCompression.Ccitt3 or TiffCompression.Ccitt4.

[Visual Basic]
Public Property TiffBinarizationMethod As ImageBinarizationMethod
[C#]
public ImageBinarizationMethod TiffBinarizationMethod {get; set;}

Remarks

The default value is ImageBinarizationMethod.Threshold.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


TiffCompression Property

Aspose.Words

ImageSaveOptions.TiffCompression Property

Gets or sets the type of compression to apply when saving generated images to the TIFF format.

[Visual Basic]
Public Property TiffCompression As TiffCompression
[C#]
public TiffCompression TiffCompression {get; set;}

Remarks

Has effect only when saving to TIFF.

The default value is Lzw.

Example

Converts a page of a Word document into a TIFF image and uses the CCITT compression.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff)
{
    TiffCompression = TiffCompression.Ccitt3,
    PageIndex = 0,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToTiffCompression.tiff", options);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


UseGdiEmfRenderer Property

Aspose.Words

ImageSaveOptions.UseGdiEmfRenderer Property

Gets or sets a value determining whether to use GDI+ or Aspose.Words metafile renderer when saving to EMF.

[Visual Basic]
Public Property UseGdiEmfRenderer As Boolean
[C#]
public bool UseGdiEmfRenderer {get; set;}

Remarks

If set to true GDI+ metafile renderer is used. I.e. content is written to GDI+ graphics object and saved to metafile.

If set to false Aspose.Words metafile renderer is used. I.e. content is written directly to the metafile format with Aspose.Words.

The default value is true.

Has effect only when saving to EMF.

Example

Shows how to save metafiles directly without using GDI+ to EMF.

[C#]

Document doc = new Document(MyDir + "SaveOptions.MyraidPro.docx");

ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Emf)
{
    UseGdiEmfRenderer = false
};

doc.Save(ArtifactsDir + "SaveOptions.UseGdiEmfRenderer.docx", saveOptions);

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


VerticalResolution Property

Aspose.Words

ImageSaveOptions.VerticalResolution Property

Gets or sets the vertical resolution for the generated images, in dots per inch.

[Visual Basic]
Public Property VerticalResolution As Single
[C#]
public float VerticalResolution {get; set;}

Remarks

This property has effect only when saving to raster image formats.

The default value is 96.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageSaveOptions Methods

The methods of the ImageSaveOptions class are listed below. For a complete list of ImageSaveOptions class members, see the ImageSaveOptions Members topic.

Public Instance Methods

Clone | Creates a deep clone of this object.
Equals (inherited from FixedPageSaveOptions) |

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageSaveOptions.Clone Method

Creates a deep clone of this object.

[Visual Basic]
Public Function Clone() As ImageSaveOptions
[C#]
public ImageSaveOptions Clone();

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


ImageSavingArgs Class

Provides data for the ImageSaving event.

For a list of all members of this type, see ImageSavingArgs Members.

System.Object
Aspose.Words.Saving.ImageSavingArgs

[Visual Basic]
Public Class ImageSavingArgs
[C#]
public class ImageSavingArgs

Remarks

By default, when Aspose.Words saves a document to HTML, it saves each image into a separate file. Aspose.Words uses the document file name and a unique number to generate unique file name for each image found in the document.

ImageSavingArgs allows to redefine how image file names are generated or to completely circumvent saving of images into files by providing your own stream objects.

To apply your own logic for generating image file names use the ImageFileName, CurrentShape and IsImageAvailable properties.

To save images into streams instead of files, use the ImageStream property.

Example

Shows how to define custom logic for controlling how images are saved when exporting to HTML based formats.

[C#]

public void SaveHtmlExportImages()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Create and pass the object which implements the handler methods.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
    options.ImageSavingCallback = new HandleImageSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithCustomImagesExport.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (args.ImageFileName.EndsWith(".jpeg"))
            args.ImageFileName = args.ImageFileName.Replace(".jpeg", ".jpg");
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ImageSavingArgs Members | Aspose.Words.Saving Namespace


ImageSavingArgs Members

ImageSavingArgs overview

Public Instance Properties

CurrentShape | Gets the ShapeBase object corresponding to the shape or group shape that is about to be saved.
Document | Gets the document object that is currently being saved.
ImageFileName | Gets or sets the file name (without path) where the image will be saved to.
ImageStream | Allows to specify the stream where the image will be saved to.
IsImageAvailable | Returns true if the current image is available for export.
KeepImageStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving an image.

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace


ImageSavingArgs Properties

The properties of the ImageSavingArgs class are listed below. For a complete list of ImageSavingArgs class members, see the ImageSavingArgs Members topic.

Public Instance Properties

CurrentShape | Gets the ShapeBase object corresponding to the shape or group shape that is about to be saved.
Document | Gets the document object that is currently being saved.
ImageFileName | Gets or sets the file name (without path) where the image will be saved to.
ImageStream | Allows to specify the stream where the image will be saved to.
IsImageAvailable | Returns true if the current image is available for export.
KeepImageStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving an image.

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace


CurrentShape Property

Aspose.Words

ImageSavingArgs.CurrentShape Property

Gets the ShapeBase object corresponding to the shape or group shape that is about to be saved.

[Visual Basic]
Public ReadOnly Property CurrentShape As ShapeBase
[C#]
public ShapeBase CurrentShape {get;}

Remarks

IImageSavingCallback can be fired while saving either a shape or a group shape. That's why the property has ShapeBase type. You can check whether it's a group shape comparing ShapeType with Group or by casting it to one of derived classes: Shape or GroupShape.

Aspose.Words uses the document file name and a unique number to generate unique file name for each image found in the document. You can use the CurrentShape property to generate a "better" file name by examining shape properties such as Title (Shape only), SourceFullName (Shape only) and Name. Of course you can build file names using any other properties or criteria but note that subsidiary file names must be unique within the export operation.

Some images in the document can be unavailable. To check image availability use the IsImageAvailable property.

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace


Document Property

Aspose.Words

ImageSavingArgs.Document Property

Gets the document object that is currently being saved.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace


ImageFileName Property

Aspose.Words

ImageSavingArgs.ImageFileName Property

Gets or sets the file name (without path) where the image will be saved to.

[Visual Basic]
Public Property ImageFileName As String
[C#]
public string ImageFileName {get; set;}

Remarks

This property allows you to redefine how the image file names are generated during export to HTML.

When the event is fired, this property contains the file name that was generated by Aspose.Words. You can change the value of this property to save the image into a different file. Note that file names must be unique.

Aspose.Words automatically generates a unique file name for every embedded image when exporting to HTML format. How the image file name is generated depends on whether you save the document to a file or to a stream.

When saving a document to a file, the generated image file name looks like <document base file name>.<image number>.<extension>.

When saving a document to a stream, the generated image file name looks like Aspose.Words.<document guid>.<image number>.<extension>.

ImageFileName must contain only the file name without the path. Aspose.Words determines the path for saving and the value of the src attribute for writing to HTML using the document file name, the ImagesFolder and ImagesFolderAlias properties.

Example

Shows how to define custom logic for controlling how images are saved when exporting to HTML based formats.

[C#]

public void SaveHtmlExportImages()
{
    Document doc = new Document(MyDir + "Document.doc");

    // Create and pass the object which implements the handler methods.
    HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
    options.ImageSavingCallback = new HandleImageSaving();

    doc.Save(ArtifactsDir + "Document.SaveWithCustomImagesExport.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs args)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (args.ImageFileName.EndsWith(".jpeg"))
            args.ImageFileName = args.ImageFileName.Replace(".jpeg", ".jpg");
    }
}

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace | CurrentShape | IsImageAvailable | ImageStream | ImagesFolder | ImagesFolderAlias


ImageStream Property

Aspose.Words

ImageSavingArgs.ImageStream Property

Allows to specify the stream where the image will be saved to.

[Visual Basic]
Public Property ImageStream As Stream
[C#]
public Stream ImageStream {get; set;}

Remarks

This property allows you to save images to streams instead of files during HTML.

The default value is null. When this property is null, the image will be saved to a file specified in the ImageFileName property.

Using IImageSavingCallback you cannot substitute one image with another. It is intended only for control over location where to save images.

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace | ImageFileName | KeepImageStreamOpen


IsImageAvailable Property

Aspose.Words

ImageSavingArgs.IsImageAvailable Property

Returns true if the current image is available for export.

[Visual Basic]
Public ReadOnly Property IsImageAvailable As Boolean
[C#]
public bool IsImageAvailable {get;}

Remarks

Some images in the document can be unavailable, for example, because the image is linked and the link is inaccessible or does not point to a valid image. In this case Aspose.Words exports an icon with a red cross. This property returns true if the original image is available; returns false if the original image is not available and a "no image" icon will be offered for save.

When saving a group shape or a shape that doesn't require any image this property is always true.

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace | CurrentShape


KeepImageStreamOpen Property

Aspose.Words

ImageSavingArgs.KeepImageStreamOpen Property

Specifies whether Aspose.Words should keep the stream open or close it after saving an image.

[Visual Basic]
Public Property KeepImageStreamOpen As Boolean
[C#]
public bool KeepImageStreamOpen {get; set;}

Remarks

Default is false and Aspose.Words will close the stream you provided in the ImageStream property after writing an image into it. Specify true to keep the stream open.

See Also

ImageSavingArgs Class | Aspose.Words.Saving Namespace | ImageStream


IPageSavingCallback Interface

Implement this interface if you want to control how Aspose.Words saves separate pages when saving a document to fixed page formats.

For a list of all members of this type, see IPageSavingCallback Members.

[Visual Basic]
Public Interface IPageSavingCallback
[C#]
public interface IPageSavingCallback

Example

Shows how separate pages are saved when a document is exported to fixed page format.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

    HtmlFixedSaveOptions htmlFixedSaveOptions =
        new HtmlFixedSaveOptions { PageIndex = 0, PageCount = doc.PageCount };
    htmlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback();

    doc.Save(ArtifactsDir + "Rendering.html", htmlFixedSaveOptions);

    string[] filePaths = Directory.GetFiles(ArtifactsDir + "", "Page_*.html");

    for (int i = 0; i < doc.PageCount; i++)
    {
        string file = string.Format(ArtifactsDir + "Page_{0}.html", i);
    }
}

/// <summary>
/// Custom PageFileName is specified.
/// </summary>
private class CustomPageFileNamePageSavingCallback : IPageSavingCallback
{
    public void PageSaving(PageSavingArgs args)
    {
        // Specify name of the output file for the current page.
        args.PageFileName = string.Format(ArtifactsDir + "Page_{0}.html", args.PageIndex);
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IPageSavingCallback Members | Aspose.Words.Saving Namespace


IPageSavingCallback Members

IPageSavingCallback overview

Public Instance Methods

PageSaving Called when Aspose.Words saves a separate page to fixed page formats.

See Also

IPageSavingCallback Interface | Aspose.Words.Saving Namespace


IPageSavingCallback Methods

The methods of the IPageSavingCallback interface are listed below. For a complete list of IPageSavingCallback interface members, see the IPageSavingCallback Members topic.

Public Instance Methods

PageSaving Called when Aspose.Words saves a separate page to fixed page formats.

See Also

IPageSavingCallback Interface | Aspose.Words.Saving Namespace


IPageSavingCallback.PageSaving Method

Called when Aspose.Words saves a separate page to fixed page formats.

[Visual Basic]
Sub PageSaving( _
ByVal args As PageSavingArgs _
)
[C#]
void PageSaving(
PageSavingArgs args
);

See Also

IPageSavingCallback Interface | Aspose.Words.Saving Namespace


IResourceSavingCallback Interface

Implement this interface if you want to control how Aspose.Words saves external resources (images, fonts and css) when saving a document to fixed page HTML or SVG.

For a list of all members of this type, see IResourceSavingCallback Members.

[Visual Basic]
Public Interface IResourceSavingCallback
[C#]
public interface IResourceSavingCallback

Example

Shows how used target machine fonts to display the document.

[C#]

public void UsingMachineFonts()
{
    Document doc = new Document(MyDir + "Font.DisappearingBulletPoints.doc");

    HtmlFixedSaveOptions saveOptions = new HtmlFixedSaveOptions
    {
        UseTargetMachineFonts = true,
        FontFormat = ExportFontFormat.Ttf,
        ExportEmbeddedFonts = false,
        ResourceSavingCallback = new ResourceSavingCallback()
    };

    doc.Save(ArtifactsDir + "UseMachineFonts.html", saveOptions);
}

private class ResourceSavingCallback : IResourceSavingCallback
{
    /// <summary>
    /// Called when Aspose.Words saves an external resource to fixed page HTML or SVG.
    /// </summary>
    public void ResourceSaving(ResourceSavingArgs args)
    {
        args.ResourceStream = new MemoryStream();
        args.KeepResourceStreamOpen = true;

        string extension = Path.GetExtension(args.ResourceFileName);
        switch (extension)
        {
            case ".ttf":
            case ".woff":
            {
                Assert.Fail(
                    "'ResourceSavingCallback' is not fired for fonts when 'UseTargetMachineFonts' is true");
                break;
            }
        }
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

IResourceSavingCallback Members | Aspose.Words.Saving Namespace


IResourceSavingCallback Members

IResourceSavingCallback overview

Public Instance Methods

ResourceSaving Called when Aspose.Words saves an external resource to fixed page HTML or SVG formats.

See Also

IResourceSavingCallback Interface | Aspose.Words.Saving Namespace


IResourceSavingCallback Methods

The methods of the IResourceSavingCallback interface are listed below. For a complete list of IResourceSavingCallback interface members, see the IResourceSavingCallback Members topic.

Public Instance Methods

ResourceSaving Called when Aspose.Words saves an external resource to fixed page HTML or SVG formats.

See Also

IResourceSavingCallback Interface | Aspose.Words.Saving Namespace


IResourceSavingCallback.ResourceSaving Method

Called when Aspose.Words saves an external resource to fixed page HTML or SVG formats.

[Visual Basic]
Sub ResourceSaving( _
ByVal args As ResourceSavingArgs _
)
[C#]
void ResourceSaving(
ResourceSavingArgs args
);

Example

Shows how used target machine fonts to display the document.

[C#]

public void UsingMachineFonts()
{
    Document doc = new Document(MyDir + "Font.DisappearingBulletPoints.doc");

    HtmlFixedSaveOptions saveOptions = new HtmlFixedSaveOptions
    {
        UseTargetMachineFonts = true,
        FontFormat = ExportFontFormat.Ttf,
        ExportEmbeddedFonts = false,
        ResourceSavingCallback = new ResourceSavingCallback()
    };

    doc.Save(ArtifactsDir + "UseMachineFonts.html", saveOptions);
}

private class ResourceSavingCallback : IResourceSavingCallback
{
    /// <summary>
    /// Called when Aspose.Words saves an external resource to fixed page HTML or SVG.
    /// </summary>
    public void ResourceSaving(ResourceSavingArgs args)
    {
        args.ResourceStream = new MemoryStream();
        args.KeepResourceStreamOpen = true;

        string extension = Path.GetExtension(args.ResourceFileName);
        switch (extension)
        {
            case ".ttf":
            case ".woff":
            {
                Assert.Fail(
                    "'ResourceSavingCallback' is not fired for fonts when 'UseTargetMachineFonts' is true");
                break;
            }
        }
    }
}

See Also

IResourceSavingCallback Interface | Aspose.Words.Saving Namespace


MetafileRenderingMode Enumeration

Specifies how Aspose.Words should render WMF and EMF metafiles.

[Visual Basic]
Public Enum MetafileRenderingMode
[C#]
public enum MetafileRenderingMode

Example

Shows added fallback to bitmap rendering and changing type of warnings about unsupported metafile records

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.HandleRasterWarnings.doc");

    MetafileRenderingOptions metafileRenderingOptions =
        new MetafileRenderingOptions
        {
            EmulateRasterOperations = false,
            RenderingMode = MetafileRenderingMode.VectorWithFallback
        };

    // If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
    HandleDocumentWarnings callback = new HandleDocumentWarnings();
    doc.WarningCallback = callback;

    PdfSaveOptions saveOptions = new PdfSaveOptions();
    saveOptions.MetafileRenderingOptions = metafileRenderingOptions;

    doc.Save(ArtifactsDir + "PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);

    Assert.AreEqual(1, callback.mWarnings.Count);
    Assert.True(callback.mWarnings[0].Description.Contains("R2_XORPEN"));
}

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        //For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
        if (info.WarningType == WarningType.MinorFormattingLoss)
        {
            Console.WriteLine("Unsupported operation: " + info.Description);
            mWarnings.Warning(info);
        }
    }

    public WarningInfoCollection mWarnings = new WarningInfoCollection();
}

Members

Member Name | Description | Value
VectorWithFallback | Aspose.Words tries to render a metafile as vector graphics. If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap. | 0
Vector | Aspose.Words renders a metafile as vector graphics. | 1
Bitmap | Aspose.Words invokes GDI+ to render a metafile to a bitmap and then saves the bitmap to the output document. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


MetafileRenderingOptions Class

Allows to specify additional metafile rendering options.

For a list of all members of this type, see MetafileRenderingOptions Members.

System.Object
Aspose.Words.Saving.MetafileRenderingOptions

[Visual Basic]
Public Class MetafileRenderingOptions
[C#]
public class MetafileRenderingOptions

Example

Shows added fallback to bitmap rendering and changing type of warnings about unsupported metafile records

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.HandleRasterWarnings.doc");

    MetafileRenderingOptions metafileRenderingOptions =
        new MetafileRenderingOptions
        {
            EmulateRasterOperations = false,
            RenderingMode = MetafileRenderingMode.VectorWithFallback
        };

    // If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
    HandleDocumentWarnings callback = new HandleDocumentWarnings();
    doc.WarningCallback = callback;

    PdfSaveOptions saveOptions = new PdfSaveOptions();
    saveOptions.MetafileRenderingOptions = metafileRenderingOptions;

    doc.Save(ArtifactsDir + "PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);

    Assert.AreEqual(1, callback.mWarnings.Count);
    Assert.True(callback.mWarnings[0].Description.Contains("R2_XORPEN"));
}

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        //For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
        if (info.WarningType == WarningType.MinorFormattingLoss)
        {
            Console.WriteLine("Unsupported operation: " + info.Description);
            mWarnings.Warning(info);
        }
    }

    public WarningInfoCollection mWarnings = new WarningInfoCollection();
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MetafileRenderingOptions Members | Aspose.Words.Saving Namespace


MetafileRenderingOptions Members

MetafileRenderingOptions overview

Public Instance Constructors

MetafileRenderingOptions Constructor Initializes a new instance of the MetafileRenderingOptions class.

Public Instance Properties

EmfPlusDualRenderingMode | Gets or sets a value determining how EMF+ Dual metafiles should be rendered.
EmulateRasterOperations | Gets or sets a value determining whether or not the raster operations should be emulated.
RenderingMode | Gets or sets a value determining how metafile images should be rendered.
ScaleWmfFontsToMetafileSize | Gets or sets a value determining whether or not to scale fonts in WMF metafile according to metafile size on the page.
UseEmfEmbeddedToWmf | Gets or sets a value determining how WMF metafiles with embedded EMF metafiles should be rendered.

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Constructor

Initializes a new instance of the MetafileRenderingOptions class.

[Visual Basic]
Public Sub New()
[C#]
public MetafileRenderingOptions();

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Properties

The properties of the MetafileRenderingOptions class are listed below. For a complete list of MetafileRenderingOptions class members, see the MetafileRenderingOptions Members topic.

Public Instance Properties

EmfPlusDualRenderingMode | Gets or sets a value determining how EMF+ Dual metafiles should be rendered.
EmulateRasterOperations | Gets or sets a value determining whether or not the raster operations should be emulated.
RenderingMode | Gets or sets a value determining how metafile images should be rendered.
ScaleWmfFontsToMetafileSize | Gets or sets a value determining whether or not to scale fonts in WMF metafile according to metafile size on the page.
UseEmfEmbeddedToWmf | Gets or sets a value determining how WMF metafiles with embedded EMF metafiles should be rendered.

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


EmfPlusDualRenderingMode Property

Aspose.Words

MetafileRenderingOptions.EmfPlusDualRenderingMode Property

Gets or sets a value determining how EMF+ Dual metafiles should be rendered.

[Visual Basic]
Public Property EmfPlusDualRenderingMode As EmfPlusDualRenderingMode
[C#]
public EmfPlusDualRenderingMode EmfPlusDualRenderingMode {get; set;}

Remarks

EMF+ Dual metafiles contains both EMF+ and EMF parts. MS Word and GDI+ always renders EMF+ part. Aspose.Words currently doesn't fully supports all EMF+ records and in some cases rendering result of EMF part looks better then rendering result of EMF+ part.

This option is used only when metafile is rendered as vector graphics. When metafile is rendered to bitmap, EMF+ part is always used.

The default value is EmfPlusWithFallback.

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


EmulateRasterOperations Property

Aspose.Words

MetafileRenderingOptions.EmulateRasterOperations Property

Gets or sets a value determining whether or not the raster operations should be emulated.

[Visual Basic]
Public Property EmulateRasterOperations As Boolean
[C#]
public bool EmulateRasterOperations {get; set;}

Remarks

Specific raster operations could be used in metafiles. They can not be rendered directly to vector graphics. Emulating raster operations requires partial rasterization of the resulting vector graphics which may affect the metafile rendering performance.

When this value is set to true, Aspose.Words emulates the raster operations. The resulting output maybe partially rasterized and performance might be slower.

When this value is set to false, Aspose.Words does not emulate the raster operations. When Aspose.Words encounters a raster operation in a metafile it fallbacks to rendering the metafile into a bitmap by using the operating system.

This option is used only when metafile is rendered as vector graphics.

The default value is true.

Example

Shows added fallback to bitmap rendering and changing type of warnings about unsupported metafile records

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.HandleRasterWarnings.doc");

    MetafileRenderingOptions metafileRenderingOptions =
        new MetafileRenderingOptions
        {
            EmulateRasterOperations = false,
            RenderingMode = MetafileRenderingMode.VectorWithFallback
        };

    // If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
    HandleDocumentWarnings callback = new HandleDocumentWarnings();
    doc.WarningCallback = callback;

    PdfSaveOptions saveOptions = new PdfSaveOptions();
    saveOptions.MetafileRenderingOptions = metafileRenderingOptions;

    doc.Save(ArtifactsDir + "PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);

    Assert.AreEqual(1, callback.mWarnings.Count);
    Assert.True(callback.mWarnings[0].Description.Contains("R2_XORPEN"));
}

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        //For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
        if (info.WarningType == WarningType.MinorFormattingLoss)
        {
            Console.WriteLine("Unsupported operation: " + info.Description);
            mWarnings.Warning(info);
        }
    }

    public WarningInfoCollection mWarnings = new WarningInfoCollection();
}

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


RenderingMode Property

Aspose.Words

MetafileRenderingOptions.RenderingMode Property

Gets or sets a value determining how metafile images should be rendered.

[Visual Basic]
Public Property RenderingMode As MetafileRenderingMode
[C#]
public MetafileRenderingMode RenderingMode {get; set;}

Remarks

The default value depends on the save format. For images it is Bitmap. For other formats it is VectorWithFallback.

Example

Shows added fallback to bitmap rendering and changing type of warnings about unsupported metafile records

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.HandleRasterWarnings.doc");

    MetafileRenderingOptions metafileRenderingOptions =
        new MetafileRenderingOptions
        {
            EmulateRasterOperations = false,
            RenderingMode = MetafileRenderingMode.VectorWithFallback
        };

    // If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
    HandleDocumentWarnings callback = new HandleDocumentWarnings();
    doc.WarningCallback = callback;

    PdfSaveOptions saveOptions = new PdfSaveOptions();
    saveOptions.MetafileRenderingOptions = metafileRenderingOptions;

    doc.Save(ArtifactsDir + "PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);

    Assert.AreEqual(1, callback.mWarnings.Count);
    Assert.True(callback.mWarnings[0].Description.Contains("R2_XORPEN"));
}

public class HandleDocumentWarnings : IWarningCallback
{
    /// <summary>
    /// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    /// potential issue during document processing. The callback can be set to listen for warnings generated during document
    /// load and/or document save.
    /// </summary>
    public void Warning(WarningInfo info)
    {
        //For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
        if (info.WarningType == WarningType.MinorFormattingLoss)
        {
            Console.WriteLine("Unsupported operation: " + info.Description);
            mWarnings.Warning(info);
        }
    }

    public WarningInfoCollection mWarnings = new WarningInfoCollection();
}

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


ScaleWmfFontsToMetafileSize Property

Aspose.Words

MetafileRenderingOptions.ScaleWmfFontsToMetafileSize Property

Gets or sets a value determining whether or not to scale fonts in WMF metafile according to metafile size on the page.

[Visual Basic]
Public Property ScaleWmfFontsToMetafileSize As Boolean
[C#]
public bool ScaleWmfFontsToMetafileSize {get; set;}

Remarks

When WMF metafiles are displayed in MS Word, fonts may be scaled according to actual metafile size on the page.

When this value is set to true, Aspose.Words emulates font scaling according to metafile size on the page.

When this value is set to false, Aspose.Words displays the fonts as metafile is rendered to its default size.

This option is used only when metafile is rendered as vector graphics.

The default value is true.

Example

Shows how to WMF fonts scaling according to metafile size on the page

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.FontsScaledToMetafileSize.docx");

// There is a several options for this:
// 'True' - Aspose.Words emulates font scaling according to metafile size on the page.
// 'False' - Aspose.Words displays the fonts as metafile is rendered to its default size.
// Use 'False' option is used only when metafile is rendered as vector graphics.
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.MetafileRenderingOptions.ScaleWmfFontsToMetafileSize = true;

doc.Save(ArtifactsDir + "PdfSaveOptions.FontsScaledToMetafileSize.pdf", saveOptions);

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


UseEmfEmbeddedToWmf Property

Aspose.Words

MetafileRenderingOptions.UseEmfEmbeddedToWmf Property

Gets or sets a value determining how WMF metafiles with embedded EMF metafiles should be rendered.

[Visual Basic]
Public Property UseEmfEmbeddedToWmf As Boolean
[C#]
public bool UseEmfEmbeddedToWmf {get; set;}

Remarks

WMF metafiles could contain embedded EMF data. MS Word in most cases uses embedded EMF data. GDI+ always uses WMF data.

When this value is set to true, Aspose.Words uses embedded EMF data when rendering.

When this value is set to false, Aspose.Words uses WMF data when rendering.

This option is used only when metafile is rendered as vector graphics. When metafile is rendered to bitmap, WMF data is always used.

The default value is true.

See Also

MetafileRenderingOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Enumeration

Indicates the symbol set that is used to represent numbers while rendering to fixed page formats.

[Visual Basic]
Public Enum NumeralFormat
[C#]
public enum NumeralFormat

Example

Demonstrates how to set the numeral format used when saving to PDF.

[C#]

PdfSaveOptions options = new PdfSaveOptions();
options.NumeralFormat = NumeralFormat.Context;

Members

Member Name | Description | Value
European | European numerals: 0123456789. | 0
ArabicIndic | Numerals used in Arabic: ٠١٢٣٤٥٦٧٨٩. Unicode range U+0660 - u+0669. | 1
EasternArabicIndic | Numerals used in Persian and Urdu: ۰۱۲۳۴۵۶۷۸۹. Unicode range U+06F0 - u+06F9. | 2
Context | Symbol set is decided from context(locale and RTL property). | 3
System | THIS OPTION IS NOT SUPPORTED. Symbol set is decided from regional settings. | 4

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


OdtSaveMeasureUnit Enumeration

Specified units of measure to apply to measurable document content such as shape, widths and other during saving.

[Visual Basic]
Public Enum OdtSaveMeasureUnit
[C#]
public enum OdtSaveMeasureUnit

Example

Shows how to work with units of measure of document content

[C#]

Document doc = new Document(MyDir + "OdtSaveOptions.MeasureUnit.docx");

// Open Office uses centimeters, MS Office uses inches
OdtSaveOptions saveOptions = new OdtSaveOptions();
saveOptions.MeasureUnit = OdtSaveMeasureUnit.Inches;

doc.Save(ArtifactsDir + "OdtSaveOptions.MeasureUnit.odt");

Members

Member Name | Description | Value
Centimeters | Specifies that the document content is saved using centimeters. | 0
Inches | Specifies that the document content is saved using inches. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


OdtSaveOptions Class

Can be used to specify additional options when saving a document into the Odt or Ott format.

For a list of all members of this type, see OdtSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.OdtSaveOptions

[Visual Basic]
Public Class OdtSaveOptions
Inherits SaveOptions
[C#]
public class OdtSaveOptions : SaveOptions

Remarks

At the moment provides only the SaveFormat property, but in the future will have other options added, such as an encryption password or digital signature settings.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OdtSaveOptions Members | Aspose.Words.Saving Namespace


OdtSaveOptions Members

OdtSaveOptions overview

Public Instance Constructors

OdtSaveOptions Overloaded. Initializes a new instance of the OdtSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
IsStrictSchema11 | Specifies whether export should correspond to ODT specification 1.1 strictly. OOo 3.0 displays files correctly when they contain elements and attributes of ODT 1.2. Use "false" for this purpose, or "true" for strict conformity of specification 1.1. The default value is false.
MeasureUnit | Allows to specify units of measure to apply to document content. The default value is Centimeters
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
Password | Gets or sets a password to encrypt document.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Odt or Ott.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


OdtSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Odt format.

Overload List

Initializes a new instance of this class that can be used to save a document in the Odt format.

public OdtSaveOptions();

Initializes a new instance of this class that can be used to save a document in the Odt or Ott format.

public OdtSaveOptions(SaveFormat);

Initializes a new instance of this class that can be used to save a document in the Odt format encrypted with a password.

public OdtSaveOptions(string);

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


OdtSaveOptions Constructor ()

Initializes a new instance of this class that can be used to save a document in the Odt format.

[Visual Basic]
Overloads Public Sub New()
[C#]
public OdtSaveOptions();

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace | OdtSaveOptions Constructor Overload List


OdtSaveOptions Constructor (String)

Initializes a new instance of this class that can be used to save a document in the Odt format encrypted with a password.

[Visual Basic]
Overloads Public Sub New( _
ByVal password As String _
)
[C#]
public OdtSaveOptions(
string password
);

Example

Shows how to load and change odt/ott encrypted document

[C#]

Document doc = new Document(MyDir + "OdtSaveOptions.LoadDocumentEncryptedWithAPassword" +
                            FileFormatUtil.SaveFormatToExtension(saveFormat),
    new LoadOptions("@sposeEncrypted_1145"));

DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
builder.Writeln("Encrypted document after changes.");

// Saving document using new instance of OdtSaveOptions
doc.Save(ArtifactsDir + "OdtSaveOptions.LoadDocumentEncryptedWithAPassword" +
         FileFormatUtil.SaveFormatToExtension(saveFormat), new OdtSaveOptions("@sposeEncrypted_1145"));

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace | OdtSaveOptions Constructor Overload List


OdtSaveOptions Constructor (SaveFormat)

Initializes a new instance of this class that can be used to save a document in the Odt or Ott format.

[Visual Basic]
Overloads Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public OdtSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be Odt or Ott.

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace | OdtSaveOptions Constructor Overload List


OdtSaveOptions Properties

The properties of the OdtSaveOptions class are listed below. For a complete list of OdtSaveOptions class members, see the OdtSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
IsStrictSchema11 | Specifies whether export should correspond to ODT specification 1.1 strictly. OOo 3.0 displays files correctly when they contain elements and attributes of ODT 1.2. Use "false" for this purpose, or "true" for strict conformity of specification 1.1. The default value is false.
MeasureUnit | Allows to specify units of measure to apply to document content. The default value is Centimeters
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
Password | Gets or sets a password to encrypt document.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Odt or Ott.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


IsStrictSchema11 Property

Aspose.Words

OdtSaveOptions.IsStrictSchema11 Property

Specifies whether export should correspond to ODT specification 1.1 strictly. OOo 3.0 displays files correctly when they contain elements and attributes of ODT 1.2. Use "false" for this purpose, or "true" for strict conformity of specification 1.1. The default value is false.

[Visual Basic]
Public Property IsStrictSchema11 As Boolean
[C#]
public bool IsStrictSchema11 {get; set;}

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


MeasureUnit Property

Aspose.Words

OdtSaveOptions.MeasureUnit Property

Allows to specify units of measure to apply to document content. The default value is Centimeters

[Visual Basic]
Public Property MeasureUnit As OdtSaveMeasureUnit
[C#]
public OdtSaveMeasureUnit MeasureUnit {get; set;}

Remarks

Open Office uses centimeters when specifying lengths, widths and other measurable formatting and content properties in documents whereas MS Office uses inches.

Example

Shows how to work with units of measure of document content

[C#]

Document doc = new Document(MyDir + "OdtSaveOptions.MeasureUnit.docx");

// Open Office uses centimeters, MS Office uses inches
OdtSaveOptions saveOptions = new OdtSaveOptions();
saveOptions.MeasureUnit = OdtSaveMeasureUnit.Inches;

doc.Save(ArtifactsDir + "OdtSaveOptions.MeasureUnit.odt");

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


Password Property

Aspose.Words

OdtSaveOptions.Password Property

Gets or sets a password to encrypt document.

[Visual Basic]
Public Property Password As String
[C#]
public string Password {get; set;}

Remarks

In order to save document without encryption this property should be null or empty string.

Example

Shows how to encrypted your odt/ott documents with a password.

[C#]

Document doc = new Document(MyDir + "Document.docx");

OdtSaveOptions saveOptions = new OdtSaveOptions(saveFormat);
saveOptions.Password = "@sposeEncrypted_1145";

// Saving document using password property of OdtSaveOptions
doc.Save(ArtifactsDir + "OdtSaveOptions.SaveDocumentEncryptedWithAPassword" +
         FileFormatUtil.SaveFormatToExtension(saveFormat), saveOptions);

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

OdtSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can be Odt or Ott.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

OdtSaveOptions Class | Aspose.Words.Saving Namespace


OoxmlCompliance Enumeration

Allows to specify which OOXML specification will be used when saving in the DOCX format.

[Visual Basic]
Public Enum OoxmlCompliance
[C#]
public enum OoxmlCompliance

Example

Shows conversion VML shapes to DML using ISO/IEC 29500:2008 Strict compliance level

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set Word2003 version for document, for inserting image as VML shape
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2003);

builder.InsertImage(ImageDir + "dotnet-logo.png");

// Loop through all single shapes inside document.
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{
    Console.WriteLine(shape.MarkupLanguage);
}

// Iso29500_2008 does not allow VML shapes
// You need to use OoxmlCompliance.Iso29500_2008_Strict for converting VML to DML shapes
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions
{
    Compliance = OoxmlCompliance.Iso29500_2008_Strict,
    SaveFormat = SaveFormat.Docx
};

Members

Member Name | Description | Value
Ecma376_2006 | ECMA-376 1st Edition, 2006. | 0
Iso29500_2008_Transitional | ISO/IEC 29500:2008 Transitional compliance level. | 1
Iso29500_2008_Strict | ISO/IEC 29500:2008 Strict compliance level. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


OoxmlSaveOptions Class

Can be used to specify additional options when saving a document into the Docx, Docm, Dotx, Dotm or FlatOpc format.

For a list of all members of this type, see OoxmlSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.OoxmlSaveOptions

[Visual Basic]
Public Class OoxmlSaveOptions
Inherits SaveOptions
[C#]
public class OoxmlSaveOptions : SaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OoxmlSaveOptions Members | Aspose.Words.Saving Namespace


OoxmlSaveOptions Members

OoxmlSaveOptions overview

Public Instance Constructors

OoxmlSaveOptions Overloaded. Initializes a new instance of the OoxmlSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
Compliance | Specifies the OOXML version for the output document. The default value is Ecma376_2006.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
KeepLegacyControlChars | Keeps original representation of legacy control characters.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
Password | Gets/sets a password to encrypt document using ECMA376 Standard encryption algorithm.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Docx, Docm, Dotx, Dotm or FlatOpc.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


OoxmlSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Docx format.

Overload List

Initializes a new instance of this class that can be used to save a document in the Docx format.

public OoxmlSaveOptions();

Initializes a new instance of this class that can be used to save a document in the Docx, Docm, Dotx, Dotm or FlatOpc format.

public OoxmlSaveOptions(SaveFormat);

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


OoxmlSaveOptions Constructor ()

Initializes a new instance of this class that can be used to save a document in the Docx format.

[Visual Basic]
Overloads Public Sub New()
[C#]
public OoxmlSaveOptions();

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace | OoxmlSaveOptions Constructor Overload List


OoxmlSaveOptions Constructor (SaveFormat)

Initializes a new instance of this class that can be used to save a document in the Docx, Docm, Dotx, Dotm or FlatOpc format.

[Visual Basic]
Overloads Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public OoxmlSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be Docx, Docm, Dotx, Dotm or FlatOpc.

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace | OoxmlSaveOptions Constructor Overload List


OoxmlSaveOptions Properties

The properties of the OoxmlSaveOptions class are listed below. For a complete list of OoxmlSaveOptions class members, see the OoxmlSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
Compliance | Specifies the OOXML version for the output document. The default value is Ecma376_2006.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
KeepLegacyControlChars | Keeps original representation of legacy control characters.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
Password | Gets/sets a password to encrypt document using ECMA376 Standard encryption algorithm.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can be Docx, Docm, Dotx, Dotm or FlatOpc.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


Compliance Property

Aspose.Words

OoxmlSaveOptions.Compliance Property

Specifies the OOXML version for the output document. The default value is Ecma376_2006.

[Visual Basic]
Public Property Compliance As OoxmlCompliance
[C#]
public OoxmlCompliance Compliance {get; set;}

Example

Shows conversion VML shapes to DML using ISO/IEC 29500:2008 Strict compliance level

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set Word2003 version for document, for inserting image as VML shape
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2003);

builder.InsertImage(ImageDir + "dotnet-logo.png");

// Loop through all single shapes inside document.
foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true).OfType<Shape>())
{
    Console.WriteLine(shape.MarkupLanguage);
}

// Iso29500_2008 does not allow VML shapes
// You need to use OoxmlCompliance.Iso29500_2008_Strict for converting VML to DML shapes
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions
{
    Compliance = OoxmlCompliance.Iso29500_2008_Strict,
    SaveFormat = SaveFormat.Docx
};

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


KeepLegacyControlChars Property

Aspose.Words

OoxmlSaveOptions.KeepLegacyControlChars Property

Keeps original representation of legacy control characters.

[Visual Basic]
Public Property KeepLegacyControlChars As Boolean
[C#]
public bool KeepLegacyControlChars {get; set;}

Example

Shows how to support legacy control characters when converting to .docx

[C#]

Document doc = new Document(MyDir + "OoxmlSaveOptions.KeepLegacyControlChars.doc");

// Note that only one legacy character (ShortDateTime) is supported which declared in the "DOC" format
OoxmlSaveOptions so = new OoxmlSaveOptions();
so.KeepLegacyControlChars = true;

doc.Save(ArtifactsDir + "OoxmlSaveOptions.KeepLegacyControlChars.docx", so);

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


Password Property

Aspose.Words

OoxmlSaveOptions.Password Property

Gets/sets a password to encrypt document using ECMA376 Standard encryption algorithm.

[Visual Basic]
Public Property Password As String
[C#]
public string Password {get; set;}

Remarks

In order to save document without encryption this property should be null or empty string.

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

OoxmlSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can be Docx, Docm, Dotx, Dotm or FlatOpc.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

OoxmlSaveOptions Class | Aspose.Words.Saving Namespace


OutlineOptions Class

Allows to specify outline options.

For a list of all members of this type, see OutlineOptions Members.

System.Object
Aspose.Words.Saving.OutlineOptions

[Visual Basic]
Public Class OutlineOptions
[C#]
public class OutlineOptions

Example

Shows how bookmarks in headers/footers are exported to pdf

[C#]

Document doc = new Document(MyDir + "PdfSaveOption.HeaderFooterBookmarksExportMode.docx");

// You can specify how bookmarks in headers/footers are exported.
// There is a several options for this:
// "None" - Bookmarks in headers/footers are not exported.
// "First" - Only bookmark in first header/footer of the section is exported.
// "All" - Bookmarks in all headers/footers are exported.
PdfSaveOptions saveOptions = new PdfSaveOptions
{
    HeaderFooterBookmarksExportMode = headerFooterBookmarksExportMode,
    OutlineOptions = { DefaultBookmarksOutlineLevel = 1 }
};
doc.Save(ArtifactsDir + "PdfSaveOption.HeaderFooterBookmarksExportMode.pdf", saveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OutlineOptions Members | Aspose.Words.Saving Namespace


OutlineOptions Members

OutlineOptions overview

Public Instance Constructors

OutlineOptions Constructor Initializes a new instance of the OutlineOptions class.

Public Instance Properties

BookmarksOutlineLevels | Allows to specify individual bookmarks outline level.
CreateMissingOutlineLevels | Gets or sets a value determining whether or not to create missing outline levels when the document is exported. Default value for this property is false.
CreateOutlinesForHeadingsInTables | Specifies whether or not to create outlines for headings (paragraphs formatted with the Heading styles) inside tables.
DefaultBookmarksOutlineLevel | Specifies the default level in the document outline at which to display Word bookmarks.
ExpandedOutlineLevels | Specifies how many levels in the document outline to show expanded when the file is viewed.
HeadingsOutlineLevels | Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the document outline.

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


OutlineOptions Constructor

Initializes a new instance of the OutlineOptions class.

[Visual Basic]
Public Sub New()
[C#]
public OutlineOptions();

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


OutlineOptions Properties

The properties of the OutlineOptions class are listed below. For a complete list of OutlineOptions class members, see the OutlineOptions Members topic.

Public Instance Properties

BookmarksOutlineLevels | Allows to specify individual bookmarks outline level.
CreateMissingOutlineLevels | Gets or sets a value determining whether or not to create missing outline levels when the document is exported. Default value for this property is false.
CreateOutlinesForHeadingsInTables | Specifies whether or not to create outlines for headings (paragraphs formatted with the Heading styles) inside tables.
DefaultBookmarksOutlineLevel | Specifies the default level in the document outline at which to display Word bookmarks.
ExpandedOutlineLevels | Specifies how many levels in the document outline to show expanded when the file is viewed.
HeadingsOutlineLevels | Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the document outline.

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevels Property

Aspose.Words

OutlineOptions.BookmarksOutlineLevels Property

Allows to specify individual bookmarks outline level.

[Visual Basic]
Public ReadOnly Property BookmarksOutlineLevels As BookmarksOutlineLevelCollection
[C#]
public BookmarksOutlineLevelCollection BookmarksOutlineLevels {get;}

Remarks

If bookmark level is not specified in this collection then DefaultBookmarksOutlineLevel value is used.

Example

Shows how adding bookmarks outlines with whitespaces(pdf, xps)

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Add bookmarks with whitespaces. MS Word formats (like doc, docx) does not support bookmarks with whitespaces by default
// and all whitespaces in the bookmarks were replaced with underscores. If you need to use bookmarks in PDF or XPS outlines, you can use them with whitespaces.
builder.StartBookmark("My Bookmark");
builder.Writeln("Text inside a bookmark.");

builder.StartBookmark("Nested Bookmark");
builder.Writeln("Text inside a NestedBookmark.");
builder.EndBookmark("Nested Bookmark");

builder.Writeln("Text after Nested Bookmark.");
builder.EndBookmark("My Bookmark");

// Specify bookmarks outline level. If you are using xps format, just use XpsSaveOptions.
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.OutlineOptions.BookmarksOutlineLevels.Add("My Bookmark", 1);
pdfSaveOptions.OutlineOptions.BookmarksOutlineLevels.Add("Nested Bookmark", 2);

doc.Save(ArtifactsDir + "Bookmarks.WhiteSpaces.pdf", pdfSaveOptions);

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


CreateMissingOutlineLevels Property

Aspose.Words

OutlineOptions.CreateMissingOutlineLevels Property

Gets or sets a value determining whether or not to create missing outline levels when the document is exported.

Default value for this property is false.

[Visual Basic]
Public Property CreateMissingOutlineLevels As Boolean
[C#]
public bool CreateMissingOutlineLevels {get; set;}

Example

Shows how to create missing outline levels saving the document in PDF

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Creating TOC entries
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading 1");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4;

builder.Writeln("Heading 1.1.1.1");
builder.Writeln("Heading 1.1.1.2");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading9;

builder.Writeln("Heading 1.1.1.1.1.1.1.1.1");
builder.Writeln("Heading 1.1.1.1.1.1.1.1.2");

// Create "PdfSaveOptions" with some mandatory parameters
// "HeadingsOutlineLevels" specifies how many levels of headings to include in the document outline
// "CreateMissingOutlineLevels" determining whether or not to create missing heading levels
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.OutlineOptions.HeadingsOutlineLevels = 9;
pdfSaveOptions.OutlineOptions.CreateMissingOutlineLevels = true;
pdfSaveOptions.SaveFormat = SaveFormat.Pdf;

doc.Save(ArtifactsDir + "CreateMissingOutlineLevels.pdf", pdfSaveOptions);

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


CreateOutlinesForHeadingsInTables Property

Aspose.Words

OutlineOptions.CreateOutlinesForHeadingsInTables Property

Specifies whether or not to create outlines for headings (paragraphs formatted with the Heading styles) inside tables.

[Visual Basic]
Public Property CreateOutlinesForHeadingsInTables As Boolean
[C#]
public bool CreateOutlinesForHeadingsInTables {get; set;}

Remarks

Default value is false.

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


DefaultBookmarksOutlineLevel Property

Aspose.Words

OutlineOptions.DefaultBookmarksOutlineLevel Property

Specifies the default level in the document outline at which to display Word bookmarks.

[Visual Basic]
Public Property DefaultBookmarksOutlineLevel As Integer
[C#]
public int DefaultBookmarksOutlineLevel {get; set;}

Remarks

Individual bookmarks level could be specified using BookmarksOutlineLevels property.

Specify 0 and Word bookmarks will not be displayed in the document outline. Specify 1 and Word bookmarks will be displayed in the document outline at level 1; 2 for level 2 and so on.

Default is 0. Valid range is 0 to 9.

Example

Shows how bookmarks in headers/footers are exported to pdf

[C#]

Document doc = new Document(MyDir + "PdfSaveOption.HeaderFooterBookmarksExportMode.docx");

// You can specify how bookmarks in headers/footers are exported.
// There is a several options for this:
// "None" - Bookmarks in headers/footers are not exported.
// "First" - Only bookmark in first header/footer of the section is exported.
// "All" - Bookmarks in all headers/footers are exported.
PdfSaveOptions saveOptions = new PdfSaveOptions
{
    HeaderFooterBookmarksExportMode = headerFooterBookmarksExportMode,
    OutlineOptions = { DefaultBookmarksOutlineLevel = 1 }
};
doc.Save(ArtifactsDir + "PdfSaveOption.HeaderFooterBookmarksExportMode.pdf", saveOptions);

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


ExpandedOutlineLevels Property

Aspose.Words

OutlineOptions.ExpandedOutlineLevels Property

Specifies how many levels in the document outline to show expanded when the file is viewed.

[Visual Basic]
Public Property ExpandedOutlineLevels As Integer
[C#]
public int ExpandedOutlineLevels {get; set;}

Remarks

Note that this options will not work when saving to XPS.

Specify 0 and the document outline will be collapsed; specify 1 and the first level items in the outline will be expanded and so on.

Default is 0. Valid range is 0 to 9.

Example

Converts a whole document to PDF with three levels in the document outline.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.OutlineOptions.HeadingsOutlineLevels = 3;
options.OutlineOptions.ExpandedOutlineLevels = 1;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfWithOutline.pdf", options);

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


HeadingsOutlineLevels Property

Aspose.Words

OutlineOptions.HeadingsOutlineLevels Property

Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the document outline.

[Visual Basic]
Public Property HeadingsOutlineLevels As Integer
[C#]
public int HeadingsOutlineLevels {get; set;}

Remarks

Specify 0 for no headings in the outline; specify 1 for one level of headings in the outline and so on.

Default is 0. Valid range is 0 to 9.

Example

Converts a whole document to PDF with three levels in the document outline.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.OutlineOptions.HeadingsOutlineLevels = 3;
options.OutlineOptions.ExpandedOutlineLevels = 1;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfWithOutline.pdf", options);

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


PageSavingArgs Class

Provides data for the PageSaving event.

For a list of all members of this type, see PageSavingArgs Members.

System.Object
Aspose.Words.Saving.PageSavingArgs

[Visual Basic]
Public Class PageSavingArgs
[C#]
public class PageSavingArgs

Example

Shows how separate pages are saved when a document is exported to fixed page format.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

    HtmlFixedSaveOptions htmlFixedSaveOptions =
        new HtmlFixedSaveOptions { PageIndex = 0, PageCount = doc.PageCount };
    htmlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback();

    doc.Save(ArtifactsDir + "Rendering.html", htmlFixedSaveOptions);

    string[] filePaths = Directory.GetFiles(ArtifactsDir + "", "Page_*.html");

    for (int i = 0; i < doc.PageCount; i++)
    {
        string file = string.Format(ArtifactsDir + "Page_{0}.html", i);
    }
}

/// <summary>
/// Custom PageFileName is specified.
/// </summary>
private class CustomPageFileNamePageSavingCallback : IPageSavingCallback
{
    public void PageSaving(PageSavingArgs args)
    {
        // Specify name of the output file for the current page.
        args.PageFileName = string.Format(ArtifactsDir + "Page_{0}.html", args.PageIndex);
    }
}

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PageSavingArgs Members | Aspose.Words.Saving Namespace


PageSavingArgs Members

PageSavingArgs overview

Public Instance Constructors

PageSavingArgs Constructor Initializes a new instance of the PageSavingArgs class.

Public Instance Properties

KeepPageStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a document page.
PageFileName | Gets or sets the file name where the document page will be saved to.
PageIndex | Current page index.
PageStream | Allows to specify the stream where the document page will be saved to.

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace


PageSavingArgs Constructor

Initializes a new instance of the PageSavingArgs class.

[Visual Basic]
Public Sub New()
[C#]
public PageSavingArgs();

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace


PageSavingArgs Properties

The properties of the PageSavingArgs class are listed below. For a complete list of PageSavingArgs class members, see the PageSavingArgs Members topic.

Public Instance Properties

KeepPageStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a document page.
PageFileName | Gets or sets the file name where the document page will be saved to.
PageIndex | Current page index.
PageStream | Allows to specify the stream where the document page will be saved to.

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace


KeepPageStreamOpen Property

Aspose.Words

PageSavingArgs.KeepPageStreamOpen Property

Specifies whether Aspose.Words should keep the stream open or close it after saving a document page.

[Visual Basic]
Public Property KeepPageStreamOpen As Boolean
[C#]
public bool KeepPageStreamOpen {get; set;}

Remarks

Default is false and Aspose.Words will close the stream you provided in the PageStream property after writing a document page into it. Specify true to keep the stream open.

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace | PageStream


PageFileName Property

Aspose.Words

PageSavingArgs.PageFileName Property

Gets or sets the file name where the document page will be saved to.

[Visual Basic]
Public Property PageFileName As String
[C#]
public string PageFileName {get; set;}

Remarks

If not specified then page file name and path will be generated automatically using original file name.

Example

Shows how separate pages are saved when a document is exported to fixed page format.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

    HtmlFixedSaveOptions htmlFixedSaveOptions =
        new HtmlFixedSaveOptions { PageIndex = 0, PageCount = doc.PageCount };
    htmlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback();

    doc.Save(ArtifactsDir + "Rendering.html", htmlFixedSaveOptions);

    string[] filePaths = Directory.GetFiles(ArtifactsDir + "", "Page_*.html");

    for (int i = 0; i < doc.PageCount; i++)
    {
        string file = string.Format(ArtifactsDir + "Page_{0}.html", i);
    }
}

/// <summary>
/// Custom PageFileName is specified.
/// </summary>
private class CustomPageFileNamePageSavingCallback : IPageSavingCallback
{
    public void PageSaving(PageSavingArgs args)
    {
        // Specify name of the output file for the current page.
        args.PageFileName = string.Format(ArtifactsDir + "Page_{0}.html", args.PageIndex);
    }
}

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

PageSavingArgs.PageIndex Property

Current page index.

[Visual Basic]
Public ReadOnly Property PageIndex As Integer
[C#]
public int PageIndex {get;}

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace


PageStream Property

Aspose.Words

PageSavingArgs.PageStream Property

Allows to specify the stream where the document page will be saved to.

[Visual Basic]
Public Property PageStream As Stream
[C#]
public Stream PageStream {get; set;}

Remarks

This property allows you to save document pages to streams instead of files.

The default value is null. When this property is null, the document page will be saved to a file specified in the PageFileName property.

If both PageStream and PageFileName are set, then PageStream will be used.

See Also

PageSavingArgs Class | Aspose.Words.Saving Namespace | PageFileName | KeepPageStreamOpen


PclSaveOptions Class

Can be used to specify additional options when saving a document into the Pcl format.

For a list of all members of this type, see PclSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.PclSaveOptions

[Visual Basic]
Public Class PclSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class PclSaveOptions : FixedPageSaveOptions

Example

Shows how rasterized or not transformed elements before saving.

[C#]

Document doc = new Document(MyDir + "Document.EpubConversion.doc");

PclSaveOptions saveOptions = new PclSaveOptions
{
    RasterizeTransformedElements = true
};

doc.Save(ArtifactsDir + "Document.EpubConversion.pcl", saveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PclSaveOptions Members | Aspose.Words.Saving Namespace


PclSaveOptions Members

PclSaveOptions overview

Public Instance Constructors

PclSaveOptions Constructor Initializes a new instance of the PclSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
FallbackFontName | Name of the font that will be used if no expected font is found in printer and built-in fonts collections.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
RasterizeTransformedElements | Gets or sets a value determining whether or not complex transformed elements should be rasterized before saving to PCL document. Default is true.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Pcl.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Public Instance Methods

AddPrinterFont | Adds information about font that is uploaded to the printer by manufacturer.
Equals (inherited from FixedPageSaveOptions) |

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


PclSaveOptions Constructor

Initializes a new instance of the PclSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public PclSaveOptions();

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


PclSaveOptions Properties

The properties of the PclSaveOptions class are listed below. For a complete list of PclSaveOptions class members, see the PclSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
FallbackFontName | Name of the font that will be used if no expected font is found in printer and built-in fonts collections.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
RasterizeTransformedElements | Gets or sets a value determining whether or not complex transformed elements should be rasterized before saving to PCL document. Default is true.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Pcl.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


FallbackFontName Property

Aspose.Words

PclSaveOptions.FallbackFontName Property

Name of the font that will be used if no expected font is found in printer and built-in fonts collections.

[Visual Basic]
Public Property FallbackFontName As String
[C#]
public string FallbackFontName {get; set;}

Remarks

If no fallback is found, a warning is generated and "Arial" font is used.

Example

Shows how to add information about font that is uploaded to the printer and set the font that will be used if no expected font is found in printer and built-in fonts collections.

[C#]

Document doc = new Document(MyDir + "Document.EpubConversion.doc");

PclSaveOptions saveOptions = new PclSaveOptions();
saveOptions.AddPrinterFont("Courier", "Courier");
saveOptions.FallbackFontName = "Times New Roman";

doc.Save(ArtifactsDir + "Document.EpubConversion.pcl", saveOptions);

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


RasterizeTransformedElements Property

Aspose.Words

PclSaveOptions.RasterizeTransformedElements Property

Gets or sets a value determining whether or not complex transformed elements should be rasterized before saving to PCL document. Default is true.

[Visual Basic]
Public Property RasterizeTransformedElements As Boolean
[C#]
public bool RasterizeTransformedElements {get; set;}

Remarks

PCL doesn't support some kind of transformations that are used by Aspose Words. E.g. rotated, skewed images and texture brushes. To properly render such elements rasterization process is used, i.e. saving to image and clipping. This process can take additional time and memory. If flag is set to false, some content in output may be different as compared with the source document.

Example

Shows how rasterized or not transformed elements before saving.

[C#]

Document doc = new Document(MyDir + "Document.EpubConversion.doc");

PclSaveOptions saveOptions = new PclSaveOptions
{
    RasterizeTransformedElements = true
};

doc.Save(ArtifactsDir + "Document.EpubConversion.pcl", saveOptions);

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

PclSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Pcl.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


PclSaveOptions Methods

The methods of the PclSaveOptions class are listed below. For a complete list of PclSaveOptions class members, see the PclSaveOptions Members topic.

Public Instance Methods

AddPrinterFont | Adds information about font that is uploaded to the printer by manufacturer.
Equals (inherited from FixedPageSaveOptions) |

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


PclSaveOptions.AddPrinterFont Method

Adds information about font that is uploaded to the printer by manufacturer.

[Visual Basic]
Public Sub AddPrinterFont( _
ByVal fontFullName As String, _
ByVal fontPclName As String _
)
[C#]
public void AddPrinterFont(
string fontFullName,
string fontPclName
);

Parameters

fontFullName
Full name of the font (e.g. "Times New Roman Bold Italic").
fontPclName
Name of the font that is used in Pcl document.

Remarks

There are 52 fonts that are to be built in any printer according to Pcl specification. However manufactures can add some other fonts to their devices.

Example

Shows how to add information about font that is uploaded to the printer and set the font that will be used if no expected font is found in printer and built-in fonts collections.

[C#]

Document doc = new Document(MyDir + "Document.EpubConversion.doc");

PclSaveOptions saveOptions = new PclSaveOptions();
saveOptions.AddPrinterFont("Courier", "Courier");
saveOptions.FallbackFontName = "Times New Roman";

doc.Save(ArtifactsDir + "Document.EpubConversion.pcl", saveOptions);

See Also

PclSaveOptions Class | Aspose.Words.Saving Namespace


PdfCompliance Enumeration

Specifies the PDF standards compliance level.

[Visual Basic]
Public Enum PdfCompliance
[C#]
public enum PdfCompliance

Example

Shows how to save images to PDF using JPEG encoding to decrease file size.

[C#]

Document doc = new Document(MyDir + "SaveOptions.PdfImageCompression.rtf");

PdfSaveOptions options = new PdfSaveOptions
{
    ImageCompression = PdfImageCompression.Jpeg,
    PreserveFormFields = true
};
doc.Save(ArtifactsDir + "SaveOptions.PdfImageCompression.pdf", options);

PdfSaveOptions optionsA1B = new PdfSaveOptions();
optionsA1B.Compliance = PdfCompliance.PdfA1b;
optionsA1B.ImageCompression = PdfImageCompression.Jpeg;
optionsA1B.JpegQuality = 100; // Use JPEG compression at 50% quality to reduce file size.

doc.Save(ArtifactsDir + "SaveOptions.PdfImageComppression PDF_A_1_B.pdf", optionsA1B);

Members

Member Name | Description | Value
Pdf15 | The output file will comply with the PDF 1.5 standard. | 0
PdfA1a | The output file will comply with the PDF/A-1a standard. This level includes all the requirements of PDF/A-1b and additionally requires that document structure be included (also known as being "tagged"), with the objective of ensuring that document content can be searched and repurposed. | 1
PdfA1b | The output file will comply with the PDF/A-1b standard. PDF/A-1b has the objective of ensuring reliable reproduction of the visual appearance of the document. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfCustomPropertiesExport Enumeration

Specifies the way CustomDocumentProperties are exported to PDF file.

[Visual Basic]
Public Enum PdfCustomPropertiesExport
[C#]
public enum PdfCustomPropertiesExport

Members

Member Name | Description | Value
None | No custom properties are exported. | 0
Standard | Custom properties are exported as entries in /Info dictionary. Custom properties with the following names are not exported: "Title", "Author", "Subject", "Keywords", "Creator", "Producer", "CreationDate", "ModDate", "Trapped". | 1
Metadata | Custom properties are Metadata. The namespace of exported properties in XMP packet is "custprops". Every property has an associated xml-element "custprops:Property1", "custprops:Property2" and so on. There is "rdf:Description" element inside property element. The description element has two elements "custprops:Name", containing custom property's name as a value of this xml-element, and "custprops:Value", containing custom property's value as value of this xml-element. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfDigitalSignatureDetails Class

Contains details for signing a PDF document with a digital signature.

For a list of all members of this type, see PdfDigitalSignatureDetails Members.

System.Object
Aspose.Words.Saving.PdfDigitalSignatureDetails

[Visual Basic]
Public Class PdfDigitalSignatureDetails
[C#]
public class PdfDigitalSignatureDetails

Remarks

At the moment digitally signing PDF documents is only available on .NET 2.0 or higher.

To digitally sign a PDF document when it is created by Aspose.Words, set the DigitalSignatureDetails property to a valid PdfDigitalSignatureDetails object and then save the document in the PDF format passing the PdfSaveOptions as a parameter into the Save method.

Aspose.Words creates a PKCS#7 signature over the whole PDF document and uses the "Adobe.PPKMS" filter and "adbe.pkcs7.sha1" subfilter when creating a digital signature.

Example

Shows how to sign a generated PDF document using Aspose.Words.

[C#]

// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");

// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails =
    new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "Aspose Office", DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(ArtifactsDir + "Document.Signed.pdf", options);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PdfDigitalSignatureDetails Members | Aspose.Words.Saving Namespace | DigitalSignatureDetails


PdfDigitalSignatureDetails Members

PdfDigitalSignatureDetails overview

Public Instance Constructors

PdfDigitalSignatureDetails Overloaded. Initializes a new instance of the PdfDigitalSignatureDetails class.

Public Instance Properties

CertificateHolder |
HashAlgorithm | Gets or sets the hash algorithm.
Location | Gets or sets the location of the signing.
Reason | Gets or sets the reason for the signing.
SignatureDate | Gets or sets the date of the signing.
TimestampSettings | Gets or sets the digital signature timestamp settings.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace | DigitalSignatureDetails


PdfDigitalSignatureDetails Constructor

Initializes an instance of this class.

Overload List

Initializes an instance of this class.

public PdfDigitalSignatureDetails();

Initializes an instance of this class.

public PdfDigitalSignatureDetails(CertificateHolder,string,string,DateTime);

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


PdfDigitalSignatureDetails Constructor ()

Initializes an instance of this class.

[Visual Basic]
Overloads Public Sub New()
[C#]
public PdfDigitalSignatureDetails();

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace | PdfDigitalSignatureDetails Constructor Overload List


PdfDigitalSignatureDetails Constructor (CertificateHolder, String, String, DateTime)

Initializes an instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal certificateHolder As CertificateHolder, _
ByVal reason As String, _
ByVal location As String, _
ByVal signatureDate As Date _
)
[C#]
public PdfDigitalSignatureDetails(
CertificateHolder certificateHolder,
string reason,
string location,
DateTime signatureDate
);

Parameters

certificateHolder
A certificate holder which contains the certificate itself.
reason
The reason for signing.
location
The location of signing.
signatureDate
The date and time of signing.

Example

Shows how to sign a generated PDF document using Aspose.Words.

[C#]

// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");

// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails =
    new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "Aspose Office", DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(ArtifactsDir + "Document.Signed.pdf", options);

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace | PdfDigitalSignatureDetails Constructor Overload List


PdfDigitalSignatureDetails Properties

The properties of the PdfDigitalSignatureDetails class are listed below. For a complete list of PdfDigitalSignatureDetails class members, see the PdfDigitalSignatureDetails Members topic.

Public Instance Properties

CertificateHolder |
HashAlgorithm | Gets or sets the hash algorithm.
Location | Gets or sets the location of the signing.
Reason | Gets or sets the reason for the signing.
SignatureDate | Gets or sets the date of the signing.
TimestampSettings | Gets or sets the digital signature timestamp settings.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace | DigitalSignatureDetails


CertificateHolder Property

Aspose.Words

PdfDigitalSignatureDetails.CertificateHolder Property

[Visual Basic]
Public Property CertificateHolder As CertificateHolder
[C#]
public CertificateHolder CertificateHolder {get; set;}

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


HashAlgorithm Property

Aspose.Words

PdfDigitalSignatureDetails.HashAlgorithm Property

Gets or sets the hash algorithm.

[Visual Basic]
Public Property HashAlgorithm As PdfDigitalSignatureHashAlgorithm
[C#]
public PdfDigitalSignatureHashAlgorithm HashAlgorithm {get; set;}

Remarks

The default value is the SHA-512 algorithm.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


Location Property

Aspose.Words

PdfDigitalSignatureDetails.Location Property

Gets or sets the location of the signing.

[Visual Basic]
Public Property Location As String
[C#]
public string Location {get; set;}

Remarks

The default value is null.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


Reason Property

Aspose.Words

PdfDigitalSignatureDetails.Reason Property

Gets or sets the reason for the signing.

[Visual Basic]
Public Property Reason As String
[C#]
public string Reason {get; set;}

Remarks

The default value is null.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


SignatureDate Property

Aspose.Words

PdfDigitalSignatureDetails.SignatureDate Property

Gets or sets the date of the signing.

[Visual Basic]
Public Property SignatureDate As Date
[C#]
public DateTime SignatureDate {get; set;}

Remarks

The default value is the current time.

This value will appear in the digital signature as an unverified computer time.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


TimestampSettings Property

Aspose.Words

PdfDigitalSignatureDetails.TimestampSettings Property

Gets or sets the digital signature timestamp settings.

[Visual Basic]
Public Property TimestampSettings As PdfDigitalSignatureTimestampSettings
[C#]
public PdfDigitalSignatureTimestampSettings TimestampSettings {get; set;}

Remarks

The default value is null and the digital signature will not be time-stamped. When this property is set to a valid PdfDigitalSignatureTimestampSettings object, then the digital signature in the PDF document will be time-stamped.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace


PdfDigitalSignatureHashAlgorithm Enumeration

Specifies a digital hash algorithm used by a digital signature.

[Visual Basic]
Public Enum PdfDigitalSignatureHashAlgorithm
[C#]
public enum PdfDigitalSignatureHashAlgorithm

Members

Member Name | Description | Value
Sha1 | SHA-1 hash algorithm. | 0
Sha256 | SHA-256 hash algorithm. | 1
Sha384 | SHA-384 hash algorithm. | 2
Sha512 | SHA-512 hash algorithm. | 3
Md5 | SHA-1 hash algorithm. | 4

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfDigitalSignatureTimestampSettings Class

Contains settings of the digital signature timestamp.

For a list of all members of this type, see PdfDigitalSignatureTimestampSettings Members.

System.Object
Aspose.Words.Saving.PdfDigitalSignatureTimestampSettings

[Visual Basic]
Public Class PdfDigitalSignatureTimestampSettings
[C#]
public class PdfDigitalSignatureTimestampSettings

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PdfDigitalSignatureTimestampSettings Members | Aspose.Words.Saving Namespace


PdfDigitalSignatureTimestampSettings Members

PdfDigitalSignatureTimestampSettings overview

Public Instance Constructors

PdfDigitalSignatureTimestampSettings Overloaded. Initializes a new instance of the PdfDigitalSignatureTimestampSettings class.

Public Instance Properties

Password | Timestamp server password.
ServerUrl | Timestamp server URL.
Timeout | Time-out value for accessing timestamp server.
UserName | Timestamp server user name.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


PdfDigitalSignatureTimestampSettings Constructor

Initializes an instance of this class.

Overload List

Initializes an instance of this class.

public PdfDigitalSignatureTimestampSettings();

Initializes an instance of this class.

public PdfDigitalSignatureTimestampSettings(string,string,string);

Initializes an instance of this class.

public PdfDigitalSignatureTimestampSettings(string,string,string,TimeSpan);

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


PdfDigitalSignatureTimestampSettings Constructor ()

Initializes an instance of this class.

[Visual Basic]
Overloads Public Sub New()
[C#]
public PdfDigitalSignatureTimestampSettings();

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace | PdfDigitalSignatureTimestampSettings Constructor Overload List


PdfDigitalSignatureTimestampSettings Constructor (String, String, String)

Initializes an instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal serverUrl As String, _
ByVal userName As String, _
ByVal password As String _
)
[C#]
public PdfDigitalSignatureTimestampSettings(
string serverUrl,
string userName,
string password
);

Parameters

serverUrl
Timestamp server URL.
userName
Timestamp server user name.
password
Timestamp server password.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace | PdfDigitalSignatureTimestampSettings Constructor Overload List


PdfDigitalSignatureTimestampSettings Constructor (String, String, String, TimeSpan)

Initializes an instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal serverUrl As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal timeout As TimeSpan _
)
[C#]
public PdfDigitalSignatureTimestampSettings(
string serverUrl,
string userName,
string password,
TimeSpan timeout
);

Parameters

serverUrl
Timestamp server URL.
userName
Timestamp server user name.
password
Timestamp server password.
timeout
Time-out value for accessing timestamp server.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace | PdfDigitalSignatureTimestampSettings Constructor Overload List


PdfDigitalSignatureTimestampSettings Properties

The properties of the PdfDigitalSignatureTimestampSettings class are listed below. For a complete list of PdfDigitalSignatureTimestampSettings class members, see the PdfDigitalSignatureTimestampSettings Members topic.

Public Instance Properties

Password | Timestamp server password.
ServerUrl | Timestamp server URL.
Timeout | Time-out value for accessing timestamp server.
UserName | Timestamp server user name.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


Password Property

Aspose.Words

PdfDigitalSignatureTimestampSettings.Password Property

Timestamp server password.

[Visual Basic]
Public Property Password As String
[C#]
public string Password {get; set;}

Remarks

The default value is null.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


ServerUrl Property

Aspose.Words

PdfDigitalSignatureTimestampSettings.ServerUrl Property

Timestamp server URL.

[Visual Basic]
Public Property ServerUrl As String
[C#]
public string ServerUrl {get; set;}

Remarks

The default value is null. If null, then the digital signature will not be time-stamped.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


Timeout Property

Aspose.Words

PdfDigitalSignatureTimestampSettings.Timeout Property

Time-out value for accessing timestamp server.

[Visual Basic]
Public Property Timeout As TimeSpan
[C#]
public TimeSpan Timeout {get; set;}

Remarks

The default value is 100 seconds.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


UserName Property

Aspose.Words

PdfDigitalSignatureTimestampSettings.UserName Property

Timestamp server user name.

[Visual Basic]
Public Property UserName As String
[C#]
public string UserName {get; set;}

Remarks

The default value is null.

See Also

PdfDigitalSignatureTimestampSettings Class | Aspose.Words.Saving Namespace


PdfEncryptionAlgorithm Enumeration

Specifies the encryption algorithm to use for encrypting a PDF document.

[Visual Basic]
Public Enum PdfEncryptionAlgorithm
[C#]
public enum PdfEncryptionAlgorithm

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

Members

Member Name | Description | Value
RC4_40 | RC4 encryption, key length of 40 bits. | 0
RC4_128 | RC4 encryption, key length of 128 bits. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfEncryptionDetails Class

Contains details for encrypting and access permissions for a PDF document.

For a list of all members of this type, see PdfEncryptionDetails Members.

System.Object
Aspose.Words.Saving.PdfEncryptionDetails

[Visual Basic]
Public Class PdfEncryptionDetails
[C#]
public class PdfEncryptionDetails

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PdfEncryptionDetails Members | Aspose.Words.Saving Namespace


PdfEncryptionDetails Members

PdfEncryptionDetails overview

Public Instance Constructors

PdfEncryptionDetails Constructor Initializes an instance of this class.

Public Instance Properties

EncryptionAlgorithm | Specifies the encryption algorithm to use.
OwnerPassword | Specifies the owner password for the encrypted PDF document.
Permissions | Specifies the operations that are allowed to a user on an encrypted PDF document. The default value is DisallowAll.
UserPassword | Specifies the user password required for opening the encrypted PDF document.

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


PdfEncryptionDetails Constructor

Initializes an instance of this class.

[Visual Basic]
Public Sub New( _
ByVal userPassword As String, _
ByVal ownerPassword As String, _
ByVal encryptionAlgorithm As PdfEncryptionAlgorithm _
)
[C#]
public PdfEncryptionDetails(
string userPassword,
string ownerPassword,
PdfEncryptionAlgorithm encryptionAlgorithm
);

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


PdfEncryptionDetails Properties

The properties of the PdfEncryptionDetails class are listed below. For a complete list of PdfEncryptionDetails class members, see the PdfEncryptionDetails Members topic.

Public Instance Properties

EncryptionAlgorithm | Specifies the encryption algorithm to use.
OwnerPassword | Specifies the owner password for the encrypted PDF document.
Permissions | Specifies the operations that are allowed to a user on an encrypted PDF document. The default value is DisallowAll.
UserPassword | Specifies the user password required for opening the encrypted PDF document.

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


EncryptionAlgorithm Property

Aspose.Words

PdfEncryptionDetails.EncryptionAlgorithm Property

Specifies the encryption algorithm to use.

[Visual Basic]
Public Property EncryptionAlgorithm As PdfEncryptionAlgorithm
[C#]
public PdfEncryptionAlgorithm EncryptionAlgorithm {get; set;}

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


OwnerPassword Property

Aspose.Words

PdfEncryptionDetails.OwnerPassword Property

Specifies the owner password for the encrypted PDF document.

[Visual Basic]
Public Property OwnerPassword As String
[C#]
public string OwnerPassword {get; set;}

Remarks

The owner password allows the user to open an encrypted PDF document without any access restrictions specified in Permissions.

The owner password cannot be the same as the user password.

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


Permissions Property

Aspose.Words

PdfEncryptionDetails.Permissions Property

Specifies the operations that are allowed to a user on an encrypted PDF document. The default value is DisallowAll.

[Visual Basic]
Public Property Permissions As PdfPermissions
[C#]
public PdfPermissions Permissions {get; set;}

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


UserPassword Property

Aspose.Words

PdfEncryptionDetails.UserPassword Property

Specifies the user password required for opening the encrypted PDF document.

[Visual Basic]
Public Property UserPassword As String
[C#]
public string UserPassword {get; set;}

Remarks

The user password will be required to open an encrypted PDF document for viewing. The permissions specified in Permissions will be enforced by the reader software.

The user password can be null or empty string, in this case no password will be required from the user when opening the PDF document. The user password cannot be the same as the owner password.

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

See Also

PdfEncryptionDetails Class | Aspose.Words.Saving Namespace


PdfFontEmbeddingMode Enumeration

Specifies how Aspose.Words should embed fonts.

[Visual Basic]
Public Enum PdfFontEmbeddingMode
[C#]
public enum PdfFontEmbeddingMode

Example

Shows how to set Aspose.Words to skip embedding Arial and Times New Roman fonts into a PDF document.

[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Rendering.doc");

// To disable embedding standard windows font use the PdfSaveOptions and set the EmbedStandardWindowsFonts property to false.
PdfSaveOptions options = new PdfSaveOptions();
options.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedNone;

// The output PDF will be saved without embedding standard windows fonts.
doc.Save(ArtifactsDir + "Rendering.DisableEmbedWindowsFonts.pdf");

Members

Member Name | Description | Value
EmbedAll | Aspose.Words embeds all fonts. | 0
EmbedNonstandard | Aspose.Words embeds all fonts excepting standard Windows fonts Arial and Times New Roman. Only Arial and Times New Roman fonts are affected in this mode because MS Word doesn't embed only these fonts when saving document to PDF. | 1
EmbedNone | Aspose.Words do not embed any fonts. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfImageColorSpaceExportMode Enumeration

Specifies how the color space will be selected for the images in PDF document.

[Visual Basic]
Public Enum PdfImageColorSpaceExportMode
[C#]
public enum PdfImageColorSpaceExportMode

Members

Member Name | Description | Value
Auto | Aspose.Words automatically selects the most appropriate color space for each image. | 0
SimpleCmyk | Aspose.Words coverts RGB images to CMYK color space using simple formula. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfImageCompression Enumeration

Specifies the type of compression applied to images in the PDF file.

[Visual Basic]
Public Enum PdfImageCompression
[C#]
public enum PdfImageCompression

Example

Shows how to save images to PDF using JPEG encoding to decrease file size.

[C#]

Document doc = new Document(MyDir + "SaveOptions.PdfImageCompression.rtf");

PdfSaveOptions options = new PdfSaveOptions
{
    ImageCompression = PdfImageCompression.Jpeg,
    PreserveFormFields = true
};
doc.Save(ArtifactsDir + "SaveOptions.PdfImageCompression.pdf", options);

PdfSaveOptions optionsA1B = new PdfSaveOptions();
optionsA1B.Compliance = PdfCompliance.PdfA1b;
optionsA1B.ImageCompression = PdfImageCompression.Jpeg;
optionsA1B.JpegQuality = 100; // Use JPEG compression at 50% quality to reduce file size.

doc.Save(ArtifactsDir + "SaveOptions.PdfImageComppression PDF_A_1_B.pdf", optionsA1B);

Members

Member Name | Description | Value
Auto | Automatically selects the most appropriate compression for each image. | 0
Jpeg | Jpeg compression. Does not support transparency. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfPageMode Enumeration

Specifies how the PDF document should be displayed when opened in the PDF reader.

[Visual Basic]
Public Enum PdfPageMode
[C#]
public enum PdfPageMode

Members

Member Name | Description | Value
UseNone | Neither document outline nor thumbnail images are visible. | 0
UseOutlines | Document outline is visible. Note that if there're no outlines in the PDF document then outline navigation pane will not be visible anyway. | 1
UseThumbs | Thumbnail images are visible. | 2
FullScreen | Full-screen mode, with no menu bar, window controls, or any other window visible. | 3
UseOC | Optional content group panel is visible. | 4

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfPermissions Enumeration

Specifies the operations that are allowed to a user on an encrypted PDF document.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum PdfPermissions
[C#]
public enum PdfPermissions

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

Members

Member Name | Description | Value
DisallowAll | Disallows all operations on the PDF document. This is the default value. | 0
AllowAll | Allows all operations on the PDF document. | 65535
ContentCopy | Allows copying or otherwise extracting text and graphics from the document, including extraction for accessibility purposes. | 16
ContentCopyForAccessibility | Allows extract text and graphics in support of accessibility to disabled users or for other purposes. When using RC4 40-bit encryption, this option is ignored and accessibility is allowed whenever ContentCopy is set. | 512
ModifyContents | Allows modifying the document’s contents. | 8
ModifyAnnotations | Allows adding or modifying text annotations. When using RC4 40-bit encryption, this option also allows filling in form fields. | 32
FillIn | Allows filling in forms and signing the document. When using RC4 40-bit encryption, this option is ignored and filling in form is allowed whenever ModifyAnnotations is set. | 256
DocumentAssembly | Allows assembling the document: inserting, rotating, or deleting pages and creating navigation elements such as bookmarks or thumbnail images. When using RC4 40-bit encryption, this option is ignored and document assembly is allowed when ModifyContents is set. | 1024
Printing | Allows printing the document. | 4
HighResolutionPrinting | Allows printing the document to the highest resolution possible. When using RC4 40-bit encryption, this option is ignored and high resolution printing is allowed when Printing is set. | 2052

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfSaveOptions Class

Can be used to specify additional options when saving a document into the Pdf format.

For a list of all members of this type, see PdfSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.PdfSaveOptions

[Visual Basic]
Public Class PdfSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class PdfSaveOptions : FixedPageSaveOptions

Example

Saves a document to PDF without compression.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.TextCompression = PdfTextCompression.None;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfNoCompression.pdf", options);
Converts a whole document to PDF with three levels in the document outline.
[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.OutlineOptions.HeadingsOutlineLevels = 3;
options.OutlineOptions.ExpandedOutlineLevels = 1;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfWithOutline.pdf", options);
Shows how to sign a generated PDF document using Aspose.Words.
[C#]

// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");

// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails =
    new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "Aspose Office", DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(ArtifactsDir + "Document.Signed.pdf", options);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PdfSaveOptions Members | Aspose.Words.Saving Namespace


PdfSaveOptions Members

PdfSaveOptions overview

Public Instance Constructors

PdfSaveOptions Constructor Initializes a new instance of this class that can be used to save a document in the Pdf format.

Public Instance Properties

AdditionalTextPositioning | A flag specifying whether to write additional text positioning operators or not.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
Compliance | Specifies the PDF standards compliance level for output documents.
CreateNoteHyperlinks | Specifies whether to convert footnote/endnote references in main text story into active hyperlinks. When clicked the hyperlink will lead to the corresponding footnote/endnote. Default is false.
CustomPropertiesExport | Gets or sets a value determining the way CustomDocumentProperties are exported to PDF file. Default value is None.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DigitalSignatureDetails | Gets or sets the details for signing the output PDF document.
DisplayDocTitle | A flag specifying whether the window’s title bar should display the document title taken from the Title entry of the document information dictionary.
DmlEffectsRenderingMode | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
DownsampleOptions | Allows to specify downsample options.
EmbedFullFonts | Controls how fonts are embedded into the resulting PDF documents.
EncryptionDetails | Gets or sets the details for encrypting the output PDF document.
EscapeUri | A flag specifying whether URI should be escaped before writing.
ExportDocumentStructure | Gets or sets a value determining whether or not to export document structure.
FontEmbeddingMode | Specifies the font embedding mode.
HeaderFooterBookmarksExportMode | Determines how bookmarks in headers/footers are exported.
ImageColorSpaceExportMode | Specifies how the color space will be selected for the images in PDF document.
ImageCompression | Specifies compression type to be used for all images in the document. Default is Auto.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside PDF document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OpenHyperlinksInNewWindow | Gets or sets a value determining whether hyperlinks in the output Pdf document are forced to be opened in a new window (or tab) of a browser.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
OutlineOptions | Allows to specify outline options.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageMode | Specifies how the PDF document should be displayed when opened in the PDF reader.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PreblendImages | Gets or sets a value determining whether or not to preblend transparent images with black background color.
PreserveFormFields | Specifies whether to preserve Microsoft Word form fields as form fields in PDF or convert them to text. Default is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Pdf.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
TextCompression | Specifies compression type to be used for all textual content in the document.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseBookFoldPrintingSettings | Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.
UseCoreFonts | Gets or sets a value determining whether or not to substitute TrueType fonts Arial, Times New Roman, Courier New and Symbol with core PDF Type 1 fonts.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
ZoomBehavior | Gets or sets a value determining what type of zoom should be applied when a document is opened with a PDF viewer.
ZoomFactor | Gets or sets a value determining zoom factor (in percentages) for a document.

Public Instance Methods

Clone | Creates a deep clone of this object.
Equals (inherited from FixedPageSaveOptions) |

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PdfSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Pdf format.

[Visual Basic]
Public Sub New()
[C#]
public PdfSaveOptions();

Example

Demonstrates how to set Aspose.Words to embed full fonts in the output PDF document.

[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Rendering.doc");

// Aspose.Words embeds full fonts by default when EmbedFullFonts is set to true. The property below can be changed
// each time a document is rendered.
PdfSaveOptions options = new PdfSaveOptions();
options.EmbedFullFonts = true;

// The output PDF will be embedded with all fonts found in the document.
doc.Save(ArtifactsDir + "Rendering.EmbedFullFonts.pdf");

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PdfSaveOptions Properties

The properties of the PdfSaveOptions class are listed below. For a complete list of PdfSaveOptions class members, see the PdfSaveOptions Members topic.

Public Instance Properties

AdditionalTextPositioning | A flag specifying whether to write additional text positioning operators or not.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
Compliance | Specifies the PDF standards compliance level for output documents.
CreateNoteHyperlinks | Specifies whether to convert footnote/endnote references in main text story into active hyperlinks. When clicked the hyperlink will lead to the corresponding footnote/endnote. Default is false.
CustomPropertiesExport | Gets or sets a value determining the way CustomDocumentProperties are exported to PDF file. Default value is None.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DigitalSignatureDetails | Gets or sets the details for signing the output PDF document.
DisplayDocTitle | A flag specifying whether the window’s title bar should display the document title taken from the Title entry of the document information dictionary.
DmlEffectsRenderingMode | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
DownsampleOptions | Allows to specify downsample options.
EmbedFullFonts | Controls how fonts are embedded into the resulting PDF documents.
EncryptionDetails | Gets or sets the details for encrypting the output PDF document.
EscapeUri | A flag specifying whether URI should be escaped before writing.
ExportDocumentStructure | Gets or sets a value determining whether or not to export document structure.
FontEmbeddingMode | Specifies the font embedding mode.
HeaderFooterBookmarksExportMode | Determines how bookmarks in headers/footers are exported.
ImageColorSpaceExportMode | Specifies how the color space will be selected for the images in PDF document.
ImageCompression | Specifies compression type to be used for all images in the document. Default is Auto.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside PDF document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OpenHyperlinksInNewWindow | Gets or sets a value determining whether hyperlinks in the output Pdf document are forced to be opened in a new window (or tab) of a browser.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
OutlineOptions | Allows to specify outline options.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageMode | Specifies how the PDF document should be displayed when opened in the PDF reader.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PreblendImages | Gets or sets a value determining whether or not to preblend transparent images with black background color.
PreserveFormFields | Specifies whether to preserve Microsoft Word form fields as form fields in PDF or convert them to text. Default is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Pdf.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
TextCompression | Specifies compression type to be used for all textual content in the document.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseBookFoldPrintingSettings | Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.
UseCoreFonts | Gets or sets a value determining whether or not to substitute TrueType fonts Arial, Times New Roman, Courier New and Symbol with core PDF Type 1 fonts.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
ZoomBehavior | Gets or sets a value determining what type of zoom should be applied when a document is opened with a PDF viewer.
ZoomFactor | Gets or sets a value determining zoom factor (in percentages) for a document.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


AdditionalTextPositioning Property

Aspose.Words

PdfSaveOptions.AdditionalTextPositioning Property

A flag specifying whether to write additional text positioning operators or not.

[Visual Basic]
Public Property AdditionalTextPositioning As Boolean
[C#]
public bool AdditionalTextPositioning {get; set;}

Remarks

If true, additional text positioning operators are written to the output PDF. This may help to overcome issues with inaccurate text positioning with some printers. The downside is the increased PDF document size.

The default value is false.

Example

Show how to write additional text positioning operators.

[C#]

Document doc = new Document(MyDir + "PdfSaveOptions.AdditionalTextPositioning.docx");

PdfSaveOptions saveOptions = new PdfSaveOptions();
// This may help to overcome issues with inaccurate text positioning with some printers
saveOptions.AdditionalTextPositioning = true;
saveOptions.TextCompression = PdfTextCompression.None;

doc.Save(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf", saveOptions);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


Compliance Property

Aspose.Words

PdfSaveOptions.Compliance Property

Specifies the PDF standards compliance level for output documents.

[Visual Basic]
Public Property Compliance As PdfCompliance
[C#]
public PdfCompliance Compliance {get; set;}

Remarks

Default is Pdf15.

Example

Shows how to save images to PDF using JPEG encoding to decrease file size.

[C#]

Document doc = new Document(MyDir + "SaveOptions.PdfImageCompression.rtf");

PdfSaveOptions options = new PdfSaveOptions
{
    ImageCompression = PdfImageCompression.Jpeg,
    PreserveFormFields = true
};
doc.Save(ArtifactsDir + "SaveOptions.PdfImageCompression.pdf", options);

PdfSaveOptions optionsA1B = new PdfSaveOptions();
optionsA1B.Compliance = PdfCompliance.PdfA1b;
optionsA1B.ImageCompression = PdfImageCompression.Jpeg;
optionsA1B.JpegQuality = 100; // Use JPEG compression at 50% quality to reduce file size.

doc.Save(ArtifactsDir + "SaveOptions.PdfImageComppression PDF_A_1_B.pdf", optionsA1B);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


CreateNoteHyperlinks Property

Aspose.Words

PdfSaveOptions.CreateNoteHyperlinks Property

Specifies whether to convert footnote/endnote references in main text story into active hyperlinks. When clicked the hyperlink will lead to the corresponding footnote/endnote. Default is false.

[Visual Basic]
Public Property CreateNoteHyperlinks As Boolean
[C#]
public bool CreateNoteHyperlinks {get; set;}

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


CustomPropertiesExport Property

Aspose.Words

PdfSaveOptions.CustomPropertiesExport Property

Gets or sets a value determining the way CustomDocumentProperties are exported to PDF file. Default value is None.

[Visual Basic]
Public Property CustomPropertiesExport As PdfCustomPropertiesExport
[C#]
public PdfCustomPropertiesExport CustomPropertiesExport {get; set;}

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DigitalSignatureDetails Property

Aspose.Words

PdfSaveOptions.DigitalSignatureDetails Property

Gets or sets the details for signing the output PDF document.

[Visual Basic]
Public Property DigitalSignatureDetails As PdfDigitalSignatureDetails
[C#]
public PdfDigitalSignatureDetails DigitalSignatureDetails {get; set;}

Remarks

At the moment digitally signing PDF documents is only available on .NET 2.0 or higher.

The default value is null and the output document will not be signed. When this property is set to a valid PdfDigitalSignatureDetails object, then the output PDF document will be digitally signed.

Example

Shows how to sign a generated PDF document using Aspose.Words.

[C#]

// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");

// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails =
    new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "Aspose Office", DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(ArtifactsDir + "Document.Signed.pdf", options);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DisplayDocTitle Property

Aspose.Words

PdfSaveOptions.DisplayDocTitle Property

A flag specifying whether the window’s title bar should display the document title taken from the Title entry of the document information dictionary.

[Visual Basic]
Public Property DisplayDocTitle As Boolean
[C#]
public bool DisplayDocTitle {get; set;}

Remarks

If false, the title bar should instead display the name of the PDF file containing the document.

The default value is false.

Example

Shows how to display title of the document as title bar.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");
doc.BuiltInDocumentProperties.Title = "Windows bar pdf title";

PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { DisplayDocTitle = true };

doc.Save(ArtifactsDir + "PdfTitle.pdf", pdfSaveOptions);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DmlEffectsRenderingMode Property

Aspose.Words

PdfSaveOptions.DmlEffectsRenderingMode Property

Gets or sets a value determining how DrawingML effects are rendered.

[Visual Basic]
Overrides Public Property DmlEffectsRenderingMode As DmlEffectsRenderingMode
[C#]
public override DmlEffectsRenderingMode DmlEffectsRenderingMode {get; set;}

Remarks

The default value is Simplified.

This property is used when the document is exported to fixed page formats.

If Compliance is set to PdfA1a or PdfA1b, property always returns None.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DownsampleOptions Property

Aspose.Words

PdfSaveOptions.DownsampleOptions Property

Allows to specify downsample options.

[Visual Basic]
Public Property DownsampleOptions As DownsampleOptions
[C#]
public DownsampleOptions DownsampleOptions {get; set;}

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


EmbedFullFonts Property

Aspose.Words

PdfSaveOptions.EmbedFullFonts Property

Controls how fonts are embedded into the resulting PDF documents.

[Visual Basic]
Public Property EmbedFullFonts As Boolean
[C#]
public bool EmbedFullFonts {get; set;}

Remarks

The default value is false, which means the fonts are subsetted before embedding. Subsetting is useful if you want to keep the output file size smaller. Subsetting removes all unused glyphs from a font.

When this value is set to true, a complete font file is embedded into PDF without subsetting. This will result in larger output files, but can be a useful option when you want to edit the resulting PDF later (e.g. add more text).

Some fonts are large (several megabytes) and embedding them without subsetting will result in large output documents.

Example

Demonstrates how to set Aspose.Words to embed full fonts in the output PDF document.

[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Rendering.doc");

// Aspose.Words embeds full fonts by default when EmbedFullFonts is set to true. The property below can be changed
// each time a document is rendered.
PdfSaveOptions options = new PdfSaveOptions();
options.EmbedFullFonts = true;

// The output PDF will be embedded with all fonts found in the document.
doc.Save(ArtifactsDir + "Rendering.EmbedFullFonts.pdf");
Demonstrates how to set Aspose.Words to subset fonts in the output PDF.
[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Rendering.doc");

// To subset fonts in the output PDF document, simply create new PdfSaveOptions and set EmbedFullFonts to false.
PdfSaveOptions options = new PdfSaveOptions();
options.EmbedFullFonts = false;

// The output PDF will contain subsets of the fonts in the document. Only the glyphs used
// in the document are included in the PDF fonts.
doc.Save(ArtifactsDir + "Rendering.SubsetFonts.pdf");

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


EncryptionDetails Property

Aspose.Words

PdfSaveOptions.EncryptionDetails Property

Gets or sets the details for encrypting the output PDF document.

[Visual Basic]
Public Property EncryptionDetails As PdfEncryptionDetails
[C#]
public PdfEncryptionDetails EncryptionDetails {get; set;}

Remarks

The default value is null and the output document will not be encrypted. When this property is set to a valid PdfEncryptionDetails object, then the output PDF document will be encrypted.

Note that encryption cannot be used when PDF/A compliance is set as this compliance does not permit encryption.");

Example

Demonstrates how to set permissions on a PDF document generated by Aspose.Words.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions saveOptions = new PdfSaveOptions();

// Create encryption details and set owner password.
PdfEncryptionDetails encryptionDetails =
    new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128);

// Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll;

// Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
saveOptions.EncryptionDetails = encryptionDetails;

// Render the document to PDF format with the specified permissions.
doc.Save(ArtifactsDir + "Rendering.SpecifyPermissions.pdf", saveOptions);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


EscapeUri Property

Aspose.Words

PdfSaveOptions.EscapeUri Property

A flag specifying whether URI should be escaped before writing.

[Visual Basic]
Public Property EscapeUri As Boolean
[C#]
public bool EscapeUri {get; set;}

Remarks

Note that if this option is set to false hyperlinks are written "as is", so valid (escaped) URI should be provided in document's model.

The default value is true.

Example

Shows how to escape hyperlinks or not in the document.

[C#]

DocumentBuilder builder = new DocumentBuilder();
builder.InsertHyperlink("Testlink", uri, false);

// Set this property to false if you are sure that hyperlinks in document's model are already escaped
PdfSaveOptions options = new PdfSaveOptions();
options.EscapeUri = isEscaped;

builder.Document.Save(ArtifactsDir + "PdfSaveOptions.EscapedUri.pdf", options);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ExportDocumentStructure Property

Aspose.Words

PdfSaveOptions.ExportDocumentStructure Property

Gets or sets a value determining whether or not to export document structure.

[Visual Basic]
Public Property ExportDocumentStructure As Boolean
[C#]
public bool ExportDocumentStructure {get; set;}

Remarks

This value is ignored when saving to PDF/A-1a because document structure is required for this compliance.

Note that exporting the document structure significantly increases the memory consumption, especially for the large documents.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


FontEmbeddingMode Property

Aspose.Words

PdfSaveOptions.FontEmbeddingMode Property

Specifies the font embedding mode.

[Visual Basic]
Public Property FontEmbeddingMode As PdfFontEmbeddingMode
[C#]
public PdfFontEmbeddingMode FontEmbeddingMode {get; set;}

Remarks

The default value is EmbedAll.

This setting works only for the text in ANSI (Windows-1252) encoding. If the document contains non-ANSI text then corresponding fonts will be embedded regardless of this setting.

Note that when saving to PDF/A this option must be set to EmbedAll as all fonts must be embedded in the PDF file.

Example

Shows how to set Aspose.Words to skip embedding Arial and Times New Roman fonts into a PDF document.

[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Rendering.doc");

// To disable embedding standard windows font use the PdfSaveOptions and set the EmbedStandardWindowsFonts property to false.
PdfSaveOptions options = new PdfSaveOptions();
options.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedNone;

// The output PDF will be saved without embedding standard windows fonts.
doc.Save(ArtifactsDir + "Rendering.DisableEmbedWindowsFonts.pdf");

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


HeaderFooterBookmarksExportMode Property

Aspose.Words

PdfSaveOptions.HeaderFooterBookmarksExportMode Property

Determines how bookmarks in headers/footers are exported.

[Visual Basic]
Public Property HeaderFooterBookmarksExportMode As HeaderFooterBookmarksExportMode
[C#]
public HeaderFooterBookmarksExportMode HeaderFooterBookmarksExportMode {get; set;}

Remarks

The default value is All.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ImageColorSpaceExportMode Property

Aspose.Words

PdfSaveOptions.ImageColorSpaceExportMode Property

Specifies how the color space will be selected for the images in PDF document.

[Visual Basic]
Public Property ImageColorSpaceExportMode As PdfImageColorSpaceExportMode
[C#]
public PdfImageColorSpaceExportMode ImageColorSpaceExportMode {get; set;}

Remarks

The default value is Auto. If SimpleCmyk value is specified, ImageCompression option is ignored and Flate compression is used for all images in the document.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ImageCompression Property

Aspose.Words

PdfSaveOptions.ImageCompression Property

Specifies compression type to be used for all images in the document. Default is Auto.

[Visual Basic]
Public Property ImageCompression As PdfImageCompression
[C#]
public PdfImageCompression ImageCompression {get; set;}

Remarks

Using Jpeg lets you control quality of images in the output document through the JpegQuality property. Using Jpeg provides the fastest conversion speed when compared to the performance of other compression types.

Example

Shows how to save images to PDF using JPEG encoding to decrease file size.

[C#]

Document doc = new Document(MyDir + "SaveOptions.PdfImageCompression.rtf");

PdfSaveOptions options = new PdfSaveOptions
{
    ImageCompression = PdfImageCompression.Jpeg,
    PreserveFormFields = true
};
doc.Save(ArtifactsDir + "SaveOptions.PdfImageCompression.pdf", options);

PdfSaveOptions optionsA1B = new PdfSaveOptions();
optionsA1B.Compliance = PdfCompliance.PdfA1b;
optionsA1B.ImageCompression = PdfImageCompression.Jpeg;
optionsA1B.JpegQuality = 100; // Use JPEG compression at 50% quality to reduce file size.

doc.Save(ArtifactsDir + "SaveOptions.PdfImageComppression PDF_A_1_B.pdf", optionsA1B);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


JpegQuality Property

Aspose.Words

PdfSaveOptions.JpegQuality Property

Gets or sets a value determining the quality of the JPEG images inside PDF document.

[Visual Basic]
Public Property JpegQuality As Integer
[C#]
new public int JpegQuality {get; set;}

Remarks

Has effect only when a document contains JPEG images.

Use this property to get or set the quality of the images inside a document when saving in PDF format. The value may vary from 0 to 100 where 0 means worst quality but maximum compression and 100 means best quality but minimum compression. If quality is 100 and source image is JPEG, it means no compression - original bytes will be saved.

The default value is 100.

Example

Shows how to save images to PDF using JPEG encoding to decrease file size.

[C#]

Document doc = new Document(MyDir + "SaveOptions.PdfImageCompression.rtf");

PdfSaveOptions options = new PdfSaveOptions
{
    ImageCompression = PdfImageCompression.Jpeg,
    PreserveFormFields = true
};
doc.Save(ArtifactsDir + "SaveOptions.PdfImageCompression.pdf", options);

PdfSaveOptions optionsA1B = new PdfSaveOptions();
optionsA1B.Compliance = PdfCompliance.PdfA1b;
optionsA1B.ImageCompression = PdfImageCompression.Jpeg;
optionsA1B.JpegQuality = 100; // Use JPEG compression at 50% quality to reduce file size.

doc.Save(ArtifactsDir + "SaveOptions.PdfImageComppression PDF_A_1_B.pdf", optionsA1B);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


OpenHyperlinksInNewWindow Property

Aspose.Words

PdfSaveOptions.OpenHyperlinksInNewWindow Property

Gets or sets a value determining whether hyperlinks in the output Pdf document are forced to be opened in a new window (or tab) of a browser.

[Visual Basic]
Public Property OpenHyperlinksInNewWindow As Boolean
[C#]
public bool OpenHyperlinksInNewWindow {get; set;}

Remarks

The default value is false. When this value is set to true hyperlinks are saved using JavaScript code. JavaScript code is app.launchURL("URL", true);, where URL is a hyperlink.

Note that if this option is set to true hyperlinks can't work in some PDF readers e.g. Chrome, Firefox.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


OutlineOptions Property

Aspose.Words

PdfSaveOptions.OutlineOptions Property

Allows to specify outline options.

[Visual Basic]
Public ReadOnly Property OutlineOptions As OutlineOptions
[C#]
public OutlineOptions OutlineOptions {get;}

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PageMode Property

Aspose.Words

PdfSaveOptions.PageMode Property

Specifies how the PDF document should be displayed when opened in the PDF reader.

[Visual Basic]
Public Property PageMode As PdfPageMode
[C#]
public PdfPageMode PageMode {get; set;}

Remarks

The default value is UseOutlines.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PreblendImages Property

Aspose.Words

PdfSaveOptions.PreblendImages Property

Gets or sets a value determining whether or not to preblend transparent images with black background color.

[Visual Basic]
Public Property PreblendImages As Boolean
[C#]
public bool PreblendImages {get; set;}

Remarks

Preblending images may improve PDF document visual appearance in Adobe Reader and remove anti-aliasing artifacts.

In order to properly display preblended images, PDF viewer application must support /Matte entry in soft-mask image dictionary. Also preblending images may decrease PDF rendering performance.

The default value is false.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PreserveFormFields Property

Aspose.Words

PdfSaveOptions.PreserveFormFields Property

Specifies whether to preserve Microsoft Word form fields as form fields in PDF or convert them to text. Default is false.

[Visual Basic]
Public Property PreserveFormFields As Boolean
[C#]
public bool PreserveFormFields {get; set;}

Remarks

Microsoft Word form fields include text input, drop down and check box controls. When set to false, these fields will be exported as text to PDF. When set to true, these fields will be exported as PDF form fields.

When exporting form fields to PDF as form fields, some formatting loss might occur because PDF form fields do not support all features of Microsoft Word form fields.

Example

Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.

[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");

// Option 1: Save document to file in the PDF format with default options
doc.Save(ArtifactsDir + "Rendering.PdfDefaultOptions.pdf");

// Option 2: Save the document to stream in the PDF format with default options
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Pdf);
// Rewind the stream position back to the beginning, ready for use
stream.Seek(0, SeekOrigin.Begin);

// Option 3: Save document to the PDF format with specified options
// Render the first page only and preserve form fields as usable controls and not as plain text
PdfSaveOptions pdfOptions = new PdfSaveOptions();
pdfOptions.PageIndex = 0;
pdfOptions.PageCount = 1;
pdfOptions.PreserveFormFields = true;
doc.Save(ArtifactsDir + "Rendering.PdfCustomOptions.pdf", pdfOptions);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

PdfSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Pdf.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


TextCompression Property

Aspose.Words

PdfSaveOptions.TextCompression Property

Specifies compression type to be used for all textual content in the document.

[Visual Basic]
Public Property TextCompression As PdfTextCompression
[C#]
public PdfTextCompression TextCompression {get; set;}

Remarks

Default is Flate.

Example

Saves a document to PDF without compression.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.TextCompression = PdfTextCompression.None;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfNoCompression.pdf", options);

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


UseBookFoldPrintingSettings Property

Aspose.Words

PdfSaveOptions.UseBookFoldPrintingSettings Property

Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.

[Visual Basic]
Public Property UseBookFoldPrintingSettings As Boolean
[C#]
public bool UseBookFoldPrintingSettings {get; set;}

Remarks

If this option is specified, page range set via PageIndex and PageCount is ignored when saving. This behavior matches MS Word. If book fold printing settings are not specified in page setup, this option will have no effect.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


UseCoreFonts Property

Aspose.Words

PdfSaveOptions.UseCoreFonts Property

Gets or sets a value determining whether or not to substitute TrueType fonts Arial, Times New Roman, Courier New and Symbol with core PDF Type 1 fonts.

[Visual Basic]
Public Property UseCoreFonts As Boolean
[C#]
public bool UseCoreFonts {get; set;}

Remarks

The default value is false. When this value is set to true Arial, Times New Roman, Courier New and Symbol fonts are replaced in PDF document with corresponding core Type 1 font.

Core PDF fonts, or their font metrics and suitable substitution fonts, are required to be available to any PDF viewer application.

This setting works only for the text in ANSI (Windows-1252) encoding. Non-ANSI text will be written with embedded TrueType font regardless of this setting.

Settings core fonts to true is not allowed when saving to PDF/A as this compliance requires all fonts to be embedded.

This option has a higher priority then FontEmbeddingMode option.

Example

Shows how to set Aspose.Words to avoid embedding core fonts and let the reader substitute PDF Type 1 fonts instead.

[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Rendering.doc");

// To disable embedding of core fonts and substitute PDF type 1 fonts set UseCoreFonts to true.
PdfSaveOptions options = new PdfSaveOptions();
options.UseCoreFonts = true;

// The output PDF will not be embedded with core fonts such as Arial, Times New Roman etc.
doc.Save(ArtifactsDir + "Rendering.DisableEmbedWindowsFonts.pdf");

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ZoomBehavior Property

Aspose.Words

PdfSaveOptions.ZoomBehavior Property

Gets or sets a value determining what type of zoom should be applied when a document is opened with a PDF viewer.

[Visual Basic]
Public Property ZoomBehavior As PdfZoomBehavior
[C#]
public PdfZoomBehavior ZoomBehavior {get; set;}

Remarks

The default value is None, i.e. no fit is applied.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ZoomFactor Property

Aspose.Words

PdfSaveOptions.ZoomFactor Property

Gets or sets a value determining zoom factor (in percentages) for a document.

[Visual Basic]
Public Property ZoomFactor As Integer
[C#]
public int ZoomFactor {get; set;}

Remarks

This value is used only if ZoomBehavior is set to ZoomFactor.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PdfSaveOptions Methods

The methods of the PdfSaveOptions class are listed below. For a complete list of PdfSaveOptions class members, see the PdfSaveOptions Members topic.

Public Instance Methods

Clone | Creates a deep clone of this object.
Equals (inherited from FixedPageSaveOptions) |

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PdfSaveOptions.Clone Method

Creates a deep clone of this object.

[Visual Basic]
Public Function Clone() As PdfSaveOptions
[C#]
public PdfSaveOptions Clone();

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PdfTextCompression Enumeration

Specifies a type of compression applied to all content in the PDF file except images.

[Visual Basic]
Public Enum PdfTextCompression
[C#]
public enum PdfTextCompression

Example

Saves a document to PDF without compression.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

PdfSaveOptions options = new PdfSaveOptions();
options.TextCompression = PdfTextCompression.None;

doc.Save(ArtifactsDir + "Rendering.SaveToPdfNoCompression.pdf", options);

Members

Member Name | Description | Value
None | No compression. | 0
Flate | Flate (ZIP) compression. | 1

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PdfZoomBehavior Enumeration

Specifies the type of zoom applied to a PDF document when it is opened in a PDF viewer.

[Visual Basic]
Public Enum PdfZoomBehavior
[C#]
public enum PdfZoomBehavior

Members

Member Name | Description | Value
None | How the document is displayed is left to the PDF viewer. Usually the viewer displays the document to fit page width. | 0
ZoomFactor | Displays the page using the specified zoom factor. | 1
FitPage | Displays the page so it visible entirely. | 2
FitWidth | Fits the width of the page. | 3
FitHeight | Fits the height of the page. | 4
FitBox | Fits the bounding box (rectangle containing all visible elements on the page). | 5

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


PsSaveOptions Class

Can be used to specify additional options when saving a document into the Ps format.

For a list of all members of this type, see PsSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.PsSaveOptions

[Visual Basic]
Public Class PsSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class PsSaveOptions : FixedPageSaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PsSaveOptions Members | Aspose.Words.Saving Namespace


PsSaveOptions Members

PsSaveOptions overview

Public Instance Constructors

PsSaveOptions Constructor Initializes a new instance of the PsSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Ps.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseBookFoldPrintingSettings | Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Public Instance Methods

Equals (inherited from FixedPageSaveOptions)

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


PsSaveOptions Constructor

Initializes a new instance of the PsSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public PsSaveOptions();

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


PsSaveOptions Properties

The properties of the PsSaveOptions class are listed below. For a complete list of PsSaveOptions class members, see the PsSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Ps.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseBookFoldPrintingSettings | Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

PsSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Ps.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


UseBookFoldPrintingSettings Property

Aspose.Words

PsSaveOptions.UseBookFoldPrintingSettings Property

Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.

[Visual Basic]
Public Property UseBookFoldPrintingSettings As Boolean
[C#]
public bool UseBookFoldPrintingSettings {get; set;}

Remarks

If this option is specified, page range set via PageIndex and PageCount is ignored when saving. This behavior matches MS Word. If book fold printing settings are not specified in page setup, this option will have no effect.

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


ResourceSavingArgs Class

Provides data for the ResourceSaving event.

For a list of all members of this type, see ResourceSavingArgs Members.

System.Object
Aspose.Words.Saving.ResourceSavingArgs

[Visual Basic]
Public Class ResourceSavingArgs
[C#]
public class ResourceSavingArgs

Remarks

By default, when Aspose.Words saves a document to fixed page HTML or SVG, it saves each resource into a separate file. Aspose.Words uses the document file name and a unique number to generate unique file name for each resource found in the document.

ResourceSavingArgs allows to redefine how resource file names are generated or to completely circumvent saving of resources into files by providing your own stream objects.

To apply your own logic for generating resource file names use the ResourceFileName property.

To save resources into streams instead of files, use the ResourceStream property.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ResourceSavingArgs Members | Aspose.Words.Saving Namespace


ResourceSavingArgs Members

ResourceSavingArgs overview

Public Instance Properties

Document | Gets the document object that is currently being saved.
KeepResourceStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a resource.
ResourceFileName | Gets or sets the file name (without path) where the resource will be saved to.
ResourceFileUri | Gets or sets the uniform resource identifier (URI) used to reference the resource file from the document.
ResourceStream | Allows to specify the stream where the resource will be saved to.

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace


ResourceSavingArgs Properties

The properties of the ResourceSavingArgs class are listed below. For a complete list of ResourceSavingArgs class members, see the ResourceSavingArgs Members topic.

Public Instance Properties

Document | Gets the document object that is currently being saved.
KeepResourceStreamOpen | Specifies whether Aspose.Words should keep the stream open or close it after saving a resource.
ResourceFileName | Gets or sets the file name (without path) where the resource will be saved to.
ResourceFileUri | Gets or sets the uniform resource identifier (URI) used to reference the resource file from the document.
ResourceStream | Allows to specify the stream where the resource will be saved to.

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace


Document Property

Aspose.Words

ResourceSavingArgs.Document Property

Gets the document object that is currently being saved.

[Visual Basic]
Public ReadOnly Property Document As Document
[C#]
public Document Document {get;}

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace


KeepResourceStreamOpen Property

Aspose.Words

ResourceSavingArgs.KeepResourceStreamOpen Property

Specifies whether Aspose.Words should keep the stream open or close it after saving a resource.

[Visual Basic]
Public Property KeepResourceStreamOpen As Boolean
[C#]
public bool KeepResourceStreamOpen {get; set;}

Remarks

Default is false and Aspose.Words will close the stream you provided in the ResourceStream property after writing a resource into it. Specify true to keep the stream open.

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace | ResourceStream


ResourceFileName Property

Aspose.Words

ResourceSavingArgs.ResourceFileName Property

Gets or sets the file name (without path) where the resource will be saved to.

[Visual Basic]
Public Property ResourceFileName As String
[C#]
public string ResourceFileName {get; set;}

Remarks

This property allows you to redefine how the resource file names are generated during export to fixed page HTML or SVG.

When the event is fired, this property contains the file name that was generated by Aspose.Words. You can change the value of this property to save the resource into a different file. Note that file names must be unique.

Aspose.Words automatically generates a unique file name for every resource when exporting to fixed page HTML or SVG format. How the resource file name is generated depends on whether you save the document to a file or to a stream.

When saving a document to a file, the generated resource file name looks like <document base file name>.<image number>.<extension>.

When saving a document to a stream, the generated resource file name looks like Aspose.Words.<document guid>.<image number>.<extension>.

ResourceFileName must contain only the file name without the path. Aspose.Words determines the path for saving and the value of the src attribute for writing to fixed page HTML or SVG using the document file name, the ResourcesFolder or ResourcesFolder and ResourcesFolderAlias or ResourcesFolderAlias properties.

ResourcesFolder ResourcesFolder ResourcesFolderAlias ResourcesFolderAlias

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace | ResourceStream


ResourceFileUri Property

Aspose.Words

ResourceSavingArgs.ResourceFileUri Property

Gets or sets the uniform resource identifier (URI) used to reference the resource file from the document.

[Visual Basic]
Public Property ResourceFileUri As String
[C#]
public string ResourceFileUri {get; set;}

Remarks

This property allows you to change URIs of resource files exported to fixed page HTML or SVG documents.

Aspose.Words automatically generates an URI for every resource file during export to fixed page HTML or SVG format. The generated URIs reference resource files saved by Aspose.Words. However, the URIs can be incorrect if resource files are to be moved to other location or if resource files are saved to streams. This property allows to correct URIs in these cases.

When the event is fired, this property contains the URI that was generated by Aspose.Words. You can change the value of this property to provide a custom URI for the resource file.

ResourcesFolder ResourcesFolder ResourcesFolderAlias ResourcesFolderAlias

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace


ResourceStream Property

Aspose.Words

ResourceSavingArgs.ResourceStream Property

Allows to specify the stream where the resource will be saved to.

[Visual Basic]
Public Property ResourceStream As Stream
[C#]
public Stream ResourceStream {get; set;}

Remarks

This property allows you to save resources to streams instead of files.

The default value is null. When this property is null, the resource will be saved to a file specified in the ResourceFileName property.

Using IResourceSavingCallback you cannot substitute one resource with another. It is intended only for control over location where to save resources.

See Also

ResourceSavingArgs Class | Aspose.Words.Saving Namespace | ResourceFileName | KeepResourceStreamOpen


RtfSaveOptions Class

Can be used to specify additional options when saving a document into the Rtf format.

For a list of all members of this type, see RtfSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.RtfSaveOptions

[Visual Basic]
Public Class RtfSaveOptions
Inherits SaveOptions
[C#]
public class RtfSaveOptions : SaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RtfSaveOptions Members | Aspose.Words.Saving Namespace


RtfSaveOptions Members

RtfSaveOptions overview

Public Instance Constructors

RtfSaveOptions Constructor Initializes a new instance of the RtfSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
ExportCompactSize | Allows to make output RTF documents smaller in size, but if they contain RTL (right-to-left) text, it will not be displayed correctly. Default value is false.
ExportImagesForOldReaders | Specifies whether the keywords for "old readers" are written to RTF or not. This can significantly affect the size of the RTF document. Default value is true.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Rtf.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


RtfSaveOptions Constructor

Initializes a new instance of the RtfSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public RtfSaveOptions();

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


RtfSaveOptions Properties

The properties of the RtfSaveOptions class are listed below. For a complete list of RtfSaveOptions class members, see the RtfSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
ExportCompactSize | Allows to make output RTF documents smaller in size, but if they contain RTL (right-to-left) text, it will not be displayed correctly. Default value is false.
ExportImagesForOldReaders | Specifies whether the keywords for "old readers" are written to RTF or not. This can significantly affect the size of the RTF document. Default value is true.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Rtf.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


ExportCompactSize Property

Aspose.Words

RtfSaveOptions.ExportCompactSize Property

Allows to make output RTF documents smaller in size, but if they contain RTL (right-to-left) text, it will not be displayed correctly. Default value is false.

[Visual Basic]
Public Property ExportCompactSize As Boolean
[C#]
public bool ExportCompactSize {get; set;}

Remarks

If the document that you want to convert to RTF using Aspose.Words does not contain right-to-left text in languages like Arabic, then you can set this option to true to reduce the size of the resulting RTF.

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


ExportImagesForOldReaders Property

Aspose.Words

RtfSaveOptions.ExportImagesForOldReaders Property

Specifies whether the keywords for "old readers" are written to RTF or not. This can significantly affect the size of the RTF document. Default value is true.

[Visual Basic]
Public Property ExportImagesForOldReaders As Boolean
[C#]
public bool ExportImagesForOldReaders {get; set;}

Remarks

"Old readers" are pre-Microsoft Word 97 applications and also WordPad. When this option is true Aspose.Words writes additional RTF keywords. These keywords allow the document to be displayed correctly when opened in an "old reader" application, but can significantly increase the size of the document.

If you set this option to false, then only images in WMF, EMF and BMP formats will be displayed in "old readers".

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

RtfSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Rtf.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


SaveOptions Class

This is an abstract base class for classes that allow the user to specify additional options when saving a document into a particular format.

For a list of all members of this type, see SaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Derived types

[Visual Basic]
MustInherit Public Class SaveOptions
[C#]
public abstract class SaveOptions

Remarks

An instance of the SaveOptions class or any derived class is passed to the stream Save or string Save overloads for the user to define custom options when saving a document.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SaveOptions Members | Aspose.Words.Saving Namespace


SaveOptions Members

SaveOptions overview

Public Static (Shared) Methods

CreateSaveOptions Overloaded. Creates a save options object of a correct class.

Public Instance Properties

ColorMode | Gets or sets a value determining how colors are rendered.
DefaultTemplate | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode | Gets or sets a value determining how DrawingML shapes are rendered.
MemoryOptimization | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used.
TempFolder | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


SaveOptions Properties

The properties of the SaveOptions class are listed below. For a complete list of SaveOptions class members, see the SaveOptions Members topic.

Public Instance Properties

ColorMode | Gets or sets a value determining how colors are rendered.
DefaultTemplate | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode | Gets or sets a value determining how DrawingML shapes are rendered.
MemoryOptimization | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used.
TempFolder | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


ColorMode Property

Aspose.Words

SaveOptions.ColorMode Property

Gets or sets a value determining how colors are rendered.

[Visual Basic]
Public Property ColorMode As ColorMode
[C#]
public ColorMode ColorMode {get; set;}

Remarks

The default value is Normal.

This property is used when the document is exported to fixed page formats.

Example

Shows how change image color with save options property

[C#]

// Open document with color image
Document doc = new Document(MyDir + "Rendering.doc");
// Set grayscale mode for document
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { ColorMode = ColorMode.Grayscale };

// Assert that color image in document was grey
doc.Save(ArtifactsDir + "ColorMode.PdfGrayscaleMode.pdf", pdfSaveOptions);

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


DefaultTemplate Property

Aspose.Words

SaveOptions.DefaultTemplate Property

Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).

[Visual Basic]
Public Property DefaultTemplate As String
[C#]
public string DefaultTemplate {get; set;}

Remarks

If specified, this path is used to load template when AutomaticallyUpdateSyles is true, but AttachedTemplate is empty.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


DmlEffectsRenderingMode Property

Aspose.Words

SaveOptions.DmlEffectsRenderingMode Property

Gets or sets a value determining how DrawingML effects are rendered.

[Visual Basic]
Overridable Public Property DmlEffectsRenderingMode As DmlEffectsRenderingMode
[C#]
public virtual DmlEffectsRenderingMode DmlEffectsRenderingMode {get; set;}

Remarks

The default value is Simplified.

This property is used when the document is exported to fixed page formats.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


DmlRenderingMode Property

Aspose.Words

SaveOptions.DmlRenderingMode Property

Gets or sets a value determining how DrawingML shapes are rendered.

[Visual Basic]
Public Property DmlRenderingMode As DmlRenderingMode
[C#]
public DmlRenderingMode DmlRenderingMode {get; set;}

Remarks

The default value is Fallback.

This property is used when the document is exported to fixed page formats.

Example

Shows how to define rendering for DML shapes

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { DmlRenderingMode = DmlRenderingMode.DrawingML };

doc.Save(ArtifactsDir + "DrawingMl.pdf", pdfSaveOptions);

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


MemoryOptimization Property

Aspose.Words

SaveOptions.MemoryOptimization Property

Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.

[Visual Basic]
Public Property MemoryOptimization As Boolean
[C#]
public bool MemoryOptimization {get; set;}

Remarks

Setting this option to true can significantly decrease memory consumption while saving large documents at the cost of slower saving time.

Example

Shows an option to optimize memory consumption when you work with large documents.

[C#]

Document doc = new Document(MyDir + "SaveOptions.MemoryOptimization.doc");
// When set to true it will improve document memory footprint but will add extra time to processing.
// This optimization is only applied during save operation.
SaveOptions saveOptions = SaveOptions.CreateSaveOptions(SaveFormat.Pdf);
saveOptions.MemoryOptimization = true;

doc.Save(ArtifactsDir + "SaveOptions.MemoryOptimization.pdf", saveOptions);

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


PrettyFormat Property

Aspose.Words

SaveOptions.PrettyFormat Property

When true, pretty formats output where applicable. Default value is false.

[Visual Basic]
Public Property PrettyFormat As Boolean
[C#]
public bool PrettyFormat {get; set;}

Remarks

Set to true to make HTML, MHTML, EPUB, WordML, RTF, DOCX and ODT output human readable. Useful for testing or debugging.

Example

Shows how to pass an option to export HTML tags in a well spaced, human readable format.

[C#]

Document doc = new Document(MyDir + "Document.doc");

HtmlSaveOptions htmlOptions = new HtmlSaveOptions(SaveFormat.Html);
// Enabling the PrettyFormat setting will export HTML in an indented format that is easy to read.
// If this is setting is false (by default) then the HTML tags will be exported in condensed form with no indentation.
htmlOptions.PrettyFormat = true;

doc.Save(ArtifactsDir + "Document.PrettyFormat.html", htmlOptions);

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

SaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used.

[Visual Basic]
MustOverride Public Property SaveFormat As SaveFormat
[C#]
public abstract SaveFormat SaveFormat {get; set;}

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


TempFolder Property

Aspose.Words

SaveOptions.TempFolder Property

Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.

[Visual Basic]
Public Property TempFolder As String
[C#]
public string TempFolder {get; set;}

Remarks

When Aspose.Words saves a document, it needs to create temporary internal structures. By default, these internal structures are created in memory and the memory usage spikes for a short period while the document is being saved. When saving is complete, the memory is freed and reclaimed by the garbage collector.

If you are saving a very large document (thousands of pages) and/or processing many documents at the same time, then the memory spike during saving can be significant enough to cause the system to throw OutOfMemoryException. Specifying a temporary folder using TempFolder will cause Aspose.Words to keep the internal structures in temporary files instead of memory. It reduces the memory usage during saving, but will decrease the save performance.

The folder must exist and be writable, otherwise an exception will be thrown.

Aspose.Words automatically deletes all temporary files when saving is complete.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


UpdateFields Property

Aspose.Words

SaveOptions.UpdateFields Property

Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.

[Visual Basic]
Public Property UpdateFields As Boolean
[C#]
public bool UpdateFields {get; set;}

Remarks

Allows to specify whether to mimic or not MS Word behaviour.

Example

Shows how to update fields before saving into a PDF document.

[C#]

Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

PdfSaveOptions pdfSaveOptions = new PdfSaveOptions
{
    UpdateFields = false
};

doc.Save(ArtifactsDir + "UpdateFields_False.pdf", pdfSaveOptions);

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


UpdateLastSavedTimeProperty Property

Aspose.Words

SaveOptions.UpdateLastSavedTimeProperty Property

Gets or sets a value determining whether the LastSavedTime property is updated before saving.

[Visual Basic]
Public Property UpdateLastSavedTimeProperty As Boolean
[C#]
public bool UpdateLastSavedTimeProperty {get; set;}

Example

Shows how to update a document time property when you want to save it

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Get last saved time
DateTime documentTimeBeforeSave = doc.BuiltInDocumentProperties.LastSavedTime;

OoxmlSaveOptions saveOptions = new OoxmlSaveOptions
{
    UpdateLastSavedTimeProperty = true
};

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


UpdateSdtContent Property

Aspose.Words

SaveOptions.UpdateSdtContent Property

Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.

[Visual Basic]
Public Property UpdateSdtContent As Boolean
[C#]
public bool UpdateSdtContent {get; set;}

Remarks

The default value is true.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


UseAntiAliasing Property

Aspose.Words

SaveOptions.UseAntiAliasing Property

Gets or sets a value determining whether or not to use anti-aliasing for rendering.

[Visual Basic]
Public Property UseAntiAliasing As Boolean
[C#]
public bool UseAntiAliasing {get; set;}

Remarks

The default value is false. When this value is set to true anti-aliasing is used for rendering.

This property is used when the document is exported to the following formats: Tiff, Png, Bmp, Jpeg, Emf. When the document is exported to the Html, Mhtml and Epub formats this option is used for raster images.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


UseHighQualityRendering Property

Aspose.Words

SaveOptions.UseHighQualityRendering Property

Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

[Visual Basic]
Public Property UseHighQualityRendering As Boolean
[C#]
public bool UseHighQualityRendering {get; set;}

Remarks

The default value is false.

This property is used when the document is exported to image formats: Tiff, Png, Bmp, Jpeg, Emf.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


SaveOptions Methods

The methods of the SaveOptions class are listed below. For a complete list of SaveOptions class members, see the SaveOptions Members topic.

Public Static (Shared) Methods

CreateSaveOptions Overloaded. Creates a save options object of a correct class.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


CreateSaveOptions Method

Aspose.Words

SaveOptions.CreateSaveOptions Method

Creates a save options object of a correct class.

Overload List

Creates a save options object of a class suitable for the specified save format.

public static SaveOptions CreateSaveOptions(SaveFormat);

Creates a save options object of a class suitable for the file extension specified in the given file name.

public static SaveOptions CreateSaveOptions(string);

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


SaveOptions.CreateSaveOptions Method (SaveFormat)

Creates a save options object of a class suitable for the specified save format.

[Visual Basic]
Overloads Public Shared Function CreateSaveOptions( _
ByVal saveFormat As SaveFormat _
) As SaveOptions
[C#]
public static SaveOptions CreateSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
The save format for which to create a save options object.

Return Value

An object of a class that derives from SaveOptions.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace | SaveOptions.CreateSaveOptions Overload List


SaveOptions.CreateSaveOptions Method (String)

Creates a save options object of a class suitable for the file extension specified in the given file name.

[Visual Basic]
Overloads Public Shared Function CreateSaveOptions( _
ByVal fileName As String _
) As SaveOptions
[C#]
public static SaveOptions CreateSaveOptions(
string fileName
);

Parameters

fileName
The extension of this file name determines the class of the save options object to create.

Return Value

An object of a class that derives from SaveOptions.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace | SaveOptions.CreateSaveOptions Overload List


SaveOutputParameters Class

This object is returned to the caller after a document is saved and contains additional information that has been generated or calculated during the save operation. The caller can use or ignore this object.

For a list of all members of this type, see SaveOutputParameters Members.

System.Object
Aspose.Words.Saving.SaveOutputParameters

[Visual Basic]
Public Class SaveOutputParameters
[C#]
public class SaveOutputParameters

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SaveOutputParameters Members | Aspose.Words.Saving Namespace


SaveOutputParameters Members

SaveOutputParameters overview

Public Instance Properties

ContentType Returns the Content-Type string (Internet Media Type) that identifies the type of the saved document.

See Also

SaveOutputParameters Class | Aspose.Words.Saving Namespace


SaveOutputParameters Properties

The properties of the SaveOutputParameters class are listed below. For a complete list of SaveOutputParameters class members, see the SaveOutputParameters Members topic.

Public Instance Properties

ContentType Returns the Content-Type string (Internet Media Type) that identifies the type of the saved document.

See Also

SaveOutputParameters Class | Aspose.Words.Saving Namespace


ContentType Property

Aspose.Words

SaveOutputParameters.ContentType Property

Returns the Content-Type string (Internet Media Type) that identifies the type of the saved document.

[Visual Basic]
Public ReadOnly Property ContentType As String
[C#]
public string ContentType {get;}

See Also

SaveOutputParameters Class | Aspose.Words.Saving Namespace


SvgSaveOptions Class

Can be used to specify additional options when saving a document into the Svg format.

For a list of all members of this type, see SvgSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.SvgSaveOptions

[Visual Basic]
Public Class SvgSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class SvgSaveOptions : FixedPageSaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

SvgSaveOptions Members | Aspose.Words.Saving Namespace


SvgSaveOptions Members

SvgSaveOptions overview

Public Instance Constructors

SvgSaveOptions Constructor Initializes a new instance of the SvgSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
ExportEmbeddedImages | Specified whether images should be embedded into SVG document as base64. Note setting this flag can significantly increase size of output SVG file.
FitToViewPort | Specifies if the output SVG should fill the available viewport area (browser window or container). When set to true width and height of output SVG are set to 100%. The default value is false.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResourceSavingCallback | Allows to control how resources (images) are saved when a document is exported to SVG format.
ResourcesFolder | Specifies the physical folder where resources (images) are saved when exporting a document to Svg format. Default is null.
ResourcesFolderAlias | Specifies the name of the folder used to construct image URIs written into an SVG document. Default is null.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Svg.
ShowPageBorder | Controls whether a border is added to the outline of the page. Default is true.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
TextOutputMode | Gets or sets a value determining how text should be rendered in SVG. Use this property to get or set the mode of how text inside a document should be rendered when saving in SVG format. The default value is UseTargetMachineFonts.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Public Instance Methods

Equals (inherited from FixedPageSaveOptions)

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


SvgSaveOptions Constructor

Initializes a new instance of the SvgSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public SvgSaveOptions();

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


SvgSaveOptions Properties

The properties of the SvgSaveOptions class are listed below. For a complete list of SvgSaveOptions class members, see the SvgSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
ExportEmbeddedImages | Specified whether images should be embedded into SVG document as base64. Note setting this flag can significantly increase size of output SVG file.
FitToViewPort | Specifies if the output SVG should fill the available viewport area (browser window or container). When set to true width and height of output SVG are set to 100%. The default value is false.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResourceSavingCallback | Allows to control how resources (images) are saved when a document is exported to SVG format.
ResourcesFolder | Specifies the physical folder where resources (images) are saved when exporting a document to Svg format. Default is null.
ResourcesFolderAlias | Specifies the name of the folder used to construct image URIs written into an SVG document. Default is null.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Svg.
ShowPageBorder | Controls whether a border is added to the outline of the page. Default is true.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
TextOutputMode | Gets or sets a value determining how text should be rendered in SVG. Use this property to get or set the mode of how text inside a document should be rendered when saving in SVG format. The default value is UseTargetMachineFonts.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


ExportEmbeddedImages Property

Aspose.Words

SvgSaveOptions.ExportEmbeddedImages Property

Specified whether images should be embedded into SVG document as base64. Note setting this flag can significantly increase size of output SVG file.

[Visual Basic]
Public Property ExportEmbeddedImages As Boolean
[C#]
public bool ExportEmbeddedImages {get; set;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


FitToViewPort Property

Aspose.Words

SvgSaveOptions.FitToViewPort Property

Specifies if the output SVG should fill the available viewport area (browser window or container). When set to true width and height of output SVG are set to 100%.

The default value is false.

[Visual Basic]
Public Property FitToViewPort As Boolean
[C#]
public bool FitToViewPort {get; set;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


ResourceSavingCallback Property

Aspose.Words

SvgSaveOptions.ResourceSavingCallback Property

Allows to control how resources (images) are saved when a document is exported to SVG format.

[Visual Basic]
Public Property ResourceSavingCallback As IResourceSavingCallback
[C#]
public IResourceSavingCallback ResourceSavingCallback {get; set;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


ResourcesFolder Property

Aspose.Words

SvgSaveOptions.ResourcesFolder Property

Specifies the physical folder where resources (images) are saved when exporting a document to Svg format. Default is null.

[Visual Basic]
Public Property ResourcesFolder As String
[C#]
public string ResourcesFolder {get; set;}

Remarks

Has effect only if ExportEmbeddedImages property is false.

When you save a Document in SVG format, Aspose.Words needs to save all images embedded in the document as standalone files. ResourcesFolder allows you to specify where the images will be saved and ResourcesFolderAlias allows to specify how the image URIs will be constructed.

If you save a document into a file and provide a file name, Aspose.Words, by default, saves the images in the same folder where the document file is saved. Use ResourcesFolder to override this behavior.

If you save a document into a stream, Aspose.Words does not have a folder where to save the images, but still needs to save the images somewhere. In this case, you need to specify an accessible folder in the ResourcesFolder property

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace | ResourcesFolderAlias


ResourcesFolderAlias Property

Aspose.Words

SvgSaveOptions.ResourcesFolderAlias Property

Specifies the name of the folder used to construct image URIs written into an SVG document. Default is null.

[Visual Basic]
Public Property ResourcesFolderAlias As String
[C#]
public string ResourcesFolderAlias {get; set;}

Remarks

When you save a Document in SVG format, Aspose.Words needs to save all images embedded in the document as standalone files. ResourcesFolder allows you to specify where the images will be saved and ResourcesFolderAlias allows to specify how the image URIs will be constructed.

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace | ResourcesFolder


SaveFormat Property

Aspose.Words

SvgSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Svg.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


ShowPageBorder Property

Aspose.Words

SvgSaveOptions.ShowPageBorder Property

Controls whether a border is added to the outline of the page. Default is true.

[Visual Basic]
Public Property ShowPageBorder As Boolean
[C#]
public bool ShowPageBorder {get; set;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


TextOutputMode Property

Aspose.Words

SvgSaveOptions.TextOutputMode Property

Gets or sets a value determining how text should be rendered in SVG.

Use this property to get or set the mode of how text inside a document should be rendered when saving in SVG format.

The default value is UseTargetMachineFonts.

[Visual Basic]
Public Property TextOutputMode As SvgTextOutputMode
[C#]
public SvgTextOutputMode TextOutputMode {get; set;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


SvgTextOutputMode Enumeration

[Visual Basic]
Public Enum SvgTextOutputMode
[C#]
public enum SvgTextOutputMode

Members

Member Name | Description | Value
UseSvgFonts | SVG fonts are used to render text. Note, not all browsers support SVG fonts. | 0
UseTargetMachineFonts | Fonts installed on the target machine are used to render text. Note, if some of fonts used in the document are not available on the target machine, document can look differently. | 1
UsePlacedGlyphs | Text is rendered using curves. Note, text selection will not work if you use this option. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


TiffCompression Enumeration

Specifies what type of compression to apply when saving page images into a TIFF file.

[Visual Basic]
Public Enum TiffCompression
[C#]
public enum TiffCompression

Example

Converts a page of a Word document into a TIFF image and uses the CCITT compression.

[C#]

Document doc = new Document(MyDir + "Rendering.doc");

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff)
{
    TiffCompression = TiffCompression.Ccitt3,
    PageIndex = 0,
    PageCount = 1
};

doc.Save(ArtifactsDir + "Rendering.SaveToTiffCompression.tiff", options);

Members

Member Name | Description | Value
None | Specifies no compression. | 0
Rle | Specifies the RLE compression scheme. | 1
Lzw | Specifies the LZW compression scheme. In Java emulated by Deflate (Zip) compression. | 2
Ccitt3 | Specifies the CCITT3 compression scheme. | 3
Ccitt4 | Specifies the CCITT4 compression scheme. | 4

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


TxtExportHeadersFootersMode Enumeration

Specifies the way headers and footers are exported to plain text format.

[Visual Basic]
Public Enum TxtExportHeadersFootersMode
[C#]
public enum TxtExportHeadersFootersMode

Example

Shows how to specifies the way headers and footers are exported to plain text format.

[C#]

Document doc = new Document(MyDir + "HeaderFooter.HeaderFooterOrder.docx");

// Three values are available in TxtExportHeadersFootersMode enum:
// "None" - No headers and footers are exported
// "AllAtEnd" - All headers and footers are placed after all section bodies at the very end of a document
// "PrimaryOnly" - Only primary headers and footers are exported at the beginning and end of each section (default value)
TxtSaveOptions saveOptions = new TxtSaveOptions { ExportHeadersFootersMode = txtExportHeadersFootersMode };

doc.Save(ArtifactsDir + "ExportHeadersFooters.txt", saveOptions);

Members

Member Name | Description | Value
None | No headers and footers are exported. | 0
PrimaryOnly | Only primary headers and footers are exported at the beginning and end of each section. | 1
AllAtEnd | All headers and footers are placed after all section bodies at the very end of a document. | 2

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Saving Namespace


TxtListIndentation Class

Specifies how list levels are indented when document is exporting to Text format.

For a list of all members of this type, see TxtListIndentation Members.

System.Object
Aspose.Words.Saving.TxtListIndentation

[Visual Basic]
Public Class TxtListIndentation
[C#]
public class TxtListIndentation

Example

Shows how list levels are displayed when the document is converting to plain text format

[C#]

Document doc = new Document(MyDir + "TxtSaveOptions.TxtListIndentation.docx");

TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
txtSaveOptions.ListIndentation.Count = 3;
txtSaveOptions.ListIndentation.Character = ' ';
txtSaveOptions.PreserveTableLayout = true;

doc.Save(ArtifactsDir + "TxtSaveOptions.TxtListIndentation.txt", txtSaveOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TxtListIndentation Members | Aspose.Words.Saving Namespace


TxtListIndentation Members

TxtListIndentation overview

Public Instance Constructors

TxtListIndentation Constructor Initializes a new instance of the TxtListIndentation class.

Public Instance Properties

Character | Gets or sets which character to use for indenting list levels. The default value is '\0', that means there is no indentation.
Count | Gets or sets how many Character to use as indentation per one list level. The default value is 0, that means no indentation.

See Also

TxtListIndentation Class | Aspose.Words.Saving Namespace


TxtListIndentation Constructor

Initializes a new instance of the TxtListIndentation class.

[Visual Basic]
Public Sub New()
[C#]
public TxtListIndentation();

See Also

TxtListIndentation Class | Aspose.Words.Saving Namespace


TxtListIndentation Properties

The properties of the TxtListIndentation class are listed below. For a complete list of TxtListIndentation class members, see the TxtListIndentation Members topic.

Public Instance Properties

Character | Gets or sets which character to use for indenting list levels. The default value is '\0', that means there is no indentation.
Count | Gets or sets how many Character to use as indentation per one list level. The default value is 0, that means no indentation.

See Also

TxtListIndentation Class | Aspose.Words.Saving Namespace


Character Property

Aspose.Words

TxtListIndentation.Character Property

Gets or sets which character to use for indenting list levels. The default value is '\0', that means there is no indentation.

[Visual Basic]
Public Property Character As Char
[C#]
public char Character {get; set;}

Example

Shows how list levels are displayed when the document is converting to plain text format

[C#]

Document doc = new Document(MyDir + "TxtSaveOptions.TxtListIndentation.docx");

TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
txtSaveOptions.ListIndentation.Count = 3;
txtSaveOptions.ListIndentation.Character = ' ';
txtSaveOptions.PreserveTableLayout = true;

doc.Save(ArtifactsDir + "TxtSaveOptions.TxtListIndentation.txt", txtSaveOptions);

See Also

TxtListIndentation Class | Aspose.Words.Saving Namespace


Count Property

Aspose.Words

TxtListIndentation.Count Property

Gets or sets how many Character to use as indentation per one list level. The default value is 0, that means no indentation.

[Visual Basic]
Public Property Count As Integer
[C#]
public int Count {get; set;}

Example

Shows how list levels are displayed when the document is converting to plain text format

[C#]

Document doc = new Document(MyDir + "TxtSaveOptions.TxtListIndentation.docx");

TxtSaveOptions txtSaveOptions = new TxtSaveOptions();
txtSaveOptions.ListIndentation.Count = 3;
txtSaveOptions.ListIndentation.Character = ' ';
txtSaveOptions.PreserveTableLayout = true;

doc.Save(ArtifactsDir + "TxtSaveOptions.TxtListIndentation.txt", txtSaveOptions);

See Also

TxtListIndentation Class | Aspose.Words.Saving Namespace


TxtSaveOptions Class

Can be used to specify additional options when saving a document into the Text format.

For a list of all members of this type, see TxtSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.TxtSaveOptionsBase
Aspose.Words.Saving.TxtSaveOptions

[Visual Basic]
Public Class TxtSaveOptions
Inherits TxtSaveOptionsBase
[C#]
public class TxtSaveOptions : TxtSaveOptionsBase

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TxtSaveOptions Members | Aspose.Words.Saving Namespace


TxtSaveOptions Members

TxtSaveOptions overview

Public Instance Constructors

TxtSaveOptions Constructor Initializes a new instance of the TxtSaveOptions class.

Public Instance Properties

AddBidiMarks | Specifies whether to add bi-directional marks before each BiDi run when exporting in plain text format. The default value is false.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
Encoding (inherited from TxtSaveOptionsBase) | Specifies the encoding to use when exporting in text formats. Default value is Encoding.UTF8.
ExportHeadersFootersMode (inherited from TxtSaveOptionsBase) | Specifies the way headers and footers are exported to the text formats. Default value is PrimaryOnly.
ForcePageBreaks (inherited from TxtSaveOptionsBase) | Allows to specify whether the page breaks should be preserved during export. The default value is false.
ListIndentation | Gets a ListIndentation object that specifies how many and which character to use for indentation of list levels. By default it is zero count of character '\0', that means no indentation.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
ParagraphBreak (inherited from TxtSaveOptionsBase) | Specifies the string to use as a paragraph break when exporting in text formats.
PreserveTableLayout (inherited from TxtSaveOptionsBase) | Specifies whether the program should attempt to preserve layout of tables when saving in the plain text format. The default value is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Text.
SimplifyListLabels | Specifies whether the program should simplify list labels in case of complex label formatting not being adequately represented by plain text. If set to true, numbered list labels are written in simple numeric format and itemized list labels as simple ASCII characters. The default value is false.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


TxtSaveOptions Constructor

Initializes a new instance of the TxtSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public TxtSaveOptions();

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


TxtSaveOptions Properties

The properties of the TxtSaveOptions class are listed below. For a complete list of TxtSaveOptions class members, see the TxtSaveOptions Members topic.

Public Instance Properties

AddBidiMarks | Specifies whether to add bi-directional marks before each BiDi run when exporting in plain text format. The default value is false.
ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
Encoding (inherited from TxtSaveOptionsBase) | Specifies the encoding to use when exporting in text formats. Default value is Encoding.UTF8.
ExportHeadersFootersMode (inherited from TxtSaveOptionsBase) | Specifies the way headers and footers are exported to the text formats. Default value is PrimaryOnly.
ForcePageBreaks (inherited from TxtSaveOptionsBase) | Allows to specify whether the page breaks should be preserved during export. The default value is false.
ListIndentation | Gets a ListIndentation object that specifies how many and which character to use for indentation of list levels. By default it is zero count of character '\0', that means no indentation.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
ParagraphBreak (inherited from TxtSaveOptionsBase) | Specifies the string to use as a paragraph break when exporting in text formats.
PreserveTableLayout (inherited from TxtSaveOptionsBase) | Specifies whether the program should attempt to preserve layout of tables when saving in the plain text format. The default value is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Text.
SimplifyListLabels | Specifies whether the program should simplify list labels in case of complex label formatting not being adequately represented by plain text. If set to true, numbered list labels are written in simple numeric format and itemized list labels as simple ASCII characters. The default value is false.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


AddBidiMarks Property

Aspose.Words

TxtSaveOptions.AddBidiMarks Property

Specifies whether to add bi-directional marks before each BiDi run when exporting in plain text format.

The default value is false.

[Visual Basic]
Public Property AddBidiMarks As Boolean
[C#]
public bool AddBidiMarks {get; set;}

Example

Shows how to insert Unicode Character 'RIGHT-TO-LEFT MARK' (U+200F) before each bi-directional Run in text.

[C#]

Document doc = new Document(MyDir + "Document.docx");

TxtSaveOptions saveOptions = new TxtSaveOptions { AddBidiMarks = true };

doc.Save(ArtifactsDir + "AddBidiMarks.txt", saveOptions);

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


ListIndentation Property

Aspose.Words

TxtSaveOptions.ListIndentation Property

Gets a ListIndentation object that specifies how many and which character to use for indentation of list levels. By default it is zero count of character '\0', that means no indentation.

[Visual Basic]
Public ReadOnly Property ListIndentation As TxtListIndentation
[C#]
public TxtListIndentation ListIndentation {get;}

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

TxtSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Text.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


SimplifyListLabels Property

Aspose.Words

TxtSaveOptions.SimplifyListLabels Property

Specifies whether the program should simplify list labels in case of complex label formatting not being adequately represented by plain text.

If set to true, numbered list labels are written in simple numeric format and itemized list labels as simple ASCII characters. The default value is false.

[Visual Basic]
Public Property SimplifyListLabels As Boolean
[C#]
public bool SimplifyListLabels {get; set;}

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


TxtSaveOptionsBase Class

The base class for specifying additional options when saving a document into a text based formats.

For a list of all members of this type, see TxtSaveOptionsBase Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.TxtSaveOptionsBase
Aspose.Words.Saving.TxtSaveOptions

[Visual Basic]
MustInherit Public Class TxtSaveOptionsBase
Inherits SaveOptions
[C#]
public abstract class TxtSaveOptionsBase : SaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TxtSaveOptionsBase Members | Aspose.Words.Saving Namespace


TxtSaveOptionsBase Members

TxtSaveOptionsBase overview

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
Encoding | Specifies the encoding to use when exporting in text formats. Default value is Encoding.UTF8.
ExportHeadersFootersMode | Specifies the way headers and footers are exported to the text formats. Default value is PrimaryOnly.
ForcePageBreaks | Allows to specify whether the page breaks should be preserved during export. The default value is false.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
ParagraphBreak | Specifies the string to use as a paragraph break when exporting in text formats.
PreserveTableLayout | Specifies whether the program should attempt to preserve layout of tables when saving in the plain text format. The default value is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat (inherited from SaveOptions) | Specifies the format in which the document will be saved if this save options object is used.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


TxtSaveOptionsBase Properties

The properties of the TxtSaveOptionsBase class are listed below. For a complete list of TxtSaveOptionsBase class members, see the TxtSaveOptionsBase Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
Encoding | Specifies the encoding to use when exporting in text formats. Default value is Encoding.UTF8.
ExportHeadersFootersMode | Specifies the way headers and footers are exported to the text formats. Default value is PrimaryOnly.
ForcePageBreaks | Allows to specify whether the page breaks should be preserved during export. The default value is false.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
ParagraphBreak | Specifies the string to use as a paragraph break when exporting in text formats.
PreserveTableLayout | Specifies whether the program should attempt to preserve layout of tables when saving in the plain text format. The default value is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat (inherited from SaveOptions) | Specifies the format in which the document will be saved if this save options object is used.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


Encoding Property

Aspose.Words

TxtSaveOptionsBase.Encoding Property

Specifies the encoding to use when exporting in text formats. Default value is Encoding.UTF8.

[Visual Basic]
Public Property Encoding As Encoding
[C#]
public Encoding Encoding {get; set;}

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


ExportHeadersFootersMode Property

Aspose.Words

TxtSaveOptionsBase.ExportHeadersFootersMode Property

Specifies the way headers and footers are exported to the text formats. Default value is PrimaryOnly.

[Visual Basic]
Public Property ExportHeadersFootersMode As TxtExportHeadersFootersMode
[C#]
public TxtExportHeadersFootersMode ExportHeadersFootersMode {get; set;}

Example

Shows how to specifies the way headers and footers are exported to plain text format.

[C#]

Document doc = new Document(MyDir + "HeaderFooter.HeaderFooterOrder.docx");

// Three values are available in TxtExportHeadersFootersMode enum:
// "None" - No headers and footers are exported
// "AllAtEnd" - All headers and footers are placed after all section bodies at the very end of a document
// "PrimaryOnly" - Only primary headers and footers are exported at the beginning and end of each section (default value)
TxtSaveOptions saveOptions = new TxtSaveOptions { ExportHeadersFootersMode = txtExportHeadersFootersMode };

doc.Save(ArtifactsDir + "ExportHeadersFooters.txt", saveOptions);

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


ForcePageBreaks Property

Aspose.Words

TxtSaveOptionsBase.ForcePageBreaks Property

Allows to specify whether the page breaks should be preserved during export.

The default value is false.

[Visual Basic]
Public Property ForcePageBreaks As Boolean
[C#]
public bool ForcePageBreaks {get; set;}

Remarks

The property affects only page breaks that are inserted explicitly into a document. It is not related to page breaks that MS Word automatically inserts at the end of each page.

Example

Shows how to specify whether the page breaks should be preserved during export.

[C#]

Document doc = new Document(MyDir + "SaveOptions.PageBreaks.docx");

TxtSaveOptions saveOptions = new TxtSaveOptions { ForcePageBreaks = false };

doc.Save(ArtifactsDir + "SaveOptions.PageBreaks.txt", saveOptions);

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


ParagraphBreak Property

Aspose.Words

TxtSaveOptionsBase.ParagraphBreak Property

Specifies the string to use as a paragraph break when exporting in text formats.

[Visual Basic]
Public Property ParagraphBreak As String
[C#]
public string ParagraphBreak {get; set;}

Remarks

The default value is CrLf.

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


PreserveTableLayout Property

Aspose.Words

TxtSaveOptionsBase.PreserveTableLayout Property

Specifies whether the program should attempt to preserve layout of tables when saving in the plain text format. The default value is false.

[Visual Basic]
Public Property PreserveTableLayout As Boolean
[C#]
public bool PreserveTableLayout {get; set;}

See Also

TxtSaveOptionsBase Class | Aspose.Words.Saving Namespace


WordML2003SaveOptions Class

Can be used to specify additional options when saving a document into the WordML format.

For a list of all members of this type, see WordML2003SaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.WordML2003SaveOptions

[Visual Basic]
Public Class WordML2003SaveOptions
Inherits SaveOptions
[C#]
public class WordML2003SaveOptions : SaveOptions

Remarks

At the moment provides only the SaveFormat property, but in the future may have other options added.

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

WordML2003SaveOptions Members | Aspose.Words.Saving Namespace


WordML2003SaveOptions Members

WordML2003SaveOptions overview

Public Instance Constructors

WordML2003SaveOptions Constructor Initializes a new instance of the WordML2003SaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be WordML.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

WordML2003SaveOptions Class | Aspose.Words.Saving Namespace


WordML2003SaveOptions Constructor

Initializes a new instance of the WordML2003SaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public WordML2003SaveOptions();

See Also

WordML2003SaveOptions Class | Aspose.Words.Saving Namespace


WordML2003SaveOptions Properties

The properties of the WordML2003SaveOptions class are listed below. For a complete list of WordML2003SaveOptions class members, see the WordML2003SaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be WordML.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

WordML2003SaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

WordML2003SaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be WordML.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

WordML2003SaveOptions Class | Aspose.Words.Saving Namespace


XamlFixedSaveOptions Class

Can be used to specify additional options when saving a document into the XamlFixed format.

For a list of all members of this type, see XamlFixedSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.XamlFixedSaveOptions

[Visual Basic]
Public Class XamlFixedSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class XamlFixedSaveOptions : FixedPageSaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

XamlFixedSaveOptions Members | Aspose.Words.Saving Namespace


XamlFixedSaveOptions Members

XamlFixedSaveOptions overview

Public Instance Constructors

XamlFixedSaveOptions Constructor Initializes a new instance of the XamlFixedSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResourceSavingCallback | Allows to control how resources (images and fonts) are saved when a document is exported to fixed page Xaml format.
ResourcesFolder | Specifies the physical folder where resources (images and fonts) are saved when exporting a document to fixed page Xaml format. Default is null.
ResourcesFolderAlias | Specifies the name of the folder used to construct image URIs written into an fixed page Xaml document. Default is null.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be XamlFixed.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Public Instance Methods

Equals (inherited from FixedPageSaveOptions)

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


XamlFixedSaveOptions Constructor

Initializes a new instance of the XamlFixedSaveOptions class.

[Visual Basic]
Public Sub New()
[C#]
public XamlFixedSaveOptions();

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


XamlFixedSaveOptions Properties

The properties of the XamlFixedSaveOptions class are listed below. For a complete list of XamlFixedSaveOptions class members, see the XamlFixedSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
ResourceSavingCallback | Allows to control how resources (images and fonts) are saved when a document is exported to fixed page Xaml format.
ResourcesFolder | Specifies the physical folder where resources (images and fonts) are saved when exporting a document to fixed page Xaml format. Default is null.
ResourcesFolderAlias | Specifies the name of the folder used to construct image URIs written into an fixed page Xaml document. Default is null.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be XamlFixed.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ResourceSavingCallback Property

Aspose.Words

XamlFixedSaveOptions.ResourceSavingCallback Property

Allows to control how resources (images and fonts) are saved when a document is exported to fixed page Xaml format.

[Visual Basic]
Public Property ResourceSavingCallback As IResourceSavingCallback
[C#]
public IResourceSavingCallback ResourceSavingCallback {get; set;}

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


ResourcesFolder Property

Aspose.Words

XamlFixedSaveOptions.ResourcesFolder Property

Specifies the physical folder where resources (images and fonts) are saved when exporting a document to fixed page Xaml format. Default is null.

[Visual Basic]
Public Property ResourcesFolder As String
[C#]
public string ResourcesFolder {get; set;}

Remarks

When you save a Document in fixed page Xaml format, Aspose.Words needs to save all images embedded in the document as standalone files. ResourcesFolder allows you to specify where the images will be saved and ResourcesFolderAlias allows to specify how the image URIs will be constructed.

If you save a document into a file and provide a file name, Aspose.Words, by default, saves the images in the same folder where the document file is saved. Use ResourcesFolder to override this behavior.

If you save a document into a stream, Aspose.Words does not have a folder where to save the images, but still needs to save the images somewhere. In this case, you need to specify an accessible folder by using the ResourcesFolder property

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace | ResourcesFolderAlias


ResourcesFolderAlias Property

Aspose.Words

XamlFixedSaveOptions.ResourcesFolderAlias Property

Specifies the name of the folder used to construct image URIs written into an fixed page Xaml document. Default is null.

[Visual Basic]
Public Property ResourcesFolderAlias As String
[C#]
public string ResourcesFolderAlias {get; set;}

Remarks

When you save a Document in fixed page Xaml format, Aspose.Words needs to save all images embedded in the document as standalone files. ResourcesFolder allows you to specify where the images will be saved and ResourcesFolderAlias allows to specify how the image URIs will be constructed.

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace | ResourcesFolder


SaveFormat Property

Aspose.Words

XamlFixedSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be XamlFixed.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


XamlFlowSaveOptions Class

Can be used to specify additional options when saving a document into the XamlFlow or XamlFlowPack format.

For a list of all members of this type, see XamlFlowSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.XamlFlowSaveOptions

[Visual Basic]
Public Class XamlFlowSaveOptions
Inherits SaveOptions
[C#]
public class XamlFlowSaveOptions : SaveOptions

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

XamlFlowSaveOptions Members | Aspose.Words.Saving Namespace


XamlFlowSaveOptions Members

XamlFlowSaveOptions overview

Public Instance Constructors

XamlFlowSaveOptions Overloaded. Initializes a new instance of the XamlFlowSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
ImageSavingCallback | Allows to control how images are saved when a document is saved to XAML.
ImagesFolder | Specifies the physical folder where images are saved when exporting a document to XAML format. Default is an empty string.
ImagesFolderAlias | Specifies the name of the folder used to construct image URIs written into an XAML document. Default is an empty string.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be XamlFlow.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace


XamlFlowSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the XamlFlow format.

Overload List

Initializes a new instance of this class that can be used to save a document in the XamlFlow format.

public XamlFlowSaveOptions();

Initializes a new instance of this class that can be used to save a document in the XamlFlow or XamlFlowPack format.

public XamlFlowSaveOptions(SaveFormat);

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace


XamlFlowSaveOptions Constructor ()

Initializes a new instance of this class that can be used to save a document in the XamlFlow format.

[Visual Basic]
Overloads Public Sub New()
[C#]
public XamlFlowSaveOptions();

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace | XamlFlowSaveOptions Constructor Overload List


XamlFlowSaveOptions Constructor (SaveFormat)

Initializes a new instance of this class that can be used to save a document in the XamlFlow or XamlFlowPack format.

[Visual Basic]
Overloads Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public XamlFlowSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be XamlFlow or XamlFlowPack.

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace | XamlFlowSaveOptions Constructor Overload List


XamlFlowSaveOptions Properties

The properties of the XamlFlowSaveOptions class are listed below. For a complete list of XamlFlowSaveOptions class members, see the XamlFlowSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
ImageSavingCallback | Allows to control how images are saved when a document is saved to XAML.
ImagesFolder | Specifies the physical folder where images are saved when exporting a document to XAML format. Default is an empty string.
ImagesFolderAlias | Specifies the name of the folder used to construct image URIs written into an XAML document. Default is an empty string.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be XamlFlow.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace


ImageSavingCallback Property

Aspose.Words

XamlFlowSaveOptions.ImageSavingCallback Property

Allows to control how images are saved when a document is saved to XAML.

[Visual Basic]
Public Property ImageSavingCallback As IImageSavingCallback
[C#]
public IImageSavingCallback ImageSavingCallback {get; set;}

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace


ImagesFolder Property

Aspose.Words

XamlFlowSaveOptions.ImagesFolder Property

Specifies the physical folder where images are saved when exporting a document to XAML format. Default is an empty string.

[Visual Basic]
Public Property ImagesFolder As String
[C#]
public string ImagesFolder {get; set;}

Remarks

When you save a Document in XAML format, Aspose.Words needs to save all images embedded in the document as standalone files. ImagesFolder allows you to specify where the images will be saved and ImagesFolderAlias allows to specify how the image URIs will be constructed.

If you save a document into a file and provide a file name, Aspose.Words, by default, saves the images in the same folder where the document file is saved. Use ImagesFolder to override this behavior.

If you save a document into a stream, Aspose.Words does not have a folder where to save the images, but still needs to save the images somewhere. In this case, you need to specify an accessible folder in the ImagesFolder property or provide custom streams via the ImageSavingCallback event handler.

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace | ImagesFolderAlias | ImageSavingCallback


ImagesFolderAlias Property

Aspose.Words

XamlFlowSaveOptions.ImagesFolderAlias Property

Specifies the name of the folder used to construct image URIs written into an XAML document. Default is an empty string.

[Visual Basic]
Public Property ImagesFolderAlias As String
[C#]
public string ImagesFolderAlias {get; set;}

Remarks

When you save a Document in XAML format, Aspose.Words needs to save all images embedded in the document as standalone files. ImagesFolder allows you to specify where the images will be saved and ImagesFolderAlias allows to specify how the image URIs will be constructed.

If ImagesFolderAlias is not an empty string, then the image URI written to XAML will be ImagesFolderAlias + <image file name>.

If ImagesFolderAlias is an empty string, then the image URI written to XAML will be ImagesFolder + <image file name>.

If ImagesFolderAlias is set to '.' (dot), then the image file name will be written to XAML without path regardless of other options.

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace | ImagesFolder | ImageSavingCallback


SaveFormat Property

Aspose.Words

XamlFlowSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be XamlFlow.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

XamlFlowSaveOptions Class | Aspose.Words.Saving Namespace


XpsSaveOptions Class

Can be used to specify additional options when saving a document into the Xps format.

For a list of all members of this type, see XpsSaveOptions Members.

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.XpsSaveOptions

[Visual Basic]
Public Class XpsSaveOptions
Inherits FixedPageSaveOptions
[C#]
public class XpsSaveOptions : FixedPageSaveOptions

Example

Shows how to save a document to the XPS format using the Save method and the XpsSaveOptions class.

[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save document to file in the XPS format with default options
doc.Save(ArtifactsDir + "Rendering.XpsDefaultOptions.xps");

// Save document to stream in the XPS format with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Xps);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to file in the XPS format with specified options
// Render the first page only
XpsSaveOptions xpsOptions = new XpsSaveOptions();
xpsOptions.PageIndex = 0;
xpsOptions.PageCount = 1;
doc.Save(ArtifactsDir + "Rendering.XpsCustomOptions.xps", xpsOptions);

Requirements

Namespace: Aspose.Words.Saving

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

XpsSaveOptions Members | Aspose.Words.Saving Namespace


XpsSaveOptions Members

XpsSaveOptions overview

Public Instance Constructors

XpsSaveOptions Overloaded. Initializes a new instance of the XpsSaveOptions class.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
OutlineOptions | Allows to specify outline options.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Xps.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseBookFoldPrintingSettings | Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Public Instance Methods

Equals (inherited from FixedPageSaveOptions)

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


XpsSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Xps format.

Overload List

Initializes a new instance of this class that can be used to save a document in the Xps format.

public XpsSaveOptions();

Initializes a new instance of this class that can be used to save a document in the Xps or OpenXps format.

public XpsSaveOptions(SaveFormat);

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


XpsSaveOptions Constructor ()

Initializes a new instance of this class that can be used to save a document in the Xps format.

[Visual Basic]
Overloads Public Sub New()
[C#]
public XpsSaveOptions();

Example

Shows how to save a document to the XPS format using the Save method and the XpsSaveOptions class.

[C#]

// Open the document
Document doc = new Document(MyDir + "Rendering.doc");
// Save document to file in the XPS format with default options
doc.Save(ArtifactsDir + "Rendering.XpsDefaultOptions.xps");

// Save document to stream in the XPS format with default options
MemoryStream docStream = new MemoryStream();
doc.Save(docStream, SaveFormat.Xps);
// Rewind the stream position back to the beginning, ready for use
docStream.Seek(0, SeekOrigin.Begin);

// Save document to file in the XPS format with specified options
// Render the first page only
XpsSaveOptions xpsOptions = new XpsSaveOptions();
xpsOptions.PageIndex = 0;
xpsOptions.PageCount = 1;
doc.Save(ArtifactsDir + "Rendering.XpsCustomOptions.xps", xpsOptions);

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace | XpsSaveOptions Constructor Overload List


XpsSaveOptions Constructor (SaveFormat)

Initializes a new instance of this class that can be used to save a document in the Xps or OpenXps format.

[Visual Basic]
Overloads Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public XpsSaveOptions(
SaveFormat saveFormat
);

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace | XpsSaveOptions Constructor Overload List


XpsSaveOptions Properties

The properties of the XpsSaveOptions class are listed below. For a complete list of XpsSaveOptions class members, see the XpsSaveOptions Members topic.

Public Instance Properties

ColorMode (inherited from SaveOptions) | Gets or sets a value determining how colors are rendered.
DefaultTemplate (inherited from SaveOptions) | Gets or sets path to default template (including filename). Default value for this property is empty string (Empty).
DmlEffectsRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode (inherited from SaveOptions) | Gets or sets a value determining how DrawingML shapes are rendered.
JpegQuality (inherited from FixedPageSaveOptions) | Gets or sets a value determining the quality of the JPEG images inside Html document.
MemoryOptimization (inherited from SaveOptions) | Gets or sets value determining if memory optimization should be performed before saving the document. Default value for this property is false.
MetafileRenderingOptions (inherited from FixedPageSaveOptions) | Allows to specify metafile rendering options.
NumeralFormat (inherited from FixedPageSaveOptions) | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OptimizeOutput (inherited from FixedPageSaveOptions) | Flag indicates whether it is required to optimize output. If this flag is set redundant nested canvases and empty canvases are removed, also neighbor glyphs with the same formatting are concatenated. Note: The accuracy of the content display may be affected if this property is set to true. Default is false.
OutlineOptions | Allows to specify outline options.
PageCount (inherited from FixedPageSaveOptions) | Gets or sets the number of pages to save. Default is MaxValue which means all pages of the document will be rendered.
PageIndex (inherited from FixedPageSaveOptions) | Gets or sets the 0-based index of the first page to save. Default is 0.
PageSavingCallback (inherited from FixedPageSaveOptions) | Allows to control how separate pages are saved when a document is exported to fixed page format.
PrettyFormat (inherited from SaveOptions) | When true, pretty formats output where applicable. Default value is false.
SaveFormat | Specifies the format in which the document will be saved if this save options object is used. Can only be Xps.
TempFolder (inherited from SaveOptions) | Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.
UpdateFields (inherited from SaveOptions) | Gets or sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true.
UpdateLastSavedTimeProperty (inherited from SaveOptions) | Gets or sets a value determining whether the LastSavedTime property is updated before saving.
UpdateSdtContent (inherited from SaveOptions) | Gets or sets value determining whether content of StructuredDocumentTag is updated before saving.
UseAntiAliasing (inherited from SaveOptions) | Gets or sets a value determining whether or not to use anti-aliasing for rendering.
UseBookFoldPrintingSettings | Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


OutlineOptions Property

Aspose.Words

XpsSaveOptions.OutlineOptions Property

Allows to specify outline options.

[Visual Basic]
Public ReadOnly Property OutlineOptions As OutlineOptions
[C#]
public OutlineOptions OutlineOptions {get;}

Remarks

Note that ExpandedOutlineLevels option will not work when saving to XPS.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

XpsSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Xps.

[Visual Basic]
Overrides Public Property SaveFormat As SaveFormat
[C#]
public override SaveFormat SaveFormat {get; set;}

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


UseBookFoldPrintingSettings Property

Aspose.Words

XpsSaveOptions.UseBookFoldPrintingSettings Property

Gets or sets a boolean value indicating whether the document should be saved using a booklet printing layout, if it is specified via MultiplePages.

[Visual Basic]
Public Property UseBookFoldPrintingSettings As Boolean
[C#]
public bool UseBookFoldPrintingSettings {get; set;}

Remarks

If this option is specified, page range set via PageIndex and PageCount is ignored when saving. This behavior matches MS Word. If book fold printing settings are not specified in page setup, this option will have no effect.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


Aspose.Words.Settings

Aspose.Words

Aspose.Words.Settings Namespace

The Aspose.Words.Settings namespace contains classes and enums that are used when specifying various settings and options stored in a document. These are mail merge, write protection, compatibility and other settings.

Namespace hierarchy

Classes

Class | Description
CompatibilityOptions | Contains compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Microsoft Word).
HyphenationOptions | Allows to configure document hyphenation options.
MailMergeSettings | Specifies all of the mail merge information for a document.
Odso | Specifies the Office Data Source Object (ODSO) settings for a mail merge data source.
OdsoFieldMapData | Specifies how a column in the external data source shall be mapped to the predefined merge fields within the document.
OdsoFieldMapDataCollection | A typed collection of the OdsoFieldMapData objects.
OdsoRecipientData | Represents information about a single record within an external data source that is to be excluded from the mail merge.
OdsoRecipientDataCollection | A typed collection of OdsoRecipientData
ViewOptions | Provides various options that control how a document is shown in Microsoft Word.
WriteProtection | Specifies write protection settings for a document.

Enumerations

Enumeration | Description
Compatibility | Specifies names of compatibility options.
MailMergeCheckErrors | Specifies how Microsoft Word will report errors detected during mail merge.
MailMergeDataType | Specifies the type of an external mail merge data source.
MailMergeDestination | Specifies the possible results which may be generated when a mail merge is carried out on a document.
MailMergeMainDocumentType | Specifies the possible types for a mail merge source document.
MsWordVersion | Allows Aspose.Wods to mimic MS Word version-specific application behavior.
MultiplePagesType | Specifies how document is printed out.
OdsoDataSourceType | Specifies the type of the external data source to be connected to as part of the ODSO connection information.
OdsoFieldMappingType | Specifies the possible types used to indicate if a given mail merge field has been mapped to a column in the given external data source.
ViewType | Possible values for the view mode in Microsoft Word.
ZoomType | Possible values for how large or small the document appears on the screen in Microsoft Word.


Compatibility Enumeration

Specifies names of compatibility options.

[Visual Basic]
Public Enum Compatibility
[C#]
public enum Compatibility

Members

Member Name | Description | Value
NoTabHangInd |  | 0
NoSpaceRaiseLower |  | 1
SuppressSpBfAfterPgBrk |  | 2
WrapTrailSpaces |  | 3
PrintColBlack |  | 4
NoColumnBalance |  | 5
ConvMailMergeEsc |  | 6
SuppressTopSpacing |  | 7
UseSingleBorderforContiguousCells |  | 8
TransparentMetafiles |  | 9
ShowBreaksInFrames |  | 10
SwapBordersOddFacingPgs |  | 11
DoNotLeaveBackslashAlone |  | 12
DoNotExpandOnShiftReturn |  | 13
UlTrailSpace |  | 14
BalanceSingleByteDoubleByteWidth |  | 15
SuppressTopSpacingAtTopOfPage |  | 16
SpacingInWholePoints |  | 17
PrintBodyTextBeforeHeader |  | 18
NoLeading |  | 19
SpaceForUL |  | 20
MWSmallCaps |  | 21
SuppressTopLineSpacingWP |  | 22
TruncateFontHeightLikeWP6 |  | 23
SubFontBySize |  | 24
LineWrapLikeWord6 |  | 25
DoNotSuppressParagraphBorder |  | 26
NoExtraLineSpacing |  | 27
SuppressBottomSpacing |  | 28
WPSpaceWidth |  | 29
WPJustification |  | 30
UsePrinterMetrics |  | 31
ShapeLayoutLikeWW8 |  | 32
FootnoteLayoutLikeWW8 |  | 33
DoNotUseHtmlParagraphAutoSpacing |  | 34
AdjustLineHeightInTable |  | 35
ForgetLastTabAlignment |  | 36
AutoSpaceLikeWord95 |  | 37
AlignTableRowByRow |  | 38
LayoutRawTableWidth |  | 39
LayoutTableRowsApart |  | 40
UseWord97LineBreakRules |  | 41
DoNotBreakWrappedTables |  | 42
doNotSnapToGridInCell |  | 43
SelectFldWithFirstOrLastChar |  | 44
ApplyBreakingRules |  | 45
DoNotWrapTextWithPunct |  | 46
DoNotUseEastAsianBreakRules |  | 47
UseWord2002TableStyleRules |  | 48
GrowAutofit |  | 49
UseNormalStyleForList |  | 50
DoNotUseIndentAsNumberingTabStop |  | 51
UseAltKinsokuLineBreakRules |  | 52
AllowSpaceOfSameStyleInTable |  | 53
DoNotSuppressIndentation |  | 54
DoNotAutofitConstrainedTables |  | 55
AutofitToFirstFixedWidthCell |  | 56
UnderlineTabInNumList |  | 57
DisplayHangulFixedWidth |  | 58
SplitPgBreakAndParaMark |  | 59
DoNotVertAlignCellWithSp |  | 60
DoNotBreakConstrainedForcedTable |  | 61
DoNotVertAlignInTxbx |  | 62
UseAnsiKerningPairs |  | 63
CachedColBalance |  | 64
UseFELayout |  | 65
UICompat97To2003 |  | 66
OverrideTableStyleFontSizeAndJustification |  | 67
DisableOpenTypeFontFormattingFeatures |  | 68
SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning |  | 69
UseWord2010TableStyleRules |  | 70

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace


CompatibilityOptions Class

Contains compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Microsoft Word).

For a list of all members of this type, see CompatibilityOptions Members.

System.Object
Aspose.Words.Settings.CompatibilityOptions

[Visual Basic]
Public Class CompatibilityOptions
[C#]
public class CompatibilityOptions

Remarks

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CompatibilityOptions Members | Aspose.Words.Settings Namespace | Document | CompatibilityOptions


CompatibilityOptions Members

CompatibilityOptions overview

Public Instance Properties

AdjustLineHeightInTable | Add Document Grid Line Pitch To Lines in Table Cells.
AlignTablesRowByRow | Align Table Rows Independently.
AllowSpaceOfSameStyleInTable | Allow Contextual Spacing of Paragraphs in Tables.
ApplyBreakingRules | Use Legacy Ethiopic and Amharic Line Breaking Rules.
AutofitToFirstFixedWidthCell | Allow Table Columns To Exceed Preferred Widths of Constituent Cells.
AutoSpaceLikeWord95 | Emulate Word 95 Full-Width Character Spacing.
BalanceSingleByteDoubleByteWidth | Balance Single Byte and Double Byte Characters.
CachedColBalance | Use Cached Paragraph Information for Column Balancing.
ConvMailMergeEsc | Treat Backslash Quotation Delimiter as Two Quotation Marks.
DisableOpenTypeFontFormattingFeatures |
DisplayHangulFixedWidth | Always Use Fixed Width for Hangul Characters.
DoNotAutofitConstrainedTables | Do Not AutoFit Tables To Fit Next To Wrapped Objects.
DoNotBreakConstrainedForcedTable | Don't Break Table Rows Around Floating Tables.
DoNotBreakWrappedTables | Do Not Allow Floating Tables To Break Across Pages.
DoNotExpandShiftReturn | Don't Justify Lines Ending in Soft Line Break.
DoNotLeaveBackslashAlone | Convert Backslash To Yen Sign When Entered.
DoNotSnapToGridInCell | Do Not Snap to Document Grid in Table Cells with Objects.
DoNotSuppressIndentation | Do Not Ignore Floating Objects When Calculating Paragraph Indentation.
DoNotSuppressParagraphBorders | Do Not Suppress Paragraph Borders Next To Frames.
DoNotUseEastAsianBreakRules | Do Not Compress Compressible Characters When Using Document Grid.
DoNotUseHTMLParagraphAutoSpacing | Use Fixed Paragraph Spacing for HTML Auto Setting.
DoNotUseIndentAsNumberingTabStop | Ignore Hanging Indent When Creating Tab Stop After Numbering.
DoNotVertAlignCellWithSp | Don't Vertically Align Cells Containing Floating Objects.
DoNotVertAlignInTxbx | Ignore Vertical Alignment in Textboxes.
DoNotWrapTextWithPunct | Do Not Allow Hanging Punctuation With Character Grid.
FootnoteLayoutLikeWW8 | Emulate Word 6.x/95/97 Footnote Placement.
ForgetLastTabAlignment | Ignore Width of Last Tab Stop When Aligning Paragraph If It Is Not Left Aligned.
GrowAutofit | Allow Tables to AutoFit Into Page Margins.
LayoutRawTableWidth | Ignore Space Before Table When Deciding If Table Should Wrap Floating Object.
LayoutTableRowsApart | Allow Table Rows to Wrap Inline Objects Independently.
LineWrapLikeWord6 | Emulate Word 6.0 Line Wrapping for East Asian Text.
MWSmallCaps | Emulate Word 5.x for the Macintosh Small Caps Formatting.
NoColumnBalance | Do Not Balance Text Columns within a Section.
NoExtraLineSpacing | Do Not Center Content on Lines With Exact Line Height.
NoLeading | Do Not Add Leading Between Lines of Text.
NoSpaceRaiseLower | Do Not Increase Line Height for Raised/Lowered Text.
NoTabHangInd | Do Not Create Custom Tab Stop for Hanging Indent.
OverrideTableStyleFontSizeAndJustification | Specifies how the style hierarchy of the document is evaluated.
PrintBodyTextBeforeHeader | Print Body Text before Header/Footer Contents.
PrintColBlack | Print Colors as Black And White without Dithering.
SelectFldWithFirstOrLastChar | Select Field When First or Last Character Is Selected.
ShapeLayoutLikeWW8 | Emulate Word 97 Text Wrapping Around Floating Objects.
ShowBreaksInFrames | Display Page/Column Breaks Present in Frames.
SpaceForUL | Add Additional Space Below Baseline For Underlined East Asian Text.
SpacingInWholePoints | Only Expand/Condense Text By Whole Points.
SplitPgBreakAndParaMark | Always Move Paragraph Mark to Page after a Page Break.
SubFontBySize | Increase Priority Of Font Size During Font Substitution.
SuppressBottomSpacing | Ignore Exact Line Height for Last Line on Page.
SuppressSpacingAtTopOfPage | Ignore Minimum Line Height for First Line on Page.
SuppressSpBfAfterPgBrk | Do Not Use Space Before On First Line After a Page Break.
SuppressTopSpacing | Ignore Minimum and Exact Line Height for First Line on Page.
SuppressTopSpacingWP | Emulate WordPerfect 5.x Line Spacing.
SwapBordersFacingPgs | Swap Paragraph Borders on Odd Numbered Pages.
SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning |
TransparentMetafiles | Specifies not to blank the area behind metafile pictures.
TruncateFontHeightsLikeWP6 | Emulate WordPerfect 6.x Font Height Calculation.
UICompat97To2003 | True to disable UI functionality which is not compatible with Word97-2003. Default value is false.
UlTrailSpace | Underline All Trailing Spaces.
UnderlineTabInNumList | Underline Following Character Following Numbering.
UseAltKinsokuLineBreakRules | Use Alternate Set of East Asian Line Breaking Rules.
UseAnsiKerningPairs | Use ANSI Kerning Pairs from Fonts.
UseFELayout | Do Not Bypass East Asian/Complex Script Layout Code.
UseNormalStyleForList | Do Not Automatically Apply List Paragraph Style To Bulleted/Numbered Text.
UsePrinterMetrics | Use Printer Metrics To Display Documents.
UseSingleBorderforContiguousCells | Use Simplified Rules For Table Border Conflicts.
UseWord2002TableStyleRules | Emulate Word 2002 Table Style Rules.
UseWord2010TableStyleRules |
UseWord97LineBreakRules | Emulate Word 97 East Asian Line Breaking.
WPJustification | Emulate WordPerfect 6.x Paragraph Justification.
WPSpaceWidth | Specifies whether to set the width of a space as is done in WordPerfect 5.x.
WrapTrailSpaces | Line Wrap Trailing Spaces.

Public Instance Methods

OptimizeFor Allows to optimize the document contents as well as default Aspose.Words behavior to a particular versions of MS Word. Use this method to prevent MS Word from displaying "Compatibility mode" ribbon upon document loading. (Note that you may also need to set the Compliance property to Iso29500_2008_Transitional or higher.)

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace | Document | CompatibilityOptions


CompatibilityOptions Properties

The properties of the CompatibilityOptions class are listed below. For a complete list of CompatibilityOptions class members, see the CompatibilityOptions Members topic.

Public Instance Properties

AdjustLineHeightInTable | Add Document Grid Line Pitch To Lines in Table Cells.
AlignTablesRowByRow | Align Table Rows Independently.
AllowSpaceOfSameStyleInTable | Allow Contextual Spacing of Paragraphs in Tables.
ApplyBreakingRules | Use Legacy Ethiopic and Amharic Line Breaking Rules.
AutofitToFirstFixedWidthCell | Allow Table Columns To Exceed Preferred Widths of Constituent Cells.
AutoSpaceLikeWord95 | Emulate Word 95 Full-Width Character Spacing.
BalanceSingleByteDoubleByteWidth | Balance Single Byte and Double Byte Characters.
CachedColBalance | Use Cached Paragraph Information for Column Balancing.
ConvMailMergeEsc | Treat Backslash Quotation Delimiter as Two Quotation Marks.
DisableOpenTypeFontFormattingFeatures |
DisplayHangulFixedWidth | Always Use Fixed Width for Hangul Characters.
DoNotAutofitConstrainedTables | Do Not AutoFit Tables To Fit Next To Wrapped Objects.
DoNotBreakConstrainedForcedTable | Don't Break Table Rows Around Floating Tables.
DoNotBreakWrappedTables | Do Not Allow Floating Tables To Break Across Pages.
DoNotExpandShiftReturn | Don't Justify Lines Ending in Soft Line Break.
DoNotLeaveBackslashAlone | Convert Backslash To Yen Sign When Entered.
DoNotSnapToGridInCell | Do Not Snap to Document Grid in Table Cells with Objects.
DoNotSuppressIndentation | Do Not Ignore Floating Objects When Calculating Paragraph Indentation.
DoNotSuppressParagraphBorders | Do Not Suppress Paragraph Borders Next To Frames.
DoNotUseEastAsianBreakRules | Do Not Compress Compressible Characters When Using Document Grid.
DoNotUseHTMLParagraphAutoSpacing | Use Fixed Paragraph Spacing for HTML Auto Setting.
DoNotUseIndentAsNumberingTabStop | Ignore Hanging Indent When Creating Tab Stop After Numbering.
DoNotVertAlignCellWithSp | Don't Vertically Align Cells Containing Floating Objects.
DoNotVertAlignInTxbx | Ignore Vertical Alignment in Textboxes.
DoNotWrapTextWithPunct | Do Not Allow Hanging Punctuation With Character Grid.
FootnoteLayoutLikeWW8 | Emulate Word 6.x/95/97 Footnote Placement.
ForgetLastTabAlignment | Ignore Width of Last Tab Stop When Aligning Paragraph If It Is Not Left Aligned.
GrowAutofit | Allow Tables to AutoFit Into Page Margins.
LayoutRawTableWidth | Ignore Space Before Table When Deciding If Table Should Wrap Floating Object.
LayoutTableRowsApart | Allow Table Rows to Wrap Inline Objects Independently.
LineWrapLikeWord6 | Emulate Word 6.0 Line Wrapping for East Asian Text.
MWSmallCaps | Emulate Word 5.x for the Macintosh Small Caps Formatting.
NoColumnBalance | Do Not Balance Text Columns within a Section.
NoExtraLineSpacing | Do Not Center Content on Lines With Exact Line Height.
NoLeading | Do Not Add Leading Between Lines of Text.
NoSpaceRaiseLower | Do Not Increase Line Height for Raised/Lowered Text.
NoTabHangInd | Do Not Create Custom Tab Stop for Hanging Indent.
OverrideTableStyleFontSizeAndJustification | Specifies how the style hierarchy of the document is evaluated.
PrintBodyTextBeforeHeader | Print Body Text before Header/Footer Contents.
PrintColBlack | Print Colors as Black And White without Dithering.
SelectFldWithFirstOrLastChar | Select Field When First or Last Character Is Selected.
ShapeLayoutLikeWW8 | Emulate Word 97 Text Wrapping Around Floating Objects.
ShowBreaksInFrames | Display Page/Column Breaks Present in Frames.
SpaceForUL | Add Additional Space Below Baseline For Underlined East Asian Text.
SpacingInWholePoints | Only Expand/Condense Text By Whole Points.
SplitPgBreakAndParaMark | Always Move Paragraph Mark to Page after a Page Break.
SubFontBySize | Increase Priority Of Font Size During Font Substitution.
SuppressBottomSpacing | Ignore Exact Line Height for Last Line on Page.
SuppressSpacingAtTopOfPage | Ignore Minimum Line Height for First Line on Page.
SuppressSpBfAfterPgBrk | Do Not Use Space Before On First Line After a Page Break.
SuppressTopSpacing | Ignore Minimum and Exact Line Height for First Line on Page.
SuppressTopSpacingWP | Emulate WordPerfect 5.x Line Spacing.
SwapBordersFacingPgs | Swap Paragraph Borders on Odd Numbered Pages.
SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning |
TransparentMetafiles | Specifies not to blank the area behind metafile pictures.
TruncateFontHeightsLikeWP6 | Emulate WordPerfect 6.x Font Height Calculation.
UICompat97To2003 | True to disable UI functionality which is not compatible with Word97-2003. Default value is false.
UlTrailSpace | Underline All Trailing Spaces.
UnderlineTabInNumList | Underline Following Character Following Numbering.
UseAltKinsokuLineBreakRules | Use Alternate Set of East Asian Line Breaking Rules.
UseAnsiKerningPairs | Use ANSI Kerning Pairs from Fonts.
UseFELayout | Do Not Bypass East Asian/Complex Script Layout Code.
UseNormalStyleForList | Do Not Automatically Apply List Paragraph Style To Bulleted/Numbered Text.
UsePrinterMetrics | Use Printer Metrics To Display Documents.
UseSingleBorderforContiguousCells | Use Simplified Rules For Table Border Conflicts.
UseWord2002TableStyleRules | Emulate Word 2002 Table Style Rules.
UseWord2010TableStyleRules |
UseWord97LineBreakRules | Emulate Word 97 East Asian Line Breaking.
WPJustification | Emulate WordPerfect 6.x Paragraph Justification.
WPSpaceWidth | Specifies whether to set the width of a space as is done in WordPerfect 5.x.
WrapTrailSpaces | Line Wrap Trailing Spaces.

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace | Document | CompatibilityOptions


AdjustLineHeightInTable Property

Aspose.Words

CompatibilityOptions.AdjustLineHeightInTable Property

Add Document Grid Line Pitch To Lines in Table Cells.

[Visual Basic]
Public Property AdjustLineHeightInTable As Boolean
[C#]
public bool AdjustLineHeightInTable {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


AlignTablesRowByRow Property

Aspose.Words

CompatibilityOptions.AlignTablesRowByRow Property

Align Table Rows Independently.

[Visual Basic]
Public Property AlignTablesRowByRow As Boolean
[C#]
public bool AlignTablesRowByRow {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


AllowSpaceOfSameStyleInTable Property

Aspose.Words

CompatibilityOptions.AllowSpaceOfSameStyleInTable Property

Allow Contextual Spacing of Paragraphs in Tables.

[Visual Basic]
Public Property AllowSpaceOfSameStyleInTable As Boolean
[C#]
public bool AllowSpaceOfSameStyleInTable {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


ApplyBreakingRules Property

Aspose.Words

CompatibilityOptions.ApplyBreakingRules Property

Use Legacy Ethiopic and Amharic Line Breaking Rules.

[Visual Basic]
Public Property ApplyBreakingRules As Boolean
[C#]
public bool ApplyBreakingRules {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


AutofitToFirstFixedWidthCell Property

Aspose.Words

CompatibilityOptions.AutofitToFirstFixedWidthCell Property

Allow Table Columns To Exceed Preferred Widths of Constituent Cells.

[Visual Basic]
Public Property AutofitToFirstFixedWidthCell As Boolean
[C#]
public bool AutofitToFirstFixedWidthCell {get; set;}

Remarks

The option is called "Use Word 2003 table autofit rules" in MS Word 2013 user interface. It actually affects how the grid is calculated for fixed layout tables, too (for some cases).

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


AutoSpaceLikeWord95 Property

Aspose.Words

CompatibilityOptions.AutoSpaceLikeWord95 Property

Emulate Word 95 Full-Width Character Spacing.

[Visual Basic]
Public Property AutoSpaceLikeWord95 As Boolean
[C#]
public bool AutoSpaceLikeWord95 {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


BalanceSingleByteDoubleByteWidth Property

Aspose.Words

CompatibilityOptions.BalanceSingleByteDoubleByteWidth Property

Balance Single Byte and Double Byte Characters.

[Visual Basic]
Public Property BalanceSingleByteDoubleByteWidth As Boolean
[C#]
public bool BalanceSingleByteDoubleByteWidth {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


CachedColBalance Property

Aspose.Words

CompatibilityOptions.CachedColBalance Property

Use Cached Paragraph Information for Column Balancing.

[Visual Basic]
Public Property CachedColBalance As Boolean
[C#]
public bool CachedColBalance {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


ConvMailMergeEsc Property

Aspose.Words

CompatibilityOptions.ConvMailMergeEsc Property

Treat Backslash Quotation Delimiter as Two Quotation Marks.

[Visual Basic]
Public Property ConvMailMergeEsc As Boolean
[C#]
public bool ConvMailMergeEsc {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DisableOpenTypeFontFormattingFeatures Property

Aspose.Words

CompatibilityOptions.DisableOpenTypeFontFormattingFeatures Property

[Visual Basic]
Public Property DisableOpenTypeFontFormattingFeatures As Boolean
[C#]
public bool DisableOpenTypeFontFormattingFeatures {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DisplayHangulFixedWidth Property

Aspose.Words

CompatibilityOptions.DisplayHangulFixedWidth Property

Always Use Fixed Width for Hangul Characters.

[Visual Basic]
Public Property DisplayHangulFixedWidth As Boolean
[C#]
public bool DisplayHangulFixedWidth {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotAutofitConstrainedTables Property

Aspose.Words

CompatibilityOptions.DoNotAutofitConstrainedTables Property

Do Not AutoFit Tables To Fit Next To Wrapped Objects.

[Visual Basic]
Public Property DoNotAutofitConstrainedTables As Boolean
[C#]
public bool DoNotAutofitConstrainedTables {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotBreakConstrainedForcedTable Property

Aspose.Words

CompatibilityOptions.DoNotBreakConstrainedForcedTable Property

Don't Break Table Rows Around Floating Tables.

[Visual Basic]
Public Property DoNotBreakConstrainedForcedTable As Boolean
[C#]
public bool DoNotBreakConstrainedForcedTable {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotBreakWrappedTables Property

Aspose.Words

CompatibilityOptions.DoNotBreakWrappedTables Property

Do Not Allow Floating Tables To Break Across Pages.

[Visual Basic]
Public Property DoNotBreakWrappedTables As Boolean
[C#]
public bool DoNotBreakWrappedTables {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotExpandShiftReturn Property

Aspose.Words

CompatibilityOptions.DoNotExpandShiftReturn Property

Don't Justify Lines Ending in Soft Line Break.

[Visual Basic]
Public Property DoNotExpandShiftReturn As Boolean
[C#]
public bool DoNotExpandShiftReturn {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotLeaveBackslashAlone Property

Aspose.Words

CompatibilityOptions.DoNotLeaveBackslashAlone Property

Convert Backslash To Yen Sign When Entered.

[Visual Basic]
Public Property DoNotLeaveBackslashAlone As Boolean
[C#]
public bool DoNotLeaveBackslashAlone {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotSnapToGridInCell Property

Aspose.Words

CompatibilityOptions.DoNotSnapToGridInCell Property

Do Not Snap to Document Grid in Table Cells with Objects.

[Visual Basic]
Public Property DoNotSnapToGridInCell As Boolean
[C#]
public bool DoNotSnapToGridInCell {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotSuppressIndentation Property

Aspose.Words

CompatibilityOptions.DoNotSuppressIndentation Property

Do Not Ignore Floating Objects When Calculating Paragraph Indentation.

[Visual Basic]
Public Property DoNotSuppressIndentation As Boolean
[C#]
public bool DoNotSuppressIndentation {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotSuppressParagraphBorders Property

Aspose.Words

CompatibilityOptions.DoNotSuppressParagraphBorders Property

Do Not Suppress Paragraph Borders Next To Frames.

[Visual Basic]
Public Property DoNotSuppressParagraphBorders As Boolean
[C#]
public bool DoNotSuppressParagraphBorders {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotUseEastAsianBreakRules Property

Aspose.Words

CompatibilityOptions.DoNotUseEastAsianBreakRules Property

Do Not Compress Compressible Characters When Using Document Grid.

[Visual Basic]
Public Property DoNotUseEastAsianBreakRules As Boolean
[C#]
public bool DoNotUseEastAsianBreakRules {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotUseHTMLParagraphAutoSpacing Property

Aspose.Words

CompatibilityOptions.DoNotUseHTMLParagraphAutoSpacing Property

Use Fixed Paragraph Spacing for HTML Auto Setting.

[Visual Basic]
Public Property DoNotUseHTMLParagraphAutoSpacing As Boolean
[C#]
public bool DoNotUseHTMLParagraphAutoSpacing {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotUseIndentAsNumberingTabStop Property

Aspose.Words

CompatibilityOptions.DoNotUseIndentAsNumberingTabStop Property

Ignore Hanging Indent When Creating Tab Stop After Numbering.

[Visual Basic]
Public Property DoNotUseIndentAsNumberingTabStop As Boolean
[C#]
public bool DoNotUseIndentAsNumberingTabStop {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotVertAlignCellWithSp Property

Aspose.Words

CompatibilityOptions.DoNotVertAlignCellWithSp Property

Don't Vertically Align Cells Containing Floating Objects.

[Visual Basic]
Public Property DoNotVertAlignCellWithSp As Boolean
[C#]
public bool DoNotVertAlignCellWithSp {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotVertAlignInTxbx Property

Aspose.Words

CompatibilityOptions.DoNotVertAlignInTxbx Property

Ignore Vertical Alignment in Textboxes.

[Visual Basic]
Public Property DoNotVertAlignInTxbx As Boolean
[C#]
public bool DoNotVertAlignInTxbx {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


DoNotWrapTextWithPunct Property

Aspose.Words

CompatibilityOptions.DoNotWrapTextWithPunct Property

Do Not Allow Hanging Punctuation With Character Grid.

[Visual Basic]
Public Property DoNotWrapTextWithPunct As Boolean
[C#]
public bool DoNotWrapTextWithPunct {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


FootnoteLayoutLikeWW8 Property

Aspose.Words

CompatibilityOptions.FootnoteLayoutLikeWW8 Property

Emulate Word 6.x/95/97 Footnote Placement.

[Visual Basic]
Public Property FootnoteLayoutLikeWW8 As Boolean
[C#]
public bool FootnoteLayoutLikeWW8 {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


ForgetLastTabAlignment Property

Aspose.Words

CompatibilityOptions.ForgetLastTabAlignment Property

Ignore Width of Last Tab Stop When Aligning Paragraph If It Is Not Left Aligned.

[Visual Basic]
Public Property ForgetLastTabAlignment As Boolean
[C#]
public bool ForgetLastTabAlignment {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


GrowAutofit Property

Aspose.Words

CompatibilityOptions.GrowAutofit Property

Allow Tables to AutoFit Into Page Margins.

[Visual Basic]
Public Property GrowAutofit As Boolean
[C#]
public bool GrowAutofit {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


LayoutRawTableWidth Property

Aspose.Words

CompatibilityOptions.LayoutRawTableWidth Property

Ignore Space Before Table When Deciding If Table Should Wrap Floating Object.

[Visual Basic]
Public Property LayoutRawTableWidth As Boolean
[C#]
public bool LayoutRawTableWidth {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


LayoutTableRowsApart Property

Aspose.Words

CompatibilityOptions.LayoutTableRowsApart Property

Allow Table Rows to Wrap Inline Objects Independently.

[Visual Basic]
Public Property LayoutTableRowsApart As Boolean
[C#]
public bool LayoutTableRowsApart {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


LineWrapLikeWord6 Property

Aspose.Words

CompatibilityOptions.LineWrapLikeWord6 Property

Emulate Word 6.0 Line Wrapping for East Asian Text.

[Visual Basic]
Public Property LineWrapLikeWord6 As Boolean
[C#]
public bool LineWrapLikeWord6 {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


MWSmallCaps Property

Aspose.Words

CompatibilityOptions.MWSmallCaps Property

Emulate Word 5.x for the Macintosh Small Caps Formatting.

[Visual Basic]
Public Property MWSmallCaps As Boolean
[C#]
public bool MWSmallCaps {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


NoColumnBalance Property

Aspose.Words

CompatibilityOptions.NoColumnBalance Property

Do Not Balance Text Columns within a Section.

[Visual Basic]
Public Property NoColumnBalance As Boolean
[C#]
public bool NoColumnBalance {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


NoExtraLineSpacing Property

Aspose.Words

CompatibilityOptions.NoExtraLineSpacing Property

Do Not Center Content on Lines With Exact Line Height.

[Visual Basic]
Public Property NoExtraLineSpacing As Boolean
[C#]
public bool NoExtraLineSpacing {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


NoLeading Property

Aspose.Words

CompatibilityOptions.NoLeading Property

Do Not Add Leading Between Lines of Text.

[Visual Basic]
Public Property NoLeading As Boolean
[C#]
public bool NoLeading {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


NoSpaceRaiseLower Property

Aspose.Words

CompatibilityOptions.NoSpaceRaiseLower Property

Do Not Increase Line Height for Raised/Lowered Text.

[Visual Basic]
Public Property NoSpaceRaiseLower As Boolean
[C#]
public bool NoSpaceRaiseLower {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


NoTabHangInd Property

Aspose.Words

CompatibilityOptions.NoTabHangInd Property

Do Not Create Custom Tab Stop for Hanging Indent.

[Visual Basic]
Public Property NoTabHangInd As Boolean
[C#]
public bool NoTabHangInd {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


OverrideTableStyleFontSizeAndJustification Property

Aspose.Words

CompatibilityOptions.OverrideTableStyleFontSizeAndJustification Property

Specifies how the style hierarchy of the document is evaluated.

[Visual Basic]
Public Property OverrideTableStyleFontSizeAndJustification As Boolean
[C#]
public bool OverrideTableStyleFontSizeAndJustification {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


PrintBodyTextBeforeHeader Property

Aspose.Words

CompatibilityOptions.PrintBodyTextBeforeHeader Property

Print Body Text before Header/Footer Contents.

[Visual Basic]
Public Property PrintBodyTextBeforeHeader As Boolean
[C#]
public bool PrintBodyTextBeforeHeader {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


PrintColBlack Property

Aspose.Words

CompatibilityOptions.PrintColBlack Property

Print Colors as Black And White without Dithering.

[Visual Basic]
Public Property PrintColBlack As Boolean
[C#]
public bool PrintColBlack {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SelectFldWithFirstOrLastChar Property

Aspose.Words

CompatibilityOptions.SelectFldWithFirstOrLastChar Property

Select Field When First or Last Character Is Selected.

[Visual Basic]
Public Property SelectFldWithFirstOrLastChar As Boolean
[C#]
public bool SelectFldWithFirstOrLastChar {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


ShapeLayoutLikeWW8 Property

Aspose.Words

CompatibilityOptions.ShapeLayoutLikeWW8 Property

Emulate Word 97 Text Wrapping Around Floating Objects.

[Visual Basic]
Public Property ShapeLayoutLikeWW8 As Boolean
[C#]
public bool ShapeLayoutLikeWW8 {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


ShowBreaksInFrames Property

Aspose.Words

CompatibilityOptions.ShowBreaksInFrames Property

Display Page/Column Breaks Present in Frames.

[Visual Basic]
Public Property ShowBreaksInFrames As Boolean
[C#]
public bool ShowBreaksInFrames {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SpaceForUL Property

Aspose.Words

CompatibilityOptions.SpaceForUL Property

Add Additional Space Below Baseline For Underlined East Asian Text.

[Visual Basic]
Public Property SpaceForUL As Boolean
[C#]
public bool SpaceForUL {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SpacingInWholePoints Property

Aspose.Words

CompatibilityOptions.SpacingInWholePoints Property

Only Expand/Condense Text By Whole Points.

[Visual Basic]
Public Property SpacingInWholePoints As Boolean
[C#]
public bool SpacingInWholePoints {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SplitPgBreakAndParaMark Property

Aspose.Words

CompatibilityOptions.SplitPgBreakAndParaMark Property

Always Move Paragraph Mark to Page after a Page Break.

[Visual Basic]
Public Property SplitPgBreakAndParaMark As Boolean
[C#]
public bool SplitPgBreakAndParaMark {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SubFontBySize Property

Aspose.Words

CompatibilityOptions.SubFontBySize Property

Increase Priority Of Font Size During Font Substitution.

[Visual Basic]
Public Property SubFontBySize As Boolean
[C#]
public bool SubFontBySize {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SuppressBottomSpacing Property

Aspose.Words

CompatibilityOptions.SuppressBottomSpacing Property

Ignore Exact Line Height for Last Line on Page.

[Visual Basic]
Public Property SuppressBottomSpacing As Boolean
[C#]
public bool SuppressBottomSpacing {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SuppressSpacingAtTopOfPage Property

Aspose.Words

CompatibilityOptions.SuppressSpacingAtTopOfPage Property

Ignore Minimum Line Height for First Line on Page.

[Visual Basic]
Public Property SuppressSpacingAtTopOfPage As Boolean
[C#]
public bool SuppressSpacingAtTopOfPage {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SuppressSpBfAfterPgBrk Property

Aspose.Words

CompatibilityOptions.SuppressSpBfAfterPgBrk Property

Do Not Use Space Before On First Line After a Page Break.

[Visual Basic]
Public Property SuppressSpBfAfterPgBrk As Boolean
[C#]
public bool SuppressSpBfAfterPgBrk {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SuppressTopSpacing Property

Aspose.Words

CompatibilityOptions.SuppressTopSpacing Property

Ignore Minimum and Exact Line Height for First Line on Page.

[Visual Basic]
Public Property SuppressTopSpacing As Boolean
[C#]
public bool SuppressTopSpacing {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SuppressTopSpacingWP Property

Aspose.Words

CompatibilityOptions.SuppressTopSpacingWP Property

Emulate WordPerfect 5.x Line Spacing.

[Visual Basic]
Public Property SuppressTopSpacingWP As Boolean
[C#]
public bool SuppressTopSpacingWP {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SwapBordersFacingPgs Property

Aspose.Words

CompatibilityOptions.SwapBordersFacingPgs Property

Swap Paragraph Borders on Odd Numbered Pages.

[Visual Basic]
Public Property SwapBordersFacingPgs As Boolean
[C#]
public bool SwapBordersFacingPgs {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning Property

Aspose.Words

CompatibilityOptions.SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning Property

[Visual Basic]
Public Property SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning As Boolean
[C#]
public bool SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


TransparentMetafiles Property

Aspose.Words

CompatibilityOptions.TransparentMetafiles Property

Specifies not to blank the area behind metafile pictures.

[Visual Basic]
Public Property TransparentMetafiles As Boolean
[C#]
public bool TransparentMetafiles {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


TruncateFontHeightsLikeWP6 Property

Aspose.Words

CompatibilityOptions.TruncateFontHeightsLikeWP6 Property

Emulate WordPerfect 6.x Font Height Calculation.

[Visual Basic]
Public Property TruncateFontHeightsLikeWP6 As Boolean
[C#]
public bool TruncateFontHeightsLikeWP6 {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UICompat97To2003 Property

Aspose.Words

CompatibilityOptions.UICompat97To2003 Property

True to disable UI functionality which is not compatible with Word97-2003. Default value is false.

[Visual Basic]
Public Property UICompat97To2003 As Boolean
[C#]
public bool UICompat97To2003 {get; set;}

Remarks

Controls the Word97-2003 compatibility setting that disables UI functionality which is not compatible with Word97-2003. When true, 'w:uiCompat97To2003' XML element is written to '\word\settings.xml' document package part. Default value is false. When set to false, this element is not written. Technically this property is not part of compatibility options, but we have put it here for API convenience.

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UlTrailSpace Property

Aspose.Words

CompatibilityOptions.UlTrailSpace Property

Underline All Trailing Spaces.

[Visual Basic]
Public Property UlTrailSpace As Boolean
[C#]
public bool UlTrailSpace {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UnderlineTabInNumList Property

Aspose.Words

CompatibilityOptions.UnderlineTabInNumList Property

Underline Following Character Following Numbering.

[Visual Basic]
Public Property UnderlineTabInNumList As Boolean
[C#]
public bool UnderlineTabInNumList {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseAltKinsokuLineBreakRules Property

Aspose.Words

CompatibilityOptions.UseAltKinsokuLineBreakRules Property

Use Alternate Set of East Asian Line Breaking Rules.

[Visual Basic]
Public Property UseAltKinsokuLineBreakRules As Boolean
[C#]
public bool UseAltKinsokuLineBreakRules {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseAnsiKerningPairs Property

Aspose.Words

CompatibilityOptions.UseAnsiKerningPairs Property

Use ANSI Kerning Pairs from Fonts.

[Visual Basic]
Public Property UseAnsiKerningPairs As Boolean
[C#]
public bool UseAnsiKerningPairs {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseFELayout Property

Aspose.Words

CompatibilityOptions.UseFELayout Property

Do Not Bypass East Asian/Complex Script Layout Code.

[Visual Basic]
Public Property UseFELayout As Boolean
[C#]
public bool UseFELayout {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseNormalStyleForList Property

Aspose.Words

CompatibilityOptions.UseNormalStyleForList Property

Do Not Automatically Apply List Paragraph Style To Bulleted/Numbered Text.

[Visual Basic]
Public Property UseNormalStyleForList As Boolean
[C#]
public bool UseNormalStyleForList {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UsePrinterMetrics Property

Aspose.Words

CompatibilityOptions.UsePrinterMetrics Property

Use Printer Metrics To Display Documents.

[Visual Basic]
Public Property UsePrinterMetrics As Boolean
[C#]
public bool UsePrinterMetrics {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseSingleBorderforContiguousCells Property

Aspose.Words

CompatibilityOptions.UseSingleBorderforContiguousCells Property

Use Simplified Rules For Table Border Conflicts.

[Visual Basic]
Public Property UseSingleBorderforContiguousCells As Boolean
[C#]
public bool UseSingleBorderforContiguousCells {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseWord2002TableStyleRules Property

Aspose.Words

CompatibilityOptions.UseWord2002TableStyleRules Property

Emulate Word 2002 Table Style Rules.

[Visual Basic]
Public Property UseWord2002TableStyleRules As Boolean
[C#]
public bool UseWord2002TableStyleRules {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseWord2010TableStyleRules Property

Aspose.Words

CompatibilityOptions.UseWord2010TableStyleRules Property

[Visual Basic]
Public Property UseWord2010TableStyleRules As Boolean
[C#]
public bool UseWord2010TableStyleRules {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


UseWord97LineBreakRules Property

Aspose.Words

CompatibilityOptions.UseWord97LineBreakRules Property

Emulate Word 97 East Asian Line Breaking.

[Visual Basic]
Public Property UseWord97LineBreakRules As Boolean
[C#]
public bool UseWord97LineBreakRules {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


WPJustification Property

Aspose.Words

CompatibilityOptions.WPJustification Property

Emulate WordPerfect 6.x Paragraph Justification.

[Visual Basic]
Public Property WPJustification As Boolean
[C#]
public bool WPJustification {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


WPSpaceWidth Property

Aspose.Words

CompatibilityOptions.WPSpaceWidth Property

Specifies whether to set the width of a space as is done in WordPerfect 5.x.

[Visual Basic]
Public Property WPSpaceWidth As Boolean
[C#]
public bool WPSpaceWidth {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


WrapTrailSpaces Property

Aspose.Words

CompatibilityOptions.WrapTrailSpaces Property

Line Wrap Trailing Spaces.

[Visual Basic]
Public Property WrapTrailSpaces As Boolean
[C#]
public bool WrapTrailSpaces {get; set;}

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


CompatibilityOptions Methods

The methods of the CompatibilityOptions class are listed below. For a complete list of CompatibilityOptions class members, see the CompatibilityOptions Members topic.

Public Instance Methods

OptimizeFor Allows to optimize the document contents as well as default Aspose.Words behavior to a particular versions of MS Word. Use this method to prevent MS Word from displaying "Compatibility mode" ribbon upon document loading. (Note that you may also need to set the Compliance property to Iso29500_2008_Transitional or higher.)

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace | Document | CompatibilityOptions


CompatibilityOptions.OptimizeFor Method

Allows to optimize the document contents as well as default Aspose.Words behavior to a particular versions of MS Word.

Use this method to prevent MS Word from displaying "Compatibility mode" ribbon upon document loading. (Note that you may also need to set the Compliance property to Iso29500_2008_Transitional or higher.)

[Visual Basic]
Public Sub OptimizeFor( _
ByVal version As MsWordVersion _
)
[C#]
public void OptimizeFor(
MsWordVersion version
);

See Also

CompatibilityOptions Class | Aspose.Words.Settings Namespace


HyphenationOptions Class

Allows to configure document hyphenation options.

For a list of all members of this type, see HyphenationOptions Members.

System.Object
Aspose.Words.Settings.HyphenationOptions

[Visual Basic]
Public Class HyphenationOptions
[C#]
public class HyphenationOptions

Example

Shows how to configure document hyphenation options.

[C#]

Document doc = new Document();
// Create new Run with text that we want to move to the next line using the hyphen
Run run = new Run(doc)
{
    Text =
        "poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj"
};

Paragraph para = doc.FirstSection.Body.Paragraphs[0];
para.AppendChild(run);

doc.HyphenationOptions.AutoHyphenation = true;
doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
doc.HyphenationOptions.HyphenationZone = 720; // 0.5 inch
doc.HyphenationOptions.HyphenateCaps = true;

doc.Save(ArtifactsDir + "HyphenationOptions.docx");

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

HyphenationOptions Members | Aspose.Words.Settings Namespace


HyphenationOptions Members

HyphenationOptions overview

Public Instance Constructors

HyphenationOptions Constructor Initializes a new instance of the HyphenationOptions class.

Public Instance Properties

AutoHyphenation | Gets or sets value determining whether automatic hyphenation is turned on for the document. Default value for this property is false.
ConsecutiveHyphenLimit | Gets or sets the maximum number of consecutive lines that can end with hyphens. Default value for this property is 0.
HyphenateCaps | Gets or sets value determining whether words written in all capital letters are hyphenated. Default value for this property is true.
HyphenationZone | Gets or sets the distance in 1/20 of a point from the right margin within which you do not want to hyphenate words. Default value for this property is 360 (0.25 inch).

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


HyphenationOptions Constructor

Initializes a new instance of the HyphenationOptions class.

[Visual Basic]
Public Sub New()
[C#]
public HyphenationOptions();

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


HyphenationOptions Properties

The properties of the HyphenationOptions class are listed below. For a complete list of HyphenationOptions class members, see the HyphenationOptions Members topic.

Public Instance Properties

AutoHyphenation | Gets or sets value determining whether automatic hyphenation is turned on for the document. Default value for this property is false.
ConsecutiveHyphenLimit | Gets or sets the maximum number of consecutive lines that can end with hyphens. Default value for this property is 0.
HyphenateCaps | Gets or sets value determining whether words written in all capital letters are hyphenated. Default value for this property is true.
HyphenationZone | Gets or sets the distance in 1/20 of a point from the right margin within which you do not want to hyphenate words. Default value for this property is 360 (0.25 inch).

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


AutoHyphenation Property

Aspose.Words

HyphenationOptions.AutoHyphenation Property

Gets or sets value determining whether automatic hyphenation is turned on for the document. Default value for this property is false.

[Visual Basic]
Public Property AutoHyphenation As Boolean
[C#]
public bool AutoHyphenation {get; set;}

Example

Shows how to configure document hyphenation options.

[C#]

Document doc = new Document();
// Create new Run with text that we want to move to the next line using the hyphen
Run run = new Run(doc)
{
    Text =
        "poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj"
};

Paragraph para = doc.FirstSection.Body.Paragraphs[0];
para.AppendChild(run);

doc.HyphenationOptions.AutoHyphenation = true;
doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
doc.HyphenationOptions.HyphenationZone = 720; // 0.5 inch
doc.HyphenationOptions.HyphenateCaps = true;

doc.Save(ArtifactsDir + "HyphenationOptions.docx");

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


ConsecutiveHyphenLimit Property

Aspose.Words

HyphenationOptions.ConsecutiveHyphenLimit Property

Gets or sets the maximum number of consecutive lines that can end with hyphens. Default value for this property is 0.

[Visual Basic]
Public Property ConsecutiveHyphenLimit As Integer
[C#]
public int ConsecutiveHyphenLimit {get; set;}

Remarks

If value of this property is set to 0, any number of consecutive lines can end with hyphens.

The property does not have effect when saving to fixed page formats e.g. PDF.

Example

Shows how to configure document hyphenation options.

[C#]

Document doc = new Document();
// Create new Run with text that we want to move to the next line using the hyphen
Run run = new Run(doc)
{
    Text =
        "poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj"
};

Paragraph para = doc.FirstSection.Body.Paragraphs[0];
para.AppendChild(run);

doc.HyphenationOptions.AutoHyphenation = true;
doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
doc.HyphenationOptions.HyphenationZone = 720; // 0.5 inch
doc.HyphenationOptions.HyphenateCaps = true;

doc.Save(ArtifactsDir + "HyphenationOptions.docx");

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


HyphenateCaps Property

Aspose.Words

HyphenationOptions.HyphenateCaps Property

Gets or sets value determining whether words written in all capital letters are hyphenated. Default value for this property is true.

[Visual Basic]
Public Property HyphenateCaps As Boolean
[C#]
public bool HyphenateCaps {get; set;}

Example

Shows how to configure document hyphenation options.

[C#]

Document doc = new Document();
// Create new Run with text that we want to move to the next line using the hyphen
Run run = new Run(doc)
{
    Text =
        "poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj"
};

Paragraph para = doc.FirstSection.Body.Paragraphs[0];
para.AppendChild(run);

doc.HyphenationOptions.AutoHyphenation = true;
doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
doc.HyphenationOptions.HyphenationZone = 720; // 0.5 inch
doc.HyphenationOptions.HyphenateCaps = true;

doc.Save(ArtifactsDir + "HyphenationOptions.docx");

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


HyphenationZone Property

Aspose.Words

HyphenationOptions.HyphenationZone Property

Gets or sets the distance in 1/20 of a point from the right margin within which you do not want to hyphenate words. Default value for this property is 360 (0.25 inch).

[Visual Basic]
Public Property HyphenationZone As Integer
[C#]
public int HyphenationZone {get; set;}

Example

Shows how to configure document hyphenation options.

[C#]

Document doc = new Document();
// Create new Run with text that we want to move to the next line using the hyphen
Run run = new Run(doc)
{
    Text =
        "poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj"
};

Paragraph para = doc.FirstSection.Body.Paragraphs[0];
para.AppendChild(run);

doc.HyphenationOptions.AutoHyphenation = true;
doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
doc.HyphenationOptions.HyphenationZone = 720; // 0.5 inch
doc.HyphenationOptions.HyphenateCaps = true;

doc.Save(ArtifactsDir + "HyphenationOptions.docx");

See Also

HyphenationOptions Class | Aspose.Words.Settings Namespace


MailMergeCheckErrors Enumeration

Specifies how Microsoft Word will report errors detected during mail merge.

[Visual Basic]
Public Enum MailMergeCheckErrors
[C#]
public enum MailMergeCheckErrors

Remarks

Members

Member Name | Description | Value
Simulate | Simulate the merge and report errors in a new document. | 1
PauseOnError | Complete the merge and pause to report errors. | 2
CollectErrors | Complete the merge and report errors in a new document. | 3
Default | Equals to the PauseOnError value. | 2

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | CheckErrors


MailMergeDataType Enumeration

Specifies the type of an external mail merge data source.

[Visual Basic]
Public Enum MailMergeDataType
[C#]
public enum MailMergeDataType

Remarks

Example

Shows how to execute a mail merge with MailMergeSettings.

[C#]

// We'll create a simple document that will act as a destination for mail merge data
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Dear ");
builder.InsertField("MERGEFIELD FirstName", "<FirstName>");
builder.Write(" ");
builder.InsertField("MERGEFIELD LastName", "<LastName>");
builder.Writeln(": ");
builder.InsertField("MERGEFIELD Message", "<Message>");

// Also we'll need a data source, in this case it will be an ASCII text file
// We can use any character we want as a delimiter, in this case we'll choose '|'
// The delimiter character is selected in the ODSO settings of mail merge settings
string[] lines = { "FirstName|LastName|Message",
    "John|Doe|Hello! This message was created with Aspose Words mail merge." };
File.WriteAllLines(ArtifactsDir + "Document.Lines.txt", lines);

// Set the data source, query and other things
MailMergeSettings mailMergeSettings = doc.MailMergeSettings;
mailMergeSettings.MainDocumentType = MailMergeMainDocumentType.MailingLabels;
mailMergeSettings.DataType = MailMergeDataType.Native;
mailMergeSettings.DataSource = ArtifactsDir + "Document.Lines.txt";
mailMergeSettings.Query = "SELECT * FROM " + doc.MailMergeSettings.DataSource;
mailMergeSettings.LinkToQuery = true;
mailMergeSettings.ViewMergedData = true;

// Office Data Source Object settings
Odso odso = mailMergeSettings.Odso;
odso.DataSourceType = OdsoDataSourceType.Text;
odso.ColumnDelimiter = '|';
odso.DataSource = ArtifactsDir + "Document.Lines.txt";
odso.FirstRowContainsColumnNames = true;

// The mail merge will be performed when this document is opened
doc.Save(ArtifactsDir + "Document.MailMergeSettings.docx");

Members

Member Name | Description | Value
None | No mail merge data source is specified. | -1
TextFile | Specifies that a given document has been connected to a text file via the Dynamic Data Exchange (DDE) system. | 0
Database | Specifies that a given document has been connected to an Access database via the Dynamic Data Exchange (DDE) system. | 1
Spreadsheet | Specifies that a given document has been connected to an Excel spreadsheet via the Dynamic Data Exchange (DDE) system. | 2
Query | Specifies that a given document has been connected to an external data source using an external query tool. | 3
Odbc | Specifies that a given document has been connected to an external data source via the Open Database Connectivity interface. | 4
Native | Specifies that a given document has been connected to an external data source via the Office Data Source Object (ODSO) interface. | 5
Default | Equals to None. | -1

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | DataType


MailMergeDestination Enumeration

Specifies the possible results which may be generated when a mail merge is carried out on a document.

[Visual Basic]
Public Enum MailMergeDestination
[C#]
public enum MailMergeDestination

Remarks

Members

Member Name | Description | Value
NewDocument | Specifies that conforming hosting applications shall generate new documents by populating the fields within a given document with data from the specified external data source. | 0
Printer | Specifies that conforming hosting applications shall print the documents that result from populating the fields within a given document with external data from the specified external data source. | 1
Email | Specifies that conforming hosting applications shall generate emails using the documents that result from populating the fields within a given document with data from the specified external data source. | 2
Fax | Specifies that conforming hosting applications shall generate faxes using the documents that result from populating the fields within a given document with data from the specified external data source. | 4
Default | Equals to the NewDocument value. | 0

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | Destination


MailMergeMainDocumentType Enumeration

Specifies the possible types for a mail merge source document.

[Visual Basic]
Public Enum MailMergeMainDocumentType
[C#]
public enum MailMergeMainDocumentType

Remarks

Example

Shows how to execute a mail merge with MailMergeSettings.

[C#]

// We'll create a simple document that will act as a destination for mail merge data
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Dear ");
builder.InsertField("MERGEFIELD FirstName", "<FirstName>");
builder.Write(" ");
builder.InsertField("MERGEFIELD LastName", "<LastName>");
builder.Writeln(": ");
builder.InsertField("MERGEFIELD Message", "<Message>");

// Also we'll need a data source, in this case it will be an ASCII text file
// We can use any character we want as a delimiter, in this case we'll choose '|'
// The delimiter character is selected in the ODSO settings of mail merge settings
string[] lines = { "FirstName|LastName|Message",
    "John|Doe|Hello! This message was created with Aspose Words mail merge." };
File.WriteAllLines(ArtifactsDir + "Document.Lines.txt", lines);

// Set the data source, query and other things
MailMergeSettings mailMergeSettings = doc.MailMergeSettings;
mailMergeSettings.MainDocumentType = MailMergeMainDocumentType.MailingLabels;
mailMergeSettings.DataType = MailMergeDataType.Native;
mailMergeSettings.DataSource = ArtifactsDir + "Document.Lines.txt";
mailMergeSettings.Query = "SELECT * FROM " + doc.MailMergeSettings.DataSource;
mailMergeSettings.LinkToQuery = true;
mailMergeSettings.ViewMergedData = true;

// Office Data Source Object settings
Odso odso = mailMergeSettings.Odso;
odso.DataSourceType = OdsoDataSourceType.Text;
odso.ColumnDelimiter = '|';
odso.DataSource = ArtifactsDir + "Document.Lines.txt";
odso.FirstRowContainsColumnNames = true;

// The mail merge will be performed when this document is opened
doc.Save(ArtifactsDir + "Document.MailMergeSettings.docx");

Members

Member Name | Description | Value
NotAMergeDocument | This document is not a mail merge document. | 0
FormLetters | Specifies that the mail merge source document is of the form letter type. | 1
MailingLabels | Specifies that the mail merge source document is of the mailing label type. | 2
Envelopes | Specifies that the mail merge source document is of the envelope type. | 4
Catalog | Specifies that the mail merge source document is of the catalog type. | 8
Email | Specifies that the mail merge source document is of the e-mail message type. | 16
Fax | Specifies that the mail merge source document is of the fax type. | 32
Default | Equals to NotAMergeDocument | 0

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | MainDocumentType


MailMergeSettings Class

Specifies all of the mail merge information for a document.

For a list of all members of this type, see MailMergeSettings Members.

System.Object
Aspose.Words.Settings.MailMergeSettings

[Visual Basic]
Public Class MailMergeSettings
[C#]
public class MailMergeSettings

Remarks

You can use this object to specify a mail merge data source for a document and this information (along with the available data fields) will appear in Microsoft Word when the user opens this document. Or you can use this object to query mail merge settings that the user has specified in Microsoft Word for this document.

You do not normally need to create objects of this class directly because Mail merge settings of a document are always available via the MailMergeSettings property.

To detect whether this document is a mail merge main document, check the value of the MainDocumentType property.

To remove mail merge settings and data source information from a document you can use the Clear method. Aspose.Words will not write mail merge settings to a document if the MainDocumentType property is set to NotAMergeDocument or the DataType property is set to None.

The best way to learn how to use the properties of this object is to create a document with a desired data source manually in Microsoft Word and then open that document using Aspose.Words and examine the properties of the MailMergeSettings and Odso objects. This is a good approach to take if you want to learn how to programmatically configure a data source, for example.

Aspose.Words preserves mail merge information when loading, saving and converting documents between different formats, but does not use this information when performing its own mail merge using the MailMerge object.

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

MailMergeSettings Members | Aspose.Words.Settings Namespace | MailMergeSettings


MailMergeSettings Members

MailMergeSettings overview

Public Instance Constructors

MailMergeSettings Constructor Initializes a new instance of the MailMergeSettings class.

Public Instance Properties

ActiveRecord | Specifies the one-based index of the record from the data source which shall be displayed in Microsoft Word. The default value is 1.
AddressFieldName | Specifies the column within the data source that contains e-mail addresses. The default value is an empty string.
CheckErrors | Specifies the type of error reporting which shall be conducted by Microsoft Word when performing a mail merge. The default value is Default.
ConnectString | Specifies the connection string used to connect to an external data source. The default value is an empty string.
DataSource | Specifies the path to the mail-merge data source. The default value is an empty string.
DataType | Specifies the type of the mail-merge data source and the method of data access. The default value is Default.
Destination | Specifies how Microsoft Word will output the results of a mail merge. The default value is Default.
DoNotSupressBlankLines | Specifies how an application performing the mail merge shall handle blank lines in the merged documents resulting from the mail merge. The default value is false.
HeaderSource | Specifies the path to the mail-merge header source. The default value is an empty string.
LinkToQuery | Not sure about this one. The Microsoft Word Automation Reference suggests that this specifies that the query is executed every time the document is opened in Microsoft Word. But the OOXML specification suggests that this specifies that the query contains a reference to an external query file which contains the actual query. The default value is false.
MailAsAttachment | Specifies that the documents produced during a mail merge operation should be emailed as an attachment rather than the body of the actual e-mail. The default value is false.
MailSubject | Specifies the text which shall appear in the subject line of the e-mails or faxes produced during mail merge. The default value is an empty string.
MainDocumentType | Specifies the mail-merge main document type. The default value is Default.
Odso | Gets or sets the object that specifies the Office Data Source Object (ODSO) settings.
Query | Contains the Structured Query Language string that shall be run against the specified external data source to return the set of records which shall be imported into the document when the mail merge operation is performed. The default value is an empty string.
ViewMergedData | Specifies that Microsoft Word shall display the data from the specified external data source where merge fields have been inserted (e.g. preview merged data). The default value is false.

Public Instance Methods

Clear | Clears the mail merge settings in such a way that when the document is saved, no mail merge settings will be saved and it will become a normal document.
Clone | Returns a deep clone of this object.

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace | MailMergeSettings


MailMergeSettings Constructor

Initializes a new instance of the MailMergeSettings class.

[Visual Basic]
Public Sub New()
[C#]
public MailMergeSettings();

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MailMergeSettings Properties

The properties of the MailMergeSettings class are listed below. For a complete list of MailMergeSettings class members, see the MailMergeSettings Members topic.

Public Instance Properties

ActiveRecord | Specifies the one-based index of the record from the data source which shall be displayed in Microsoft Word. The default value is 1.
AddressFieldName | Specifies the column within the data source that contains e-mail addresses. The default value is an empty string.
CheckErrors | Specifies the type of error reporting which shall be conducted by Microsoft Word when performing a mail merge. The default value is Default.
ConnectString | Specifies the connection string used to connect to an external data source. The default value is an empty string.
DataSource | Specifies the path to the mail-merge data source. The default value is an empty string.
DataType | Specifies the type of the mail-merge data source and the method of data access. The default value is Default.
Destination | Specifies how Microsoft Word will output the results of a mail merge. The default value is Default.
DoNotSupressBlankLines | Specifies how an application performing the mail merge shall handle blank lines in the merged documents resulting from the mail merge. The default value is false.
HeaderSource | Specifies the path to the mail-merge header source. The default value is an empty string.
LinkToQuery | Not sure about this one. The Microsoft Word Automation Reference suggests that this specifies that the query is executed every time the document is opened in Microsoft Word. But the OOXML specification suggests that this specifies that the query contains a reference to an external query file which contains the actual query. The default value is false.
MailAsAttachment | Specifies that the documents produced during a mail merge operation should be emailed as an attachment rather than the body of the actual e-mail. The default value is false.
MailSubject | Specifies the text which shall appear in the subject line of the e-mails or faxes produced during mail merge. The default value is an empty string.
MainDocumentType | Specifies the mail-merge main document type. The default value is Default.
Odso | Gets or sets the object that specifies the Office Data Source Object (ODSO) settings.
Query | Contains the Structured Query Language string that shall be run against the specified external data source to return the set of records which shall be imported into the document when the mail merge operation is performed. The default value is an empty string.
ViewMergedData | Specifies that Microsoft Word shall display the data from the specified external data source where merge fields have been inserted (e.g. preview merged data). The default value is false.

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace | MailMergeSettings


ActiveRecord Property

Aspose.Words

MailMergeSettings.ActiveRecord Property

Specifies the one-based index of the record from the data source which shall be displayed in Microsoft Word. The default value is 1.

[Visual Basic]
Public Property ActiveRecord As Integer
[C#]
public int ActiveRecord {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


AddressFieldName Property

Aspose.Words

MailMergeSettings.AddressFieldName Property

Specifies the column within the data source that contains e-mail addresses. The default value is an empty string.

[Visual Basic]
Public Property AddressFieldName As String
[C#]
public string AddressFieldName {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


CheckErrors Property

Aspose.Words

MailMergeSettings.CheckErrors Property

Specifies the type of error reporting which shall be conducted by Microsoft Word when performing a mail merge. The default value is Default.

[Visual Basic]
Public Property CheckErrors As MailMergeCheckErrors
[C#]
public MailMergeCheckErrors CheckErrors {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


ConnectString Property

Aspose.Words

MailMergeSettings.ConnectString Property

Specifies the connection string used to connect to an external data source. The default value is an empty string.

[Visual Basic]
Public Property ConnectString As String
[C#]
public string ConnectString {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


DataSource Property

Aspose.Words

MailMergeSettings.DataSource Property

Specifies the path to the mail-merge data source. The default value is an empty string.

[Visual Basic]
Public Property DataSource As String
[C#]
public string DataSource {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


DataType Property

Aspose.Words

MailMergeSettings.DataType Property

Specifies the type of the mail-merge data source and the method of data access. The default value is Default.

[Visual Basic]
Public Property DataType As MailMergeDataType
[C#]
public MailMergeDataType DataType {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


Destination Property

Aspose.Words

MailMergeSettings.Destination Property

Specifies how Microsoft Word will output the results of a mail merge. The default value is Default.

[Visual Basic]
Public Property Destination As MailMergeDestination
[C#]
public MailMergeDestination Destination {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


DoNotSupressBlankLines Property

Aspose.Words

MailMergeSettings.DoNotSupressBlankLines Property

Specifies how an application performing the mail merge shall handle blank lines in the merged documents resulting from the mail merge. The default value is false.

[Visual Basic]
Public Property DoNotSupressBlankLines As Boolean
[C#]
public bool DoNotSupressBlankLines {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


HeaderSource Property

Aspose.Words

MailMergeSettings.HeaderSource Property

Specifies the path to the mail-merge header source. The default value is an empty string.

[Visual Basic]
Public Property HeaderSource As String
[C#]
public string HeaderSource {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


LinkToQuery Property

Aspose.Words

MailMergeSettings.LinkToQuery Property

Not sure about this one. The Microsoft Word Automation Reference suggests that this specifies that the query is executed every time the document is opened in Microsoft Word. But the OOXML specification suggests that this specifies that the query contains a reference to an external query file which contains the actual query. The default value is false.

[Visual Basic]
Public Property LinkToQuery As Boolean
[C#]
public bool LinkToQuery {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MailAsAttachment Property

Aspose.Words

MailMergeSettings.MailAsAttachment Property

Specifies that the documents produced during a mail merge operation should be emailed as an attachment rather than the body of the actual e-mail. The default value is false.

[Visual Basic]
Public Property MailAsAttachment As Boolean
[C#]
public bool MailAsAttachment {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MailSubject Property

Aspose.Words

MailMergeSettings.MailSubject Property

Specifies the text which shall appear in the subject line of the e-mails or faxes produced during mail merge. The default value is an empty string.

[Visual Basic]
Public Property MailSubject As String
[C#]
public string MailSubject {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MainDocumentType Property

Aspose.Words

MailMergeSettings.MainDocumentType Property

Specifies the mail-merge main document type. The default value is Default.

[Visual Basic]
Public Property MainDocumentType As MailMergeMainDocumentType
[C#]
public MailMergeMainDocumentType MainDocumentType {get; set;}

Remarks

The main document is the document that contains information that is the same for each version of the merged document.

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


Odso Property

Aspose.Words

MailMergeSettings.Odso Property

Gets or sets the object that specifies the Office Data Source Object (ODSO) settings.

[Visual Basic]
Public Property Odso As Odso
[C#]
public Odso Odso {get; set;}

Remarks

This object is never null.

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


Query Property

Aspose.Words

MailMergeSettings.Query Property

Contains the Structured Query Language string that shall be run against the specified external data source to return the set of records which shall be imported into the document when the mail merge operation is performed. The default value is an empty string.

[Visual Basic]
Public Property Query As String
[C#]
public string Query {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


ViewMergedData Property

Aspose.Words

MailMergeSettings.ViewMergedData Property

Specifies that Microsoft Word shall display the data from the specified external data source where merge fields have been inserted (e.g. preview merged data). The default value is false.

[Visual Basic]
Public Property ViewMergedData As Boolean
[C#]
public bool ViewMergedData {get; set;}

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MailMergeSettings Methods

The methods of the MailMergeSettings class are listed below. For a complete list of MailMergeSettings class members, see the MailMergeSettings Members topic.

Public Instance Methods

Clear | Clears the mail merge settings in such a way that when the document is saved, no mail merge settings will be saved and it will become a normal document.
Clone | Returns a deep clone of this object.

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace | MailMergeSettings


MailMergeSettings.Clear Method

Clears the mail merge settings in such a way that when the document is saved, no mail merge settings will be saved and it will become a normal document.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MailMergeSettings.Clone Method

Returns a deep clone of this object.

[Visual Basic]
Public Function Clone() As MailMergeSettings
[C#]
public MailMergeSettings Clone();

See Also

MailMergeSettings Class | Aspose.Words.Settings Namespace


MsWordVersion Enumeration

Allows Aspose.Wods to mimic MS Word version-specific application behavior.

[Visual Basic]
Public Enum MsWordVersion
[C#]
public enum MsWordVersion

Example

Shows how to display the shape, inside a table or outside of it.

[C#]

Document doc = new Document(MyDir + "Shape.LayoutInCell.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);
int num = 1;

foreach (Run run in runs.OfType<Run>())
{
    Shape watermark = new Shape(doc, ShapeType.TextPlainText);
    watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
    watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
    watermark.IsLayoutInCell =
        true; // False - display the shape outside of table cell, True - display the shape outside of table cell

    watermark.Width = 30;
    watermark.Height = 30;
    watermark.HorizontalAlignment = HorizontalAlignment.Center;
    watermark.VerticalAlignment = VerticalAlignment.Center;

    watermark.Rotation = -40;
    watermark.Fill.Color = Color.Gainsboro;
    watermark.StrokeColor = Color.Gainsboro;

    watermark.TextPath.Text = string.Format("{0}", num);
    watermark.TextPath.FontFamily = "Arial";

    watermark.Name = string.Format("WaterMark_{0}", Guid.NewGuid());
    watermark.WrapType =
        WrapType.None; // Property will take effect only if the WrapType property is set to something other than WrapType.Inline
    watermark.BehindText = true;

    builder.MoveTo(run);
    builder.InsertNode(watermark);

    num = num + 1;
}

// Behaviour of MS Word on working with shapes in table cells is changed in the last versions.
// Adding the following line is needed to make the shape displayed in center of a page.
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2010);

doc.Save(ArtifactsDir + "Shape.LayoutInCell.docx");

Members

Member Name | Description | Value
Word2000 | Optimize Aspose.Words behavior to match MS Word 2000 version. | 0
Word2002 | Optimize Aspose.Words behavior to match MS Word 2002 version. | 1
Word2003 | Optimize Aspose.Words behavior to match MS Word 2003 version. | 2
Word2007 | Optimize Aspose.Words behavior to match MS Word 2007 version. | 3
Word2010 | Optimize Aspose.Words behavior to match MS Word 2010 version. | 4
Word2013 | Optimize Aspose.Words behavior to match MS Word 2013 version. | 5
Word2016 | Optimize Aspose.Words behavior to match MS Word 2016 version. | 6

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace


MultiplePagesType Enumeration

Specifies how document is printed out.

[Visual Basic]
Public Enum MultiplePagesType
[C#]
public enum MultiplePagesType

Members

Member Name | Description | Value
Normal | Normal printing, no multiple pages specified. | 0
MirrorMargins | Swaps left and right margins on facing pages. | 1
TwoPagesPerSheet | Prints two pages per sheet. | 2
BookFoldPrinting | Specifies whether to print the document as a book fold. | 3
BookFoldPrintingReverse | Specifies whether to print the document as a reverse book fold. | 4
Default | Default value is Normal | 0

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace


Odso Class

Specifies the Office Data Source Object (ODSO) settings for a mail merge data source.

For a list of all members of this type, see Odso Members.

System.Object
Aspose.Words.Settings.Odso

[Visual Basic]
Public Class Odso
[C#]
public class Odso

Remarks

ODSO seems to be the "new" way the newer Microsoft Word versions prefer to use when specifying certain types of data sources for a mail merge document. ODSO probably first appeared in Microsoft Word 2000.

The use of ODSO is poorly documented and the best way to learn how to use the properies of this object is to create a document with a desired data source manually in Microsoft Word and then open that document using Aspose.Words and examine the properties of the MailMergeSettings and Odso objects. This is a good approach to take if you want to learn how to programmatically configure a data source, for example.

You do not normally need to create objects of this class directly because ODSO settings are always available via the Odso property.

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Odso Members | Aspose.Words.Settings Namespace | Odso


Odso Members

Odso overview

Public Instance Constructors

Odso Constructor Initializes a new instance of the Odso class.

Public Instance Properties

ColumnDelimiter | Specifies the character which shall be interpreted as the column delimiter used to separate columns within external data sources. The default value is 0 which means there is no column delimiter defined.
DataSource | Specifies the location of the external data source to be connected to a document to perform the mail merge. The default value is an empty string.
DataSourceType | Specifies the type of the external data source to be connected to as part of the ODSO connection information for this mail merge. The default value is Default.
FieldMapDatas | Gets or sets a collection of objects that specify how columns from the external data source are mapped to the predefined merge field names in the document. This object is never null.
FirstRowContainsColumnNames | Specifies that a hosting application shall treat the first row of data in the specified external data source as a header row containing the names of each column in the data source. The default value is false.
RecipientDatas | Gets or sets a collection of objects that specify inclusion/exclusion of individual records in the mail merge. This object is never null.
TableName | Specifies the particular set of data that a source shall be connected to within an external data source. The default value is an empty string.
UdlConnectString | Specifies the Universal Data Link (UDL) connection string used to connect to an external data source. The default value is an empty string.

Public Instance Methods

Clone Returns a deep clone of this object.

See Also

Odso Class | Aspose.Words.Settings Namespace | Odso


Odso Constructor

Initializes a new instance of the Odso class.

[Visual Basic]
Public Sub New()
[C#]
public Odso();

See Also

Odso Class | Aspose.Words.Settings Namespace


Odso Properties

The properties of the Odso class are listed below. For a complete list of Odso class members, see the Odso Members topic.

Public Instance Properties

ColumnDelimiter | Specifies the character which shall be interpreted as the column delimiter used to separate columns within external data sources. The default value is 0 which means there is no column delimiter defined.
DataSource | Specifies the location of the external data source to be connected to a document to perform the mail merge. The default value is an empty string.
DataSourceType | Specifies the type of the external data source to be connected to as part of the ODSO connection information for this mail merge. The default value is Default.
FieldMapDatas | Gets or sets a collection of objects that specify how columns from the external data source are mapped to the predefined merge field names in the document. This object is never null.
FirstRowContainsColumnNames | Specifies that a hosting application shall treat the first row of data in the specified external data source as a header row containing the names of each column in the data source. The default value is false.
RecipientDatas | Gets or sets a collection of objects that specify inclusion/exclusion of individual records in the mail merge. This object is never null.
TableName | Specifies the particular set of data that a source shall be connected to within an external data source. The default value is an empty string.
UdlConnectString | Specifies the Universal Data Link (UDL) connection string used to connect to an external data source. The default value is an empty string.

See Also

Odso Class | Aspose.Words.Settings Namespace | Odso


ColumnDelimiter Property

Aspose.Words

Odso.ColumnDelimiter Property

Specifies the character which shall be interpreted as the column delimiter used to separate columns within external data sources. The default value is 0 which means there is no column delimiter defined.

[Visual Basic]
Public Property ColumnDelimiter As Char
[C#]
public char ColumnDelimiter {get; set;}

Remarks

RK I have never seen this in use.

See Also

Odso Class | Aspose.Words.Settings Namespace


DataSource Property

Aspose.Words

Odso.DataSource Property

Specifies the location of the external data source to be connected to a document to perform the mail merge. The default value is an empty string.

[Visual Basic]
Public Property DataSource As String
[C#]
public string DataSource {get; set;}

See Also

Odso Class | Aspose.Words.Settings Namespace


DataSourceType Property

Aspose.Words

Odso.DataSourceType Property

Specifies the type of the external data source to be connected to as part of the ODSO connection information for this mail merge. The default value is Default.

[Visual Basic]
Public Property DataSourceType As OdsoDataSourceType
[C#]
public OdsoDataSourceType DataSourceType {get; set;}

Remarks

This setting is purely a suggestion of the data source type that is being used for this mail merge.

See Also

Odso Class | Aspose.Words.Settings Namespace


FieldMapDatas Property

Aspose.Words

Odso.FieldMapDatas Property

Gets or sets a collection of objects that specify how columns from the external data source are mapped to the predefined merge field names in the document. This object is never null.

[Visual Basic]
Public Property FieldMapDatas As OdsoFieldMapDataCollection
[C#]
public OdsoFieldMapDataCollection FieldMapDatas {get; set;}

See Also

Odso Class | Aspose.Words.Settings Namespace


FirstRowContainsColumnNames Property

Aspose.Words

Odso.FirstRowContainsColumnNames Property

Specifies that a hosting application shall treat the first row of data in the specified external data source as a header row containing the names of each column in the data source. The default value is false.

[Visual Basic]
Public Property FirstRowContainsColumnNames As Boolean
[C#]
public bool FirstRowContainsColumnNames {get; set;}

Remarks

RK I have never seen this in use.

See Also

Odso Class | Aspose.Words.Settings Namespace


RecipientDatas Property

Aspose.Words

Odso.RecipientDatas Property

Gets or sets a collection of objects that specify inclusion/exclusion of individual records in the mail merge. This object is never null.

[Visual Basic]
Public Property RecipientDatas As OdsoRecipientDataCollection
[C#]
public OdsoRecipientDataCollection RecipientDatas {get; set;}

See Also

Odso Class | Aspose.Words.Settings Namespace


TableName Property

Aspose.Words

Odso.TableName Property

Specifies the particular set of data that a source shall be connected to within an external data source. The default value is an empty string.

[Visual Basic]
Public Property TableName As String
[C#]
public string TableName {get; set;}

See Also

Odso Class | Aspose.Words.Settings Namespace


UdlConnectString Property

Aspose.Words

Odso.UdlConnectString Property

Specifies the Universal Data Link (UDL) connection string used to connect to an external data source. The default value is an empty string.

[Visual Basic]
Public Property UdlConnectString As String
[C#]
public string UdlConnectString {get; set;}

See Also

Odso Class | Aspose.Words.Settings Namespace


Odso Methods

The methods of the Odso class are listed below. For a complete list of Odso class members, see the Odso Members topic.

Public Instance Methods

Clone Returns a deep clone of this object.

See Also

Odso Class | Aspose.Words.Settings Namespace | Odso


Odso.Clone Method

Returns a deep clone of this object.

[Visual Basic]
Public Function Clone() As Odso
[C#]
public Odso Clone();

See Also

Odso Class | Aspose.Words.Settings Namespace


OdsoDataSourceType Enumeration

Specifies the type of the external data source to be connected to as part of the ODSO connection information.

[Visual Basic]
Public Enum OdsoDataSourceType
[C#]
public enum OdsoDataSourceType

Remarks

The OOXML specification is very vague for this enum. I guess it might correspond to the WdMergeSubType enumeration http://msdn.microsoft.com/en-us/library/bb237801.aspx.

Members

Member Name | Description | Value
Text | Specifies that a given document has been connected to a text file. Possibly wdMergeSubTypeOther. | 0
Database | Specifies that a given document has been connected to a database. Possibly wdMergeSubTypeAccess. | 1
AddressBook | Specifies that a given document has been connected to an address book of contacts. Possibly wdMergeSubTypeOAL. | 2
Document1 | Specifies that a given document has been connected to another document format supported by the producing application. Possibly wdMergeSubTypeOLEDBWord. | 3
Document2 | Specifies that a given document has been connected to another document format supported by the producing application. Possibly wdMergeSubTypeWorks. | 4
Native | Specifies that a given document has been connected to another document format native to the producing application. Possibly wdMergeSubTypeOLEDBText | 5
Email | Specifies that a given document has been connected to an e-mail application. Possibly wdMergeSubTypeOutlook. | 6
None | The type of the external data source is not specified. Possibly wdMergeSubTypeWord. | 7
Legacy | Specifies that a given document has been connected to a legacy document format supported by the producing application Possibly wdMergeSubTypeWord2000. | 8
Master | Specifies that a given document has been connected to a data source which aggregates other data sources. | 9
Default | Equals to None. | 7

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | DataSourceType


OdsoFieldMapData Class

Specifies how a column in the external data source shall be mapped to the predefined merge fields within the document.

For a list of all members of this type, see OdsoFieldMapData Members.

System.Object
Aspose.Words.Settings.OdsoFieldMapData

[Visual Basic]
Public Class OdsoFieldMapData
[C#]
public class OdsoFieldMapData

Remarks

Microsoft Word provides some predefined merge field names that it allows to insert into a document as MERGEFIELD or use in the ADDRESSBLOCK or GREETINGLINE fields. The information specified in OdsoFieldMapData allows to map one column in the external data source to a single predefined merge field.

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OdsoFieldMapData Members | Aspose.Words.Settings Namespace | OdsoFieldMapDataCollection | Odso


OdsoFieldMapData Members

OdsoFieldMapData overview

Public Instance Constructors

OdsoFieldMapData Constructor Initializes a new instance of the OdsoFieldMapData class.

Public Instance Properties

Column | Specifies the zero-based index of the column within an external data source which shall be mapped to the local name of a specific MERGEFIELD field. The default value is 0.
MappedName | Specifies the predefined merge field name which shall be mapped to the column number specified by the Column property within this field mapping. The default value is an empty string.
Name | Specifies the column name within an external data source for the column whose index is specified by the Column property. The default value is an empty string.
Type | Specifies if a given mail merge field has been mapped to a column in the given external data source or not. The default value is Default.

Public Instance Methods

Clone Returns a deep clone of this object.

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace | OdsoFieldMapDataCollection | Odso


OdsoFieldMapData Constructor

Initializes a new instance of the OdsoFieldMapData class.

[Visual Basic]
Public Sub New()
[C#]
public OdsoFieldMapData();

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace


OdsoFieldMapData Properties

The properties of the OdsoFieldMapData class are listed below. For a complete list of OdsoFieldMapData class members, see the OdsoFieldMapData Members topic.

Public Instance Properties

Column | Specifies the zero-based index of the column within an external data source which shall be mapped to the local name of a specific MERGEFIELD field. The default value is 0.
MappedName | Specifies the predefined merge field name which shall be mapped to the column number specified by the Column property within this field mapping. The default value is an empty string.
Name | Specifies the column name within an external data source for the column whose index is specified by the Column property. The default value is an empty string.
Type | Specifies if a given mail merge field has been mapped to a column in the given external data source or not. The default value is Default.

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace | OdsoFieldMapDataCollection | Odso


Column Property

Aspose.Words

OdsoFieldMapData.Column Property

Specifies the zero-based index of the column within an external data source which shall be mapped to the local name of a specific MERGEFIELD field. The default value is 0.

[Visual Basic]
Public Property Column As Integer
[C#]
public int Column {get; set;}

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace


MappedName Property

Aspose.Words

OdsoFieldMapData.MappedName Property

Specifies the predefined merge field name which shall be mapped to the column number specified by the Column property within this field mapping. The default value is an empty string.

[Visual Basic]
Public Property MappedName As String
[C#]
public string MappedName {get; set;}

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace


Name Property

Aspose.Words

OdsoFieldMapData.Name Property

Specifies the column name within an external data source for the column whose index is specified by the Column property. The default value is an empty string.

[Visual Basic]
Public Property Name As String
[C#]
public string Name {get; set;}

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace


Type Property

Aspose.Words

OdsoFieldMapData.Type Property

Specifies if a given mail merge field has been mapped to a column in the given external data source or not. The default value is Default.

[Visual Basic]
Public Property Type As OdsoFieldMappingType
[C#]
public OdsoFieldMappingType Type {get; set;}

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace


OdsoFieldMapData Methods

The methods of the OdsoFieldMapData class are listed below. For a complete list of OdsoFieldMapData class members, see the OdsoFieldMapData Members topic.

Public Instance Methods

Clone Returns a deep clone of this object.

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace | OdsoFieldMapDataCollection | Odso


OdsoFieldMapData.Clone Method

Returns a deep clone of this object.

[Visual Basic]
Public Function Clone() As OdsoFieldMapData
[C#]
public OdsoFieldMapData Clone();

See Also

OdsoFieldMapData Class | Aspose.Words.Settings Namespace


OdsoFieldMapDataCollection Class

A typed collection of the OdsoFieldMapData objects.

For a list of all members of this type, see OdsoFieldMapDataCollection Members.

System.Object
Aspose.Words.Settings.OdsoFieldMapDataCollection

[Visual Basic]
Public Class OdsoFieldMapDataCollection
Implements IEnumerable`1([Aspose.Words.Settings.OdsoFieldMapData, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class OdsoFieldMapDataCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OdsoFieldMapDataCollection Members | Aspose.Words.Settings Namespace | OdsoFieldMapData | FieldMapDatas


OdsoFieldMapDataCollection Members

OdsoFieldMapDataCollection overview

Public Instance Constructors

OdsoFieldMapDataCollection Constructor Initializes a new instance of the OdsoFieldMapDataCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item in this collection.

Public Instance Methods

Add | Adds an object to the end of this collection.
Clear | Removes all elements from this collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes the element at the specified index.

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace | OdsoFieldMapData | FieldMapDatas


OdsoFieldMapDataCollection Constructor

Initializes a new instance of the OdsoFieldMapDataCollection class.

[Visual Basic]
Public Sub New()
[C#]
public OdsoFieldMapDataCollection();

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


OdsoFieldMapDataCollection Properties

The properties of the OdsoFieldMapDataCollection class are listed below. For a complete list of OdsoFieldMapDataCollection class members, see the OdsoFieldMapDataCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item in this collection.

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace | OdsoFieldMapData | FieldMapDatas


Count Property

Aspose.Words

OdsoFieldMapDataCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


Item Property

Aspose.Words

OdsoFieldMapDataCollection.Item Property

Gets or sets an item in this collection.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As OdsoFieldMapData
[C#]
public OdsoFieldMapData this[
int index
] {get; set;}

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


OdsoFieldMapDataCollection Methods

The methods of the OdsoFieldMapDataCollection class are listed below. For a complete list of OdsoFieldMapDataCollection class members, see the OdsoFieldMapDataCollection Members topic.

Public Instance Methods

Add | Adds an object to the end of this collection.
Clear | Removes all elements from this collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes the element at the specified index.

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace | OdsoFieldMapData | FieldMapDatas


OdsoFieldMapDataCollection.Add Method

Adds an object to the end of this collection.

[Visual Basic]
Public Function Add( _
ByVal value As OdsoFieldMapData _
) As Integer
[C#]
public int Add(
OdsoFieldMapData value
);

Parameters

value
The object to add. Cannot be null.

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


OdsoFieldMapDataCollection.Clear Method

Removes all elements from this collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


OdsoFieldMapDataCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of OdsoFieldMapData) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<OdsoFieldMapData> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


OdsoFieldMapDataCollection.RemoveAt Method

Removes the element at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the element.

See Also

OdsoFieldMapDataCollection Class | Aspose.Words.Settings Namespace


OdsoFieldMappingType Enumeration

Specifies the possible types used to indicate if a given mail merge field has been mapped to a column in the given external data source.

[Visual Basic]
Public Enum OdsoFieldMappingType
[C#]
public enum OdsoFieldMappingType

Remarks

Members

Member Name | Description | Value
Column | Specifies that the mail merge field has been mapped to a column in the given external data source. | 0
Null | Specifies that the mail merge field has not been mapped to a column in the given external data source. | 1
Default | Equals to Null. | 1

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | Type


OdsoRecipientData Class

Represents information about a single record within an external data source that is to be excluded from the mail merge.

For a list of all members of this type, see OdsoRecipientData Members.

System.Object
Aspose.Words.Settings.OdsoRecipientData

[Visual Basic]
Public Class OdsoRecipientData
[C#]
public class OdsoRecipientData

Remarks

If a record shall be merged into a merged document, then no information is needed about that record. However, if a given record shall not be merged into a merged document, then the value of the unique key for that record shall be stored in the UniqueTag property of this object to indicate this exclusion.

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OdsoRecipientData Members | Aspose.Words.Settings Namespace


OdsoRecipientData Members

OdsoRecipientData overview

Public Instance Constructors

OdsoRecipientData Constructor Initializes a new instance of the OdsoRecipientData class.

Public Instance Properties

Active | Specifies whether the record from the data source shall be imported into a document when the mail merge is performed. The default value is true.
Column | Specifies the column within the data source that contains unique data for the current record. The default value is 0.
Hash | Represents the hash code for this record. Sometimes Microsoft Word uses Hash of a whole record instead of a UniqueTag value. The default value is 0.
UniqueTag | Specifies the contents of a given record in the column containing unique data. The default value is null.

Public Instance Methods

Clone Returns a deep clone of this object.

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


OdsoRecipientData Constructor

Initializes a new instance of the OdsoRecipientData class.

[Visual Basic]
Public Sub New()
[C#]
public OdsoRecipientData();

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


OdsoRecipientData Properties

The properties of the OdsoRecipientData class are listed below. For a complete list of OdsoRecipientData class members, see the OdsoRecipientData Members topic.

Public Instance Properties

Active | Specifies whether the record from the data source shall be imported into a document when the mail merge is performed. The default value is true.
Column | Specifies the column within the data source that contains unique data for the current record. The default value is 0.
Hash | Represents the hash code for this record. Sometimes Microsoft Word uses Hash of a whole record instead of a UniqueTag value. The default value is 0.
UniqueTag | Specifies the contents of a given record in the column containing unique data. The default value is null.

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


Active Property

Aspose.Words

OdsoRecipientData.Active Property

Specifies whether the record from the data source shall be imported into a document when the mail merge is performed. The default value is true.

[Visual Basic]
Public Property Active As Boolean
[C#]
public bool Active {get; set;}

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


Column Property

Aspose.Words

OdsoRecipientData.Column Property

Specifies the column within the data source that contains unique data for the current record. The default value is 0.

[Visual Basic]
Public Property Column As Integer
[C#]
public int Column {get; set;}

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


Hash Property

Aspose.Words

OdsoRecipientData.Hash Property

Represents the hash code for this record. Sometimes Microsoft Word uses Hash of a whole record instead of a UniqueTag value. The default value is 0.

[Visual Basic]
Public Property Hash As Integer
[C#]
public int Hash {get; set;}

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


UniqueTag Property

Aspose.Words

OdsoRecipientData.UniqueTag Property

Specifies the contents of a given record in the column containing unique data. The default value is null.

[Visual Basic]
Public Property UniqueTag As Byte()
[C#]
public byte[] UniqueTag {get; set;}

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


OdsoRecipientData Methods

The methods of the OdsoRecipientData class are listed below. For a complete list of OdsoRecipientData class members, see the OdsoRecipientData Members topic.

Public Instance Methods

Clone Returns a deep clone of this object.

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


OdsoRecipientData.Clone Method

Returns a deep clone of this object.

[Visual Basic]
Public Function Clone() As OdsoRecipientData
[C#]
public OdsoRecipientData Clone();

See Also

OdsoRecipientData Class | Aspose.Words.Settings Namespace


OdsoRecipientDataCollection Class

A typed collection of OdsoRecipientData

For a list of all members of this type, see OdsoRecipientDataCollection Members.

System.Object
Aspose.Words.Settings.OdsoRecipientDataCollection

[Visual Basic]
Public Class OdsoRecipientDataCollection
Implements IEnumerable`1([Aspose.Words.Settings.OdsoRecipientData, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56)), IEnumerable
[C#]
public class OdsoRecipientDataCollection : 0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], IEnumerable

Remarks

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

OdsoRecipientDataCollection Members | Aspose.Words.Settings Namespace | OdsoRecipientData | RecipientDatas


OdsoRecipientDataCollection Members

OdsoRecipientDataCollection overview

Public Instance Constructors

OdsoRecipientDataCollection Constructor Initializes a new instance of the OdsoRecipientDataCollection class.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item in this collection.

Public Instance Methods

Add | Adds an object to the end of this collection.
Clear | Removes all elements from this collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes the element at the specified index.

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace | OdsoRecipientData | RecipientDatas


OdsoRecipientDataCollection Constructor

Initializes a new instance of the OdsoRecipientDataCollection class.

[Visual Basic]
Public Sub New()
[C#]
public OdsoRecipientDataCollection();

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


OdsoRecipientDataCollection Properties

The properties of the OdsoRecipientDataCollection class are listed below. For a complete list of OdsoRecipientDataCollection class members, see the OdsoRecipientDataCollection Members topic.

Public Instance Properties

Count | Gets the number of elements contained in the collection.
Item | Gets or sets an item in this collection.

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace | OdsoRecipientData | RecipientDatas


Count Property

Aspose.Words

OdsoRecipientDataCollection.Count Property

Gets the number of elements contained in the collection.

[Visual Basic]
Public ReadOnly Property Count As Integer
[C#]
public int Count {get;}

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


Item Property

Aspose.Words

OdsoRecipientDataCollection.Item Property

Gets or sets an item in this collection.

[Visual Basic]
Public Default Property Item( _
ByVal index As Integer _
) As OdsoRecipientData
[C#]
public OdsoRecipientData this[
int index
] {get; set;}

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


OdsoRecipientDataCollection Methods

The methods of the OdsoRecipientDataCollection class are listed below. For a complete list of OdsoRecipientDataCollection class members, see the OdsoRecipientDataCollection Members topic.

Public Instance Methods

Add | Adds an object to the end of this collection.
Clear | Removes all elements from this collection.
GetEnumerator | Returns an enumerator object that can be used to iterate over all items in the collection.
RemoveAt | Removes the element at the specified index.

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace | OdsoRecipientData | RecipientDatas


OdsoRecipientDataCollection.Add Method

Adds an object to the end of this collection.

[Visual Basic]
Public Function Add( _
ByVal value As OdsoRecipientData _
) As Integer
[C#]
public int Add(
OdsoRecipientData value
);

Parameters

value
The object to add. Cannot be null.

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


OdsoRecipientDataCollection.Clear Method

Removes all elements from this collection.

[Visual Basic]
Public Sub Clear()
[C#]
public void Clear();

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


OdsoRecipientDataCollection.GetEnumerator Method

Returns an enumerator object that can be used to iterate over all items in the collection.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator(Of OdsoRecipientData) _
Implements IEnumerable`1.GetEnumerator
[C#]
public IEnumerator<OdsoRecipientData> GetEnumerator();

Implements

IEnumerable`1.GetEnumerator

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


OdsoRecipientDataCollection.RemoveAt Method

Removes the element at the specified index.

[Visual Basic]
Public Sub RemoveAt( _
ByVal index As Integer _
)
[C#]
public void RemoveAt(
int index
);

Parameters

index
The zero-based index of the element.

See Also

OdsoRecipientDataCollection Class | Aspose.Words.Settings Namespace


ViewOptions Class

Provides various options that control how a document is shown in Microsoft Word.

For a list of all members of this type, see ViewOptions Members.

System.Object
Aspose.Words.Settings.ViewOptions

[Visual Basic]
Public Class ViewOptions
[C#]
public class ViewOptions

Remarks

Example

The following code shows how to make sure the document is displayed at 50% zoom when opened in Microsoft Word.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
doc.Save(ArtifactsDir + "Document.SetZoom.doc");

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ViewOptions Members | Aspose.Words.Settings Namespace | Document | ViewOptions


ViewOptions Members

ViewOptions overview

Public Instance Properties

DisplayBackgroundShape | Controls display of the background shape in print layout view.
DoNotDisplayPageBoundaries | Turns off display of the space between the top of the text and the top edge of the page.
FormsDesign | Specifies whether the document is in forms design mode.
ViewType | Controls the view mode in Microsoft Word.
ZoomPercent | Gets or sets the percentage (between 10 and 500) at which you want to view your document.
ZoomType | Gets or sets a zoom value based on the size of the window.

See Also

ViewOptions Class | Aspose.Words.Settings Namespace | Document | ViewOptions


ViewOptions Properties

The properties of the ViewOptions class are listed below. For a complete list of ViewOptions class members, see the ViewOptions Members topic.

Public Instance Properties

DisplayBackgroundShape | Controls display of the background shape in print layout view.
DoNotDisplayPageBoundaries | Turns off display of the space between the top of the text and the top edge of the page.
FormsDesign | Specifies whether the document is in forms design mode.
ViewType | Controls the view mode in Microsoft Word.
ZoomPercent | Gets or sets the percentage (between 10 and 500) at which you want to view your document.
ZoomType | Gets or sets a zoom value based on the size of the window.

See Also

ViewOptions Class | Aspose.Words.Settings Namespace | Document | ViewOptions


DisplayBackgroundShape Property

Aspose.Words

ViewOptions.DisplayBackgroundShape Property

Controls display of the background shape in print layout view.

[Visual Basic]
Public Property DisplayBackgroundShape As Boolean
[C#]
public bool DisplayBackgroundShape {get; set;}

See Also

ViewOptions Class | Aspose.Words.Settings Namespace


DoNotDisplayPageBoundaries Property

Aspose.Words

ViewOptions.DoNotDisplayPageBoundaries Property

Turns off display of the space between the top of the text and the top edge of the page.

[Visual Basic]
Public Property DoNotDisplayPageBoundaries As Boolean
[C#]
public bool DoNotDisplayPageBoundaries {get; set;}

See Also

ViewOptions Class | Aspose.Words.Settings Namespace


FormsDesign Property

Aspose.Words

ViewOptions.FormsDesign Property

Specifies whether the document is in forms design mode.

[Visual Basic]
Public Property FormsDesign As Boolean
[C#]
public bool FormsDesign {get; set;}

Remarks

Currently works only for documents in WordML format.

See Also

ViewOptions Class | Aspose.Words.Settings Namespace


ViewType Property

Aspose.Words

ViewOptions.ViewType Property

Controls the view mode in Microsoft Word.

[Visual Basic]
Public Property ViewType As ViewType
[C#]
public ViewType ViewType {get; set;}

Remarks

Although Aspose.Words is able to read and write this option, its usage is application-specific. For example MS Word 2013 does not respect the value of this option.

Example

The following code shows how to make sure the document is displayed at 50% zoom when opened in Microsoft Word.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
doc.Save(ArtifactsDir + "Document.SetZoom.doc");

See Also

ViewOptions Class | Aspose.Words.Settings Namespace


ZoomPercent Property

Aspose.Words

ViewOptions.ZoomPercent Property

Gets or sets the percentage (between 10 and 500) at which you want to view your document.

[Visual Basic]
Public Property ZoomPercent As Integer
[C#]
public int ZoomPercent {get; set;}

Remarks

If value is 0 then this property uses 100 instead, else if value is less than 10 or greater than 500 this property throws.

Although Aspose.Words is able to read and write this option, its usage is application-specific. For example MS Word 2013 does not respect the value of this option.

Example

The following code shows how to make sure the document is displayed at 50% zoom when opened in Microsoft Word.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
doc.Save(ArtifactsDir + "Document.SetZoom.doc");

See Also

ViewOptions Class | Aspose.Words.Settings Namespace


ZoomType Property

Aspose.Words

ViewOptions.ZoomType Property

Gets or sets a zoom value based on the size of the window.

[Visual Basic]
Public Property ZoomType As ZoomType
[C#]
public ZoomType ZoomType {get; set;}

See Also

ViewOptions Class | Aspose.Words.Settings Namespace


ViewType Enumeration

Possible values for the view mode in Microsoft Word.

[Visual Basic]
Public Enum ViewType
[C#]
public enum ViewType

Remarks

Example

The following code shows how to make sure the document is displayed at 50% zoom when opened in Microsoft Word.

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
doc.Save(ArtifactsDir + "Document.SetZoom.doc");

Members

Member Name | Description | Value
None | The document shall be rendered in the default view of the application. | 0
Reading | The document shall be rendered in the default view of the application. | 0
PageLayout | The document shall be opened in a view that displays the document as it will print. | 1
Outline | The document shall be rendered in a view optimized for outlining or creating long documents. | 3
Normal | The document shall be rendered in a view optimized for outlining or creating long documents. | 4
Web | The document shall be rendered in a view mimicking the way this document would be displayed in a web page. | 5

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | ViewOptions | ViewType


WriteProtection Class

Specifies write protection settings for a document.

For a list of all members of this type, see WriteProtection Members.

System.Object
Aspose.Words.Settings.WriteProtection

[Visual Basic]
Public Class WriteProtection
[C#]
public class WriteProtection

Remarks

Write protection specifies whether the author has recommended that the document is to be opened as read-only and/or require a password to modify a document.

Write protection is different from document protection. Write protection is specified in Microsoft Word in the options of the Save As dialog box.

You do not create instances of this class directly. You access document protection settings via the WriteProtection property.

Example

Shows how to protect a document with a password.

[C#]

Document doc = new Document();
Assert.IsFalse(doc.WriteProtection.IsWriteProtected);
Assert.IsFalse(doc.WriteProtection.ReadOnlyRecommended);

// Enter a password that's 15 or less characters long
doc.WriteProtection.SetPassword("docpassword123");
Assert.IsTrue(doc.WriteProtection.IsWriteProtected);

Assert.IsFalse(doc.WriteProtection.ValidatePassword("wrongpassword"));

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("We can still edit the document at this stage.");

// Save the document
// Without the password, we can only read this document in Microsoft Word
// With the password, we can read and write
doc.Save(ArtifactsDir + "Document.WriteProtection.docx");

// Re-open our document
Document docProtected = new Document(ArtifactsDir + "Document.WriteProtection.docx");
DocumentBuilder docProtectedBuilder = new DocumentBuilder(docProtected);
docProtectedBuilder.MoveToDocumentEnd();

// We can programmatically edit this document without using our password
Assert.IsTrue(docProtected.WriteProtection.IsWriteProtected);
docProtectedBuilder.Writeln("Writing text in a protected document.");

// We will still need the password if we want to open this one with Word
docProtected.Save(ArtifactsDir + "Document.WriteProtectionEditedAfter.docx");

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

WriteProtection Members | Aspose.Words.Settings Namespace


WriteProtection Members

WriteProtection overview

Public Instance Properties

IsWriteProtected | Returns true when a write protection password is set.
ReadOnlyRecommended | Specifies whether the document author has recommended that the document be opened as read-only.

Public Instance Methods

SetPassword | Sets the write protection password for the document.
ValidatePassword | Returns true if the specified password is the same as the write-protection password the document was protected with. If document is not write-protected with password then returns false.

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


WriteProtection Properties

The properties of the WriteProtection class are listed below. For a complete list of WriteProtection class members, see the WriteProtection Members topic.

Public Instance Properties

IsWriteProtected | Returns true when a write protection password is set.
ReadOnlyRecommended | Specifies whether the document author has recommended that the document be opened as read-only.

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


IsWriteProtected Property

Aspose.Words

WriteProtection.IsWriteProtected Property

Returns true when a write protection password is set.

[Visual Basic]
Public ReadOnly Property IsWriteProtected As Boolean
[C#]
public bool IsWriteProtected {get;}

Example

Shows how to protect a document with a password.

[C#]

Document doc = new Document();
Assert.IsFalse(doc.WriteProtection.IsWriteProtected);
Assert.IsFalse(doc.WriteProtection.ReadOnlyRecommended);

// Enter a password that's 15 or less characters long
doc.WriteProtection.SetPassword("docpassword123");
Assert.IsTrue(doc.WriteProtection.IsWriteProtected);

Assert.IsFalse(doc.WriteProtection.ValidatePassword("wrongpassword"));

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("We can still edit the document at this stage.");

// Save the document
// Without the password, we can only read this document in Microsoft Word
// With the password, we can read and write
doc.Save(ArtifactsDir + "Document.WriteProtection.docx");

// Re-open our document
Document docProtected = new Document(ArtifactsDir + "Document.WriteProtection.docx");
DocumentBuilder docProtectedBuilder = new DocumentBuilder(docProtected);
docProtectedBuilder.MoveToDocumentEnd();

// We can programmatically edit this document without using our password
Assert.IsTrue(docProtected.WriteProtection.IsWriteProtected);
docProtectedBuilder.Writeln("Writing text in a protected document.");

// We will still need the password if we want to open this one with Word
docProtected.Save(ArtifactsDir + "Document.WriteProtectionEditedAfter.docx");

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


ReadOnlyRecommended Property

Aspose.Words

WriteProtection.ReadOnlyRecommended Property

Specifies whether the document author has recommended that the document be opened as read-only.

[Visual Basic]
Public Property ReadOnlyRecommended As Boolean
[C#]
public bool ReadOnlyRecommended {get; set;}

Example

Shows how to protect a document with a password.

[C#]

Document doc = new Document();
Assert.IsFalse(doc.WriteProtection.IsWriteProtected);
Assert.IsFalse(doc.WriteProtection.ReadOnlyRecommended);

// Enter a password that's 15 or less characters long
doc.WriteProtection.SetPassword("docpassword123");
Assert.IsTrue(doc.WriteProtection.IsWriteProtected);

Assert.IsFalse(doc.WriteProtection.ValidatePassword("wrongpassword"));

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("We can still edit the document at this stage.");

// Save the document
// Without the password, we can only read this document in Microsoft Word
// With the password, we can read and write
doc.Save(ArtifactsDir + "Document.WriteProtection.docx");

// Re-open our document
Document docProtected = new Document(ArtifactsDir + "Document.WriteProtection.docx");
DocumentBuilder docProtectedBuilder = new DocumentBuilder(docProtected);
docProtectedBuilder.MoveToDocumentEnd();

// We can programmatically edit this document without using our password
Assert.IsTrue(docProtected.WriteProtection.IsWriteProtected);
docProtectedBuilder.Writeln("Writing text in a protected document.");

// We will still need the password if we want to open this one with Word
docProtected.Save(ArtifactsDir + "Document.WriteProtectionEditedAfter.docx");

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


WriteProtection Methods

The methods of the WriteProtection class are listed below. For a complete list of WriteProtection class members, see the WriteProtection Members topic.

Public Instance Methods

SetPassword | Sets the write protection password for the document.
ValidatePassword | Returns true if the specified password is the same as the write-protection password the document was protected with. If document is not write-protected with password then returns false.

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


WriteProtection.SetPassword Method

Sets the write protection password for the document.

[Visual Basic]
Public Sub SetPassword( _
ByVal password As String _
)
[C#]
public void SetPassword(
string password
);

Parameters

password
The password to set. Cannot be null, but can be an empty string.

Remarks

If a password is set, Microsoft Word will require the user to enter it or open the document as read-only.

Example

Sets the write protection password for the document.

[C#]

Document doc = new Document();
doc.WriteProtection.SetPassword("pwd");

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


WriteProtection.ValidatePassword Method

Returns true if the specified password is the same as the write-protection password the document was protected with. If document is not write-protected with password then returns false.

[Visual Basic]
Public Function ValidatePassword( _
ByVal password As String _
) As Boolean
[C#]
public bool ValidatePassword(
string password
);

Example

Shows how to protect a document with a password.

[C#]

Document doc = new Document();
Assert.IsFalse(doc.WriteProtection.IsWriteProtected);
Assert.IsFalse(doc.WriteProtection.ReadOnlyRecommended);

// Enter a password that's 15 or less characters long
doc.WriteProtection.SetPassword("docpassword123");
Assert.IsTrue(doc.WriteProtection.IsWriteProtected);

Assert.IsFalse(doc.WriteProtection.ValidatePassword("wrongpassword"));

DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("We can still edit the document at this stage.");

// Save the document
// Without the password, we can only read this document in Microsoft Word
// With the password, we can read and write
doc.Save(ArtifactsDir + "Document.WriteProtection.docx");

// Re-open our document
Document docProtected = new Document(ArtifactsDir + "Document.WriteProtection.docx");
DocumentBuilder docProtectedBuilder = new DocumentBuilder(docProtected);
docProtectedBuilder.MoveToDocumentEnd();

// We can programmatically edit this document without using our password
Assert.IsTrue(docProtected.WriteProtection.IsWriteProtected);
docProtectedBuilder.Writeln("Writing text in a protected document.");

// We will still need the password if we want to open this one with Word
docProtected.Save(ArtifactsDir + "Document.WriteProtectionEditedAfter.docx");

See Also

WriteProtection Class | Aspose.Words.Settings Namespace


ZoomType Enumeration

Possible values for how large or small the document appears on the screen in Microsoft Word.

[Visual Basic]
Public Enum ZoomType
[C#]
public enum ZoomType

Remarks

Members

Member Name | Description | Value
Custom | Zoom percentage is set explicitly. It is not recalculated automatically when control size changes. | 0
None | Indicates to use the explicit zoom percentage. Same as Custom. | 0
FullPage | Zoom percentage is automatically recalculated to fit one full page. | 1
PageWidth | Zoom percentage is automatically recalculated to fit page width. | 2
TextFit | Zoom percentage is automatically recalculated to fit text. | 3

Requirements

Namespace: Aspose.Words.Settings

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Settings Namespace | ViewOptions | ZoomType


Aspose.Words.Shaping

Aspose.Words

Aspose.Words.Shaping Namespace

The Aspose.Words.Shaping namespace contains classes to provide support for OpenType features using external text shaping engines.

Namespace hierarchy

Classes

Class | Description
BasicTextShaperCache | Implements basic cache for ITextShaper instances. This class is thread-safe.
Cluster | Encapsulates code points and glyphs composing a grapheme.
Glyph | Represents a glyph

Interfaces

Interface | Description
ITextShaper | Provides methods for text shaping.
ITextShaperFactory | An interface of a factory for constructing ITextShaper implementations.

Enumerations

Enumeration | Description
Direction | Text direction.
FontFeature | Features provide information about how glyphs are used in a font to render a script. https://docs.microsoft.com/en-us/typography/opentype/spec/featuretags
Script | Unicode Character Database property: Script (sc).


BasicTextShaperCache Class

Implements basic cache for ITextShaper instances. This class is thread-safe.

For a list of all members of this type, see BasicTextShaperCache Members.

System.Object
Aspose.Words.Shaping.BasicTextShaperCache

[Visual Basic]
Public Class BasicTextShaperCache
Implements ITextShaperFactory, IDisposable
[C#]
public class BasicTextShaperCache : ITextShaperFactory, IDisposable

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

BasicTextShaperCache Members | Aspose.Words.Shaping Namespace


BasicTextShaperCache Members

BasicTextShaperCache overview

Public Instance Constructors

BasicTextShaperCache Constructor Wraps factory and caches GetTextShaper results.

Public Instance Methods

Dispose

See Also

BasicTextShaperCache Class | Aspose.Words.Shaping Namespace


BasicTextShaperCache Constructor

Wraps factory and caches GetTextShaper results.

[Visual Basic]
Public Sub New( _
ByVal factory As ITextShaperFactory _
)
[C#]
public BasicTextShaperCache(
ITextShaperFactory factory
);

See Also

BasicTextShaperCache Class | Aspose.Words.Shaping Namespace


BasicTextShaperCache Methods

The methods of the BasicTextShaperCache class are listed below. For a complete list of BasicTextShaperCache class members, see the BasicTextShaperCache Members topic.

Public Instance Methods

Dispose

See Also

BasicTextShaperCache Class | Aspose.Words.Shaping Namespace


BasicTextShaperCache.Dispose Method

[Visual Basic]
NotOverridable Public Sub Dispose() _
Implements IDisposable.Dispose
[C#]
public void Dispose();

Implements

IDisposable.Dispose

See Also

BasicTextShaperCache Class | Aspose.Words.Shaping Namespace


Cluster Class

Encapsulates code points and glyphs composing a grapheme.

For a list of all members of this type, see Cluster Members.

System.Object
Aspose.Words.Shaping.Cluster

[Visual Basic]
Public Class Cluster
[C#]
public class Cluster

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Cluster Members | Aspose.Words.Shaping Namespace


Cluster Members

Cluster overview

Public Static (Shared) Methods

GetString Creates String using codepoints from the specified clusters.

Public Instance Constructors

Cluster Constructor

Public Instance Properties

Codepoints | Gets codepoints of the cluster.
Glyphs | Gets glyphs of the cluster.

Public Instance Methods

DeepClone | Returns a deep clone of this instance.
GetWidth | Returns width of the cluster.

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Cluster Constructor

[Visual Basic]
Public Sub New( _
ByVal codepoints As Integer(), _
ByVal glyphs As Glyph() _
)
[C#]
public Cluster(
int[] codepoints,
Glyph[] glyphs
);

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Cluster Properties

The properties of the Cluster class are listed below. For a complete list of Cluster class members, see the Cluster Members topic.

Public Instance Properties

Codepoints | Gets codepoints of the cluster.
Glyphs | Gets glyphs of the cluster.

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Codepoints Property

Aspose.Words

Cluster.Codepoints Property

Gets codepoints of the cluster.

[Visual Basic]
Public ReadOnly Property Codepoints As Integer()
[C#]
public int[] Codepoints {get;}

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Glyphs Property

Aspose.Words

Cluster.Glyphs Property

Gets glyphs of the cluster.

[Visual Basic]
Public ReadOnly Property Glyphs As Glyph()
[C#]
public Glyph[] Glyphs {get;}

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Cluster Methods

The methods of the Cluster class are listed below. For a complete list of Cluster class members, see the Cluster Members topic.

Public Static (Shared) Methods

GetString Creates String using codepoints from the specified clusters.

Public Instance Methods

DeepClone | Returns a deep clone of this instance.
GetWidth | Returns width of the cluster.

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Cluster.DeepClone Method

Returns a deep clone of this instance.

[Visual Basic]
Public Function DeepClone() As Cluster
[C#]
public Cluster DeepClone();

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Cluster.GetString Method

Creates String using codepoints from the specified clusters.

[Visual Basic]
Public Shared Function GetString( _
ByVal clusters As Cluster() _
) As String
[C#]
public static string GetString(
Cluster[] clusters
);

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Cluster.GetWidth Method

Returns width of the cluster.

[Visual Basic]
Public Function GetWidth( _
ByVal em As Integer, _
ByVal fontSize As Single _
) As Single
[C#]
public float GetWidth(
int em,
float fontSize
);

See Also

Cluster Class | Aspose.Words.Shaping Namespace


Direction Enumeration

Text direction.

[Visual Basic]
Public Enum Direction
[C#]
public enum Direction

Members

Member Name | Description | Value
Default | Default value, same as LTR. | 0
LTR | Left-to-right writing direction. | 0
RTL | Right-to-left writing direction. | 1
TTB | Top-to-bottom writing direction. | 2
BTT | Bottom-to-top writing direction. | 3

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Shaping Namespace


FontFeature Enumeration

Features provide information about how glyphs are used in a font to render a script. https://docs.microsoft.com/en-us/typography/opentype/spec/featuretags

[Visual Basic]
Public Enum FontFeature
[C#]
public enum FontFeature

Members

Member Name | Description | Value
GlyphCompositionDecomposition | To minimize the number of glyph alternates, it is sometimes desirable to decompose the default glyph for a character into two or more glyphs. Additionally, it may be preferable to compose default glyphs for two or more characters into a single glyph for better glyph processing. This feature permits such composition/decomposition. https://docs.microsoft.com/en-us/typography/opentype/spec/features_ae#ccmp Equivalent OpenType tag: 'ccmp' | 1667460464
StandardLigatures | Replaces a sequence of glyphs with a single glyph which is preferred for typographic purposes. This feature covers the ligatures which the designer/manufacturer judges should be used in normal conditions. Equivalent OpenType tag: 'liga' https://docs.microsoft.com/en-us/typography/opentype/spec/features_ko#liga | 1818847073
RequiredLigatures | Replaces a sequence of glyphs with a single glyph which is preferred for typographic purposes. This feature covers those ligatures, which the script determines as required to be used in normal conditions. This feature is important for some scripts to ensure correct glyph formation. https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#rlig Equivalent OpenType tag: 'rlig' | 1919707495
ContextualLigatures | Replaces a sequence of glyphs with a single glyph which is preferred for typographic purposes. Unlike other ligature features, 'clig' specifies the context in which the ligature is recommended. This capability is important in some script designs and for swash ligatures. https://docs.microsoft.com/en-us/typography/opentype/spec/features_ae#clig Equivalent OpenType tag: 'clig' | 1668049255
DiscretionaryLigatures | Replaces a sequence of glyphs with a single glyph which is preferred for typographic purposes. This feature covers those ligatures which may be used for special effect, at the user’s preference. https://docs.microsoft.com/en-us/typography/opentype/spec/features_ae#dlig Equivalent OpenType tag: 'dlig' | 1684826471
HistoricalLigatures | Some ligatures were in common use in the past, but appear anachronistic today. Some fonts include the historical forms as alternates, so they can be used for a "period" effect. This feature replaces the default (current) forms with the historical alternates. https://docs.microsoft.com/en-us/typography/opentype/spec/features_fj#hlig Equivalent OpenType tag: 'hlig' | 1751935335
Kerning | Adjusts amount of space between glyphs, generally to provide optically consistent spacing between glyphs. Although a well-designed typeface has consistent inter-glyph spacing overall, some glyph combinations require adjustment for improved legibility. Besides standard adjustment in the horizontal direction, this feature can supply size-dependent kerning data via device tables, "cross-stream" kerning in the Y text direction, and adjustment of glyph placement independent of the advance adjustment. Note that this feature may apply to runs of more than two glyphs, and would not be used in monospaced fonts. Also note that this feature does not apply to text set vertically. https://docs.microsoft.com/en-us/typography/opentype/spec/features_ko#kern Equivalent OpenType tag: 'kern' | 1801810542

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Shaping Namespace


Glyph Class

Represents a glyph

For a list of all members of this type, see Glyph Members.

System.Object
Aspose.Words.Shaping.Glyph

[Visual Basic]
Public Class Glyph
[C#]
public class Glyph

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Glyph Members | Aspose.Words.Shaping Namespace


Glyph Members

Glyph overview

Public Instance Constructors

Glyph Constructor Initializes new instance of this class.

Public Instance Properties

Advance | Advance width indicating placement for the subsequent glyph.
AdvanceOffset | Horizontal (x) offset relative to glyph position. Mostly used to attach marks (like diacritics) to base characters.
AscenderOffset | Vertical (y) offset relative to glyph position. Mostly used to attach marks (like diacritics) to base characters.
GlyphIndex | Index of the glyph (GID) in the physical font.

Public Instance Methods

Clone Returns a clone of this instance.

See Also

Glyph Class | Aspose.Words.Shaping Namespace


Glyph Constructor

Initializes new instance of this class.

[Visual Basic]
Public Sub New( _
ByVal glyphIndex As Integer, _
ByVal advance As Short, _
ByVal advanceOffset As Short, _
ByVal ascenderOffset As Short _
)
[C#]
public Glyph(
int glyphIndex,
short advance,
short advanceOffset,
short ascenderOffset
);

Parameters

glyphIndex
Glyph index.
advance
Advance metric of the glyph.
advanceOffset
Horizontal (x) offset.
ascenderOffset
Vertical (y) offset.

See Also

Glyph Class | Aspose.Words.Shaping Namespace


Glyph Properties

The properties of the Glyph class are listed below. For a complete list of Glyph class members, see the Glyph Members topic.

Public Instance Properties

Advance | Advance width indicating placement for the subsequent glyph.
AdvanceOffset | Horizontal (x) offset relative to glyph position. Mostly used to attach marks (like diacritics) to base characters.
AscenderOffset | Vertical (y) offset relative to glyph position. Mostly used to attach marks (like diacritics) to base characters.
GlyphIndex | Index of the glyph (GID) in the physical font.

See Also

Glyph Class | Aspose.Words.Shaping Namespace


Advance Property

Aspose.Words

Glyph.Advance Property

Advance width indicating placement for the subsequent glyph.

[Visual Basic]
Public Property Advance As Short
[C#]
public short Advance {get; set;}

See Also

Glyph Class | Aspose.Words.Shaping Namespace


AdvanceOffset Property

Aspose.Words

Glyph.AdvanceOffset Property

Horizontal (x) offset relative to glyph position. Mostly used to attach marks (like diacritics) to base characters.

[Visual Basic]
Public ReadOnly Property AdvanceOffset As Short
[C#]
public short AdvanceOffset {get;}

See Also

Glyph Class | Aspose.Words.Shaping Namespace


AscenderOffset Property

Aspose.Words

Glyph.AscenderOffset Property

Vertical (y) offset relative to glyph position. Mostly used to attach marks (like diacritics) to base characters.

[Visual Basic]
Public ReadOnly Property AscenderOffset As Short
[C#]
public short AscenderOffset {get;}

See Also

Glyph Class | Aspose.Words.Shaping Namespace


GlyphIndex Property

Aspose.Words

Glyph.GlyphIndex Property

Index of the glyph (GID) in the physical font.

[Visual Basic]
Public ReadOnly Property GlyphIndex As Integer
[C#]
public int GlyphIndex {get;}

See Also

Glyph Class | Aspose.Words.Shaping Namespace


Glyph Methods

The methods of the Glyph class are listed below. For a complete list of Glyph class members, see the Glyph Members topic.

Public Instance Methods

Clone Returns a clone of this instance.

See Also

Glyph Class | Aspose.Words.Shaping Namespace


Glyph.Clone Method

Returns a clone of this instance.

[Visual Basic]
Public Function Clone() As Glyph
[C#]
public Glyph Clone();

See Also

Glyph Class | Aspose.Words.Shaping Namespace


ITextShaper Interface

Provides methods for text shaping.

For a list of all members of this type, see ITextShaper Members.

[Visual Basic]
Public Interface ITextShaper
Implements IDisposable
[C#]
public interface ITextShaper : IDisposable

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ITextShaper Members | Aspose.Words.Shaping Namespace


ITextShaper Members

ITextShaper overview

Public Instance Methods

ShapeText Returns Cluster objects generated from a sequence of text fragments. Length of the returned array is equal to length of runs. If run at an index has corresponding clusters then result at the same index will have them recorded.

See Also

ITextShaper Interface | Aspose.Words.Shaping Namespace


ITextShaper Methods

The methods of the ITextShaper interface are listed below. For a complete list of ITextShaper interface members, see the ITextShaper Members topic.

Public Instance Methods

ShapeText Returns Cluster objects generated from a sequence of text fragments. Length of the returned array is equal to length of runs. If run at an index has corresponding clusters then result at the same index will have them recorded.

See Also

ITextShaper Interface | Aspose.Words.Shaping Namespace


ITextShaper.ShapeText Method

Returns Cluster objects generated from a sequence of text fragments. Length of the returned array is equal to length of runs. If run at an index has corresponding clusters then result at the same index will have them recorded.

[Visual Basic]
Function ShapeText( _
ByVal runs As String(), _
ByVal direction As Direction, _
ByVal script As Script, _
ParamArray fontFeatures As FontFeature() _
) As Cluster()[)
[C#]
Cluster[][] ShapeText(
string[] runs,
Direction direction,
Script script,
params FontFeature[] fontFeatures
);

Parameters

runs
A sequence of text fragments
direction
A direction of text
script
A script
fontFeatures
A set of features to consider

See Also

ITextShaper Interface | Aspose.Words.Shaping Namespace


ITextShaperFactory Interface

An interface of a factory for constructing ITextShaper implementations.

For a list of all members of this type, see ITextShaperFactory Members.

[Visual Basic]
Public Interface ITextShaperFactory
[C#]
public interface ITextShaperFactory

Types that implement ITextShaperFactory

Type | Description
BasicTextShaperCache | Implements basic cache for ITextShaper instances. This class is thread-safe.

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ITextShaperFactory Members | Aspose.Words.Shaping Namespace


ITextShaperFactory Members

ITextShaperFactory overview

Public Instance Methods

GetTextShaper Returns new instance of a text shaper for the font specified by fontPath and faceIndex.

See Also

ITextShaperFactory Interface | Aspose.Words.Shaping Namespace


ITextShaperFactory Methods

The methods of the ITextShaperFactory interface are listed below. For a complete list of ITextShaperFactory interface members, see the ITextShaperFactory Members topic.

Public Instance Methods

GetTextShaper Returns new instance of a text shaper for the font specified by fontPath and faceIndex.

See Also

ITextShaperFactory Interface | Aspose.Words.Shaping Namespace


ITextShaperFactory.GetTextShaper Method

Returns new instance of a text shaper for the font specified by fontPath and faceIndex.

[Visual Basic]
Function GetTextShaper( _
ByVal fontPath As String, _
ByVal faceIndex As Integer _
) As ITextShaper
[C#]
ITextShaper GetTextShaper(
string fontPath,
int faceIndex
);

Parameters

fontPath
An absolute path to the font file.
faceIndex
An index of the font face in the TrueType font collection, or 0 if specified font file is not TrueType font collection.

See Also

ITextShaperFactory Interface | Aspose.Words.Shaping Namespace


Script Enumeration

Unicode Character Database property: Script (sc).

[Visual Basic]
Public Enum Script
[C#]
public enum Script

Remarks

http://www.unicode.org/reports/tr24/tr24-29.html https://www.unicode.org/iso15924/ http://goo.gl/x9ilM

Members

Member Name | Description | Value
Default | Default script | 0
Arabic | Arabic script | 1098015074
Tamil | Tamil script | 1415671148
Cyrillic | Cyrillic script | 1132032620
Hebrew | Hebrew script | 1214603890

Requirements

Namespace: Aspose.Words.Shaping

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Shaping Namespace


Aspose.Words.Tables

Aspose.Words

Aspose.Words.Tables Namespace

The Aspose.Words.Tables namespace contains classes that represent tables, rows, cells and their formatting.

Namespace hierarchy

Classes

Class | Description
Cell | Represents a table cell.
CellCollection | Provides typed access to a collection of Cell nodes.
CellFormat | Represents all formatting for a table cell.
PreferredWidth | Represents a value and its unit of measure that is used to specify the preferred width of a table or a cell.
Row | Represents a table row.
RowCollection | Provides typed access to a collection of Row nodes.
RowFormat | Represents all formatting for a table row.
Table | Represents a table in a Word document.
TableCollection | Provides typed access to a collection of Table nodes.

Enumerations

Enumeration | Description
AutoFitBehavior | Determines how Aspose.Words resizes the table when you invoke the AutoFit method.
CellMerge | Specifies how a cell in a table is merged with other cells.
CellVerticalAlignment | Specifies vertical justification of text inside a table cell.
PreferredWidthType | Specifies the unit of measurement for the preferred width of a table or cell.
TableAlignment | Specifies alignment for an inline table.
TableStyleOptions | Specifies how table style is applied to a table.
TextWrapping | Specifies how text is wrapped around the table.


AutoFitBehavior Enumeration

Determines how Aspose.Words resizes the table when you invoke the AutoFit method.

[Visual Basic]
Public Enum AutoFitBehavior
[C#]
public enum AutoFitBehavior

Example

Shows how to build a formatted table that contains 2 rows and 2 columns.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to build a new table with a table style applied.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions =
    TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Continue with building the table as normal.
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.SetTableStyle.docx");

Members

Member Name Description Value
AutoFitToContents

Aspose.Words enables the AutoFit option, removes the preferred width from the table and all cells and then updates the table layout.

In the resulting table, cell widths are updated to fit the table contents. Most likely, the table will shrink.

0
AutoFitToWindow

When you use this value, Aspose.Words enables the AutoFit option, sets the preferred width for the table to 100%, removes preferred widths from all cells and then updates the table layout.

As a result, the table occupies all available width and the cell widths are updated to fit table contents.

1
FixedColumnWidths

Aspose.Words disables the AutoFit option and removes the preferred with from the table.

The widths of the cells remain as they are specified by their Width properties.

2

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace


Cell Class

Represents a table cell.

For a list of all members of this type, see Cell Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Tables.Cell

[Visual Basic]
Public Class Cell
Inherits CompositeNode
[C#]
public class Cell : CompositeNode

Remarks

Cell can only be a child of a Row.

Cell can contain block-level nodes Paragraph and Table.

A minimal valid cell needs to have at least one Paragraph.

Example

Retrieves the index of a cell in a row.

[C#]

int cellIndex = row.IndexOf(cell);
Shows how to replace all instances of String of text in a table and cell.
[C#]

Document doc = new Document(MyDir + "Table.SimpleTable.doc");

// Get the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

FindReplaceOptions options = new FindReplaceOptions();
options.MatchCase = true;
options.FindWholeWordsOnly = true;

// Replace any instances of our String in the entire table.
table.Range.Replace("Carrots", "Eggs", options);
// Replace any instances of our String in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", options);

doc.Save(ArtifactsDir + "Table.ReplaceCellText.doc");
Shows how to iterate through all tables in the document and display the content from each cell.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");
Shows how to build a nested table without using DocumentBuilder.
[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Cell Members | Aspose.Words.Tables Namespace


Cell Members

Cell overview

Public Instance Constructors

Cell Constructor Initializes a new instance of the Cell class.

Public Instance Properties

CellFormat | Provides access to the formatting properties of the cell.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph among the immediate children.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsFirstCell | True if this is the first cell inside a row; false otherwise.
IsLastCell | True if this is the last cell inside a row; false otherwise.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph among the immediate children.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Cell.
Paragraphs | Gets a collection of paragraphs that are immediate children of the cell.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentRow | Returns the parent row of the cell.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Tables | Gets a collection of tables that are immediate children of the cell.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum | If the last child is not a paragraph, creates and appends one empty paragraph.
FetchCellAttr | SPEED for export to formats that require fully calculated values. Gets the fully calculated value of the attribute. For example, the border could be defined on the cell or inherited from the table or defaults. Note that if the border is inherited, this will return the parent value, so don't modify it.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Cell Class | Aspose.Words.Tables Namespace


Cell Constructor

Initializes a new instance of the Cell class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Cell(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Cell is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Cell to the document use InsertAfter or InsertBefore on the row where you want the cell inserted.

Example

Shows how to build a nested table without using DocumentBuilder.

[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

See Also

Cell Class | Aspose.Words.Tables Namespace


Cell Properties

The properties of the Cell class are listed below. For a complete list of Cell class members, see the Cell Members topic.

Public Instance Properties

CellFormat | Provides access to the formatting properties of the cell.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstParagraph | Gets the first paragraph among the immediate children.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsFirstCell | True if this is the first cell inside a row; false otherwise.
IsLastCell | True if this is the last cell inside a row; false otherwise.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastParagraph | Gets the last paragraph among the immediate children.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Cell.
Paragraphs | Gets a collection of paragraphs that are immediate children of the cell.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentRow | Returns the parent row of the cell.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
Tables | Gets a collection of tables that are immediate children of the cell.

See Also

Cell Class | Aspose.Words.Tables Namespace


CellFormat Property

Aspose.Words

Cell.CellFormat Property

Provides access to the formatting properties of the cell.

[Visual Basic]
Public ReadOnly Property CellFormat As CellFormat
[C#]
public CellFormat CellFormat {get;}

Example

Shows how to modify formatting of a table cell.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Retrieve the first cell in the table.
Cell firstCell = table.FirstRow.FirstCell;

// Modify some row level properties.
firstCell.CellFormat.Width = 30; // in points
firstCell.CellFormat.Orientation = TextOrientation.Downward;
firstCell.CellFormat.Shading.ForegroundPatternColor = Color.LightGreen;
Shows how to combine the rows from two tables into one.
[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table) doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table) doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(ArtifactsDir + "Table.CombineTables.doc");
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

See Also

Cell Class | Aspose.Words.Tables Namespace


FirstParagraph Property

Aspose.Words

Cell.FirstParagraph Property

Gets the first paragraph among the immediate children.

[Visual Basic]
Public ReadOnly Property FirstParagraph As Paragraph
[C#]
public Paragraph FirstParagraph {get;}

Example

Shows how to insert a nested table using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Build the outer table.
Cell cell = builder.InsertCell();
builder.Writeln("Outer Table Cell 1");

builder.InsertCell();
builder.Writeln("Outer Table Cell 2");

// This call is important in order to create a nested table within the first table
// Without this call the cells inserted below will be appended to the outer table.
builder.EndTable();

// Move to the first cell of the outer table.
builder.MoveTo(cell.FirstParagraph);

// Build the inner table.
builder.InsertCell();
builder.Writeln("Inner Table Cell 1");
builder.InsertCell();
builder.Writeln("Inner Table Cell 2");

builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.InsertNestedTable.doc");
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

See Also

Cell Class | Aspose.Words.Tables Namespace


IsFirstCell Property

Aspose.Words

Cell.IsFirstCell Property

True if this is the first cell inside a row; false otherwise.

[Visual Basic]
Public ReadOnly Property IsFirstCell As Boolean
[C#]
public bool IsFirstCell {get;}

See Also

Cell Class | Aspose.Words.Tables Namespace


IsLastCell Property

Aspose.Words

Cell.IsLastCell Property

True if this is the last cell inside a row; false otherwise.

[Visual Basic]
Public ReadOnly Property IsLastCell As Boolean
[C#]
public bool IsLastCell {get;}

See Also

Cell Class | Aspose.Words.Tables Namespace


LastParagraph Property

Aspose.Words

Cell.LastParagraph Property

Gets the last paragraph among the immediate children.

[Visual Basic]
Public ReadOnly Property LastParagraph As Paragraph
[C#]
public Paragraph LastParagraph {get;}

See Also

Cell Class | Aspose.Words.Tables Namespace


NodeType Property

Aspose.Words

Cell.NodeType Property

Returns NodeType.Cell.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Cell Class | Aspose.Words.Tables Namespace


Paragraphs Property

Aspose.Words

Cell.Paragraphs Property

Gets a collection of paragraphs that are immediate children of the cell.

[Visual Basic]
Public ReadOnly Property Paragraphs As ParagraphCollection
[C#]
public ParagraphCollection Paragraphs {get;}

Example

Shows how to set a table to stay together on the same page.

[C#]

// To keep a table from breaking across a page we need to enable KeepWithNext
// for every paragraph in the table except for the last paragraphs in the last
// row of the table.
foreach (Cell cell in table.GetChildNodes(NodeType.Cell, true).OfType<Cell>())
foreach (Paragraph para in cell.Paragraphs.OfType<Paragraph>())
    if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
        para.ParagraphFormat.KeepWithNext = true;

See Also

Cell Class | Aspose.Words.Tables Namespace


ParentRow Property

Aspose.Words

Cell.ParentRow Property

Returns the parent row of the cell.

[Visual Basic]
Public ReadOnly Property ParentRow As Row
[C#]
public Row ParentRow {get;}

Remarks

Equivalent to (Row)FirstNonMarkupParentNode.

Example

Shows how to set a table to stay together on the same page.

[C#]

// To keep a table from breaking across a page we need to enable KeepWithNext
// for every paragraph in the table except for the last paragraphs in the last
// row of the table.
foreach (Cell cell in table.GetChildNodes(NodeType.Cell, true).OfType<Cell>())
foreach (Paragraph para in cell.Paragraphs.OfType<Paragraph>())
    if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
        para.ParagraphFormat.KeepWithNext = true;

See Also

Cell Class | Aspose.Words.Tables Namespace


Tables Property

Aspose.Words

Cell.Tables Property

Gets a collection of tables that are immediate children of the cell.

[Visual Basic]
Public ReadOnly Property Tables As TableCollection
[C#]
public TableCollection Tables {get;}

Example

Shows how to find out if a table contains another table or if the table itself is nested inside another table.

[C#]

Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true).OfType<Table>())
    {
        // First lets find if any cells in the table have tables themselves as children.
        int count = GetChildTableCount(table);
        Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

        // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
        int tableDepth = GetNestedDepthOfTable(table);

        if (tableDepth > 0)
            Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex,
                tableDepth);
        else
            Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);

        tableIndex++;
    }
}

/// <summary>
/// Calculates what level a table is nested inside other tables.
/// <returns>
/// An integer containing the level the table is nested at.
/// 0 = Table is not nested inside any other table
/// 1 = Table is nested within one parent table
/// 2 = Table is nested within two parent tables etc..</returns>
/// </summary>
private static int GetNestedDepthOfTable(Table table)
{
    int depth = 0;

    NodeType type = table.NodeType;
    // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Node parent = table.GetAncestor(type);

    while (parent != null)
    {
        // Every time we find a table a level up we increase the depth counter and then try to find an
        // ancestor of type table from the parent.
        depth++;
        parent = parent.GetAncestor(type);
    }

    return depth;
}

/// <summary>
/// Determines if a table contains any immediate child table within its cells.
/// Does not recursively traverse through those tables to check for further tables.
/// <returns>Returns true if at least one child cell contains a table.
/// Returns false if no cells in the table contains a table.</returns>
/// </summary>
private static int GetChildTableCount(Table table)
{
    int tableCount = 0;
    // Iterate through all child rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells.OfType<Cell>())
        {
            // Retrieve the collection of child tables of this cell
            TableCollection childTables = Cell.Tables;

            // If this cell has a table as a child then return true
            if (childTables.Count > 0)
                tableCount++;
        }
    }

    // No cell contains a table
    return tableCount;
}

See Also

Cell Class | Aspose.Words.Tables Namespace


Cell Methods

The methods of the Cell class are listed below. For a complete list of Cell class members, see the Cell Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum | If the last child is not a paragraph, creates and appends one empty paragraph.
FetchCellAttr | SPEED for export to formats that require fully calculated values. Gets the fully calculated value of the attribute. For example, the border could be defined on the cell or inherited from the table or defaults. Note that if the border is inherited, this will return the parent value, so don't modify it.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Cell Class | Aspose.Words.Tables Namespace


Cell.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitCellStart, then calls Accept for all child nodes of the section and calls DocumentVisitor.VisitCellEnd at the end.

See Also

Cell Class | Aspose.Words.Tables Namespace


Cell.EnsureMinimum Method

If the last child is not a paragraph, creates and appends one empty paragraph.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Shows how to ensure a cell node is valid.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Gets the first cell in the document.
Cell cell = (Cell) doc.GetChild(NodeType.Cell, 0, true);

// Ensure the cell is valid (the last child is a paragraph).
cell.EnsureMinimum();

See Also

Cell Class | Aspose.Words.Tables Namespace


Cell.FetchCellAttr Method

SPEED for export to formats that require fully calculated values. Gets the fully calculated value of the attribute. For example, the border could be defined on the cell or inherited from the table or defaults. Note that if the border is inherited, this will return the parent value, so don't modify it.

[Visual Basic]
NotOverridable Public Function FetchCellAttr( _
ByVal key As Integer _
) As Object
[C#]
public object FetchCellAttr(
int key
);

See Also

Cell Class | Aspose.Words.Tables Namespace


CellCollection Class

Provides typed access to a collection of Cell nodes.

For a list of all members of this type, see CellCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.Tables.CellCollection

[Visual Basic]
Public Class CellCollection
Inherits NodeCollection
[C#]
public class CellCollection : NodeCollection

Example

Shows how to iterate through all tables in the document and display the content from each cell.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CellCollection Members | Aspose.Words.Tables Namespace


CellCollection Members

CellCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Cell at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all cells from the collection to a new array of cells.

See Also

CellCollection Class | Aspose.Words.Tables Namespace


CellCollection Properties

The properties of the CellCollection class are listed below. For a complete list of CellCollection class members, see the CellCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Cell at the given index.

See Also

CellCollection Class | Aspose.Words.Tables Namespace


Item Property

Aspose.Words

CellCollection.Item Property

Retrieves a Cell at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Cell
[C#]
new public Cell this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

CellCollection Class | Aspose.Words.Tables Namespace


CellCollection Methods

The methods of the CellCollection class are listed below. For a complete list of CellCollection class members, see the CellCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all cells from the collection to a new array of cells.

See Also

CellCollection Class | Aspose.Words.Tables Namespace


CellCollection.ToArray Method

Copies all cells from the collection to a new array of cells.

[Visual Basic]
Public Function ToArray() As Cell()
[C#]
new public Cell[] ToArray();

Return Value

An array of cells.

See Also

CellCollection Class | Aspose.Words.Tables Namespace


CellFormat Class

Represents all formatting for a table cell.

For a list of all members of this type, see CellFormat Members.

System.Object
Aspose.Words.Tables.CellFormat

[Visual Basic]
Public Class CellFormat
[C#]
public class CellFormat

Example

Shows how to modify formatting of a table cell.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Retrieve the first cell in the table.
Cell firstCell = table.FirstRow.FirstCell;

// Modify some row level properties.
firstCell.CellFormat.Width = 30; // in points
firstCell.CellFormat.Orientation = TextOrientation.Downward;
firstCell.CellFormat.Shading.ForegroundPatternColor = Color.LightGreen;
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

CellFormat Members | Aspose.Words.Tables Namespace


CellFormat Members

CellFormat overview

Public Instance Properties

Borders | Gets collection of borders of the cell.
BottomPadding | Returns or sets the amount of space (in points) to add below the contents of cell.
FitText | If true, fits text in the cell, compressing each paragraph to the width of the cell.
HorizontalMerge | Specifies how the cell is merged horizontally with other cells in the row.
LeftPadding | Returns or sets the amount of space (in points) to add to the left of the contents of cell.
Orientation | Returns or sets the orientation of text in a table cell.
PreferredWidth | Returns or sets the preferred width of the cell.
RightPadding | Returns or sets the amount of space (in points) to add to the right of the contents of cell.
Shading | Returns a Shading object that refers to the shading formatting for the cell.
TopPadding | Returns or sets the amount of space (in points) to add above the contents of cell.
VerticalAlignment | Returns or sets the vertical alignment of text in the cell.
VerticalMerge | Specifies how the cell is merged with other cells vertically.
Width | Gets the width of the cell in points.
WrapText | If true, wrap text for the cell.

Public Instance Methods

ClearFormatting | Resets to default cell formatting. Does not change the width of the cell.
SetPaddings | Sets the amount of space (in points) to add to the left/top/right/bottom of the contents of cell.

See Also

CellFormat Class | Aspose.Words.Tables Namespace


CellFormat Properties

The properties of the CellFormat class are listed below. For a complete list of CellFormat class members, see the CellFormat Members topic.

Public Instance Properties

Borders | Gets collection of borders of the cell.
BottomPadding | Returns or sets the amount of space (in points) to add below the contents of cell.
FitText | If true, fits text in the cell, compressing each paragraph to the width of the cell.
HorizontalMerge | Specifies how the cell is merged horizontally with other cells in the row.
LeftPadding | Returns or sets the amount of space (in points) to add to the left of the contents of cell.
Orientation | Returns or sets the orientation of text in a table cell.
PreferredWidth | Returns or sets the preferred width of the cell.
RightPadding | Returns or sets the amount of space (in points) to add to the right of the contents of cell.
Shading | Returns a Shading object that refers to the shading formatting for the cell.
TopPadding | Returns or sets the amount of space (in points) to add above the contents of cell.
VerticalAlignment | Returns or sets the vertical alignment of text in the cell.
VerticalMerge | Specifies how the cell is merged with other cells vertically.
Width | Gets the width of the cell in points.
WrapText | If true, wrap text for the cell.

See Also

CellFormat Class | Aspose.Words.Tables Namespace


Borders Property

Aspose.Words

CellFormat.Borders Property

Gets collection of borders of the cell.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

Example

Shows how to combine the rows from two tables into one.

[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table) doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table) doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(ArtifactsDir + "Table.CombineTables.doc");

See Also

CellFormat Class | Aspose.Words.Tables Namespace


BottomPadding Property

Aspose.Words

CellFormat.BottomPadding Property

Returns or sets the amount of space (in points) to add below the contents of cell.

[Visual Basic]
Public Property BottomPadding As Double
[C#]
public double BottomPadding {get; set;}

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();

See Also

CellFormat Class | Aspose.Words.Tables Namespace


FitText Property

Aspose.Words

CellFormat.FitText Property

If true, fits text in the cell, compressing each paragraph to the width of the cell.

[Visual Basic]
Public Property FitText As Boolean
[C#]
public bool FitText {get; set;}

See Also

CellFormat Class | Aspose.Words.Tables Namespace


HorizontalMerge Property

Aspose.Words

CellFormat.HorizontalMerge Property

Specifies how the cell is merged horizontally with other cells in the row.

[Visual Basic]
Public Property HorizontalMerge As CellMerge
[C#]
public CellMerge HorizontalMerge {get; set;}

Remarks

Example

Creates a table with two rows with cells in the first row horizontally merged.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
// This cell is merged to the previous and should be empty.
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write("Text in one cell.");

builder.InsertCell();
builder.Write("Text in another cell.");
builder.EndRow();
builder.EndTable();
Prints the horizontal and vertical merge type of a cell.
[C#]

public void CheckCellsMerged()
{
    Document doc = new Document(MyDir + "Table.MergedCells.doc");

    // Retrieve the first table in the document.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

    foreach (Row row in table.Rows.OfType<Row>())
    {
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

    Assert.AreEqual("The cell at R1, C1 is horizontally merged.",
}

public String PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    String cellLocation =
        $"R{cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1}, C{cell.ParentRow.IndexOf(cell) + 1}";

    if (isHorizontallyMerged && isVerticallyMerged)
        return $"The cell at {cellLocation} is both horizontally and vertically merged";
    else if (isHorizontallyMerged)
        return $"The cell at {cellLocation} is horizontally merged.";
    else if (isVerticallyMerged)
        return $"The cell at {cellLocation} is vertically merged";
    else
        return $"The cell at {cellLocation} is not merged";
}

See Also

CellFormat Class | Aspose.Words.Tables Namespace | VerticalMerge


LeftPadding Property

Aspose.Words

CellFormat.LeftPadding Property

Returns or sets the amount of space (in points) to add to the left of the contents of cell.

[Visual Basic]
Public Property LeftPadding As Double
[C#]
public double LeftPadding {get; set;}

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();

See Also

CellFormat Class | Aspose.Words.Tables Namespace


Orientation Property

Aspose.Words

CellFormat.Orientation Property

Returns or sets the orientation of text in a table cell.

[Visual Basic]
Public Property Orientation As TextOrientation
[C#]
public TextOrientation Orientation {get; set;}

Example

Shows how to build a formatted table that contains 2 rows and 2 columns.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

See Also

CellFormat Class | Aspose.Words.Tables Namespace


PreferredWidth Property

Aspose.Words

CellFormat.PreferredWidth Property

Returns or sets the preferred width of the cell.

[Visual Basic]
Public Property PreferredWidth As PreferredWidth
[C#]
public PreferredWidth PreferredWidth {get; set;}

Remarks

The preferred width (along with the table's Auto Fit option) determines how the actual width of the cell is calculated by the table layout algorithm. Table layout can be performed by Aspose.Words when it saves the document or by Microsoft Word when it displays the document.

The preferred width can be specified in points or in percent. The preferred width can also be specified as "auto", which means no preferred width is specified.

The default value is Auto.

Example

Shows how to set the different preferred width settings.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table row made up of three cells which have different preferred widths.
Table table = builder.StartTable();

// Insert an absolute sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightYellow;
builder.Writeln("Cell at 40 points width");

// Insert a relative (percent) sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(20);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
builder.Writeln("Cell at 20% width");

// Insert a auto sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.Auto;
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGreen;
builder.Writeln(
    "Cell automatically sized. The size of this cell is calculated from the table preferred width.");
builder.Writeln("In this case the cell will fill up the rest of the available space.");

doc.Save(ArtifactsDir + "Table.CellPreferredWidths.doc");

See Also

CellFormat Class | Aspose.Words.Tables Namespace | Width


RightPadding Property

Aspose.Words

CellFormat.RightPadding Property

Returns or sets the amount of space (in points) to add to the right of the contents of cell.

[Visual Basic]
Public Property RightPadding As Double
[C#]
public double RightPadding {get; set;}

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();

See Also

CellFormat Class | Aspose.Words.Tables Namespace


Shading Property

Aspose.Words

CellFormat.Shading Property

Returns a Shading object that refers to the shading formatting for the cell.

[Visual Basic]
Public ReadOnly Property Shading As Shading
[C#]
public Shading Shading {get;}

Example

Shows how to insert a table using the constructors of nodes.

[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

See Also

CellFormat Class | Aspose.Words.Tables Namespace


TopPadding Property

Aspose.Words

CellFormat.TopPadding Property

Returns or sets the amount of space (in points) to add above the contents of cell.

[Visual Basic]
Public Property TopPadding As Double
[C#]
public double TopPadding {get; set;}

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();

See Also

CellFormat Class | Aspose.Words.Tables Namespace


VerticalAlignment Property

Aspose.Words

CellFormat.VerticalAlignment Property

Returns or sets the vertical alignment of text in the cell.

[Visual Basic]
Public Property VerticalAlignment As CellVerticalAlignment
[C#]
public CellVerticalAlignment VerticalAlignment {get; set;}

See Also

CellFormat Class | Aspose.Words.Tables Namespace


VerticalMerge Property

Aspose.Words

CellFormat.VerticalMerge Property

Specifies how the cell is merged with other cells vertically.

[Visual Basic]
Public Property VerticalMerge As CellMerge
[C#]
public CellMerge VerticalMerge {get; set;}

Remarks

Cells can only be merged vertically if their left and right boundaries are identical.

When cells are vertically merged, the display areas of the merged cells are consolidated. The consolidated area is used to display the contents of the first vertically merged cell and all other vertically merged cells must be empty.

Example

Creates a table with two columns with cells merged vertically in the first column.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in one cell");
builder.EndRow();

builder.InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in another cell");
builder.EndRow();
builder.EndTable();
Prints the horizontal and vertical merge type of a cell.
[C#]

public void CheckCellsMerged()
{
    Document doc = new Document(MyDir + "Table.MergedCells.doc");

    // Retrieve the first table in the document.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

    foreach (Row row in table.Rows.OfType<Row>())
    {
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

    Assert.AreEqual("The cell at R1, C1 is horizontally merged.",
}

public String PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    String cellLocation =
        $"R{cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1}, C{cell.ParentRow.IndexOf(cell) + 1}";

    if (isHorizontallyMerged && isVerticallyMerged)
        return $"The cell at {cellLocation} is both horizontally and vertically merged";
    else if (isHorizontallyMerged)
        return $"The cell at {cellLocation} is horizontally merged.";
    else if (isVerticallyMerged)
        return $"The cell at {cellLocation} is vertically merged";
    else
        return $"The cell at {cellLocation} is not merged";
}

See Also

CellFormat Class | Aspose.Words.Tables Namespace | HorizontalMerge


Width Property

Aspose.Words

CellFormat.Width Property

Gets the width of the cell in points.

[Visual Basic]
Public Property Width As Double
[C#]
public double Width {get; set;}

Remarks

The width is calculated by Aspose.Words on document loading and saving. Currently, not every combination of table, cell and document properties is supported. The returned value may not be accurate for some documents. It may not exactly match the cell width as calculated by MS Word when the document is opened in MS Word.

Setting this property is not recommended. There is no guarantee that the cell will actually have the set width. The width may be adjusted to accommodate cell contents in an auto-fit table layout. Cells in other rows may have conflicting width settings. The table may be resized to fit into the container or to meet table width settings. Consider using PreferredWidth for setting the cell width. Setting this property sets PreferredWidth implicitly since version 15.8.

Example

Shows how to create a table that contains a single formatted cell.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
builder.InsertCell();

// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted cell.");

builder.EndRow();
builder.EndTable();

See Also

CellFormat Class | Aspose.Words.Tables Namespace | PreferredWidth


WrapText Property

Aspose.Words

CellFormat.WrapText Property

If true, wrap text for the cell.

[Visual Basic]
Public Property WrapText As Boolean
[C#]
public bool WrapText {get; set;}

See Also

CellFormat Class | Aspose.Words.Tables Namespace


CellFormat Methods

The methods of the CellFormat class are listed below. For a complete list of CellFormat class members, see the CellFormat Members topic.

Public Instance Methods

ClearFormatting | Resets to default cell formatting. Does not change the width of the cell.
SetPaddings | Sets the amount of space (in points) to add to the left/top/right/bottom of the contents of cell.

See Also

CellFormat Class | Aspose.Words.Tables Namespace


CellFormat.ClearFormatting Method

Resets to default cell formatting. Does not change the width of the cell.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

Example

Shows how to combine the rows from two tables into one.

[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table) doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table) doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(ArtifactsDir + "Table.CombineTables.doc");

See Also

CellFormat Class | Aspose.Words.Tables Namespace


CellFormat.SetPaddings Method

Sets the amount of space (in points) to add to the left/top/right/bottom of the contents of cell.

[Visual Basic]
Public Sub SetPaddings( _
ByVal leftPadding As Double, _
ByVal topPadding As Double, _
ByVal rightPadding As Double, _
ByVal bottomPadding As Double _
)
[C#]
public void SetPaddings(
double leftPadding,
double topPadding,
double rightPadding,
double bottomPadding
);

Example

Shows how to set paddings to a table cell.

[C#]

DocumentBuilder builder = new DocumentBuilder();

builder.StartTable();
builder.CellFormat.Width = 300;
builder.CellFormat.SetPaddings(5, 10, 40, 50);

builder.RowFormat.HeightRule = HeightRule.Exactly;
builder.RowFormat.Height = 50;

builder.InsertCell();
builder.Write("Row 1, Col 1");

See Also

CellFormat Class | Aspose.Words.Tables Namespace


CellMerge Enumeration

Specifies how a cell in a table is merged with other cells.

[Visual Basic]
Public Enum CellMerge
[C#]
public enum CellMerge

Example

Creates a table with two rows with cells in the first row horizontally merged.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
// This cell is merged to the previous and should be empty.
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write("Text in one cell.");

builder.InsertCell();
builder.Write("Text in another cell.");
builder.EndRow();
builder.EndTable();
Creates a table with two columns with cells merged vertically in the first column.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.Write("Text in merged cells.");

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in one cell");
builder.EndRow();

builder.InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in another cell");
builder.EndRow();
builder.EndTable();
Prints the horizontal and vertical merge type of a cell.
[C#]

public void CheckCellsMerged()
{
    Document doc = new Document(MyDir + "Table.MergedCells.doc");

    // Retrieve the first table in the document.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

    foreach (Row row in table.Rows.OfType<Row>())
    {
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

    Assert.AreEqual("The cell at R1, C1 is horizontally merged.",
}

public String PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    String cellLocation =
        $"R{cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1}, C{cell.ParentRow.IndexOf(cell) + 1}";

    if (isHorizontallyMerged && isVerticallyMerged)
        return $"The cell at {cellLocation} is both horizontally and vertically merged";
    else if (isHorizontallyMerged)
        return $"The cell at {cellLocation} is horizontally merged.";
    else if (isVerticallyMerged)
        return $"The cell at {cellLocation} is vertically merged";
    else
        return $"The cell at {cellLocation} is not merged";
}

Members

Member Name | Description | Value
None | The cell is not merged. | 0
First | The cell is the first cell in a range of merged cells. | 1
Previous | The cell is merged to the previous cell horizontally or vertically. | 2

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace


CellVerticalAlignment Enumeration

Specifies vertical justification of text inside a table cell.

[Visual Basic]
Public Enum CellVerticalAlignment
[C#]
public enum CellVerticalAlignment

Example

Shows how to build a formatted table that contains 2 rows and 2 columns.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();

Members

Member Name | Description | Value
Top | Text is aligned at the top of a cell. | 0
Center | Text is aligned in the middle of a cell. | 1
Bottom | Text is aligned at the bottom of the cell. | 2

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace


PreferredWidth Class

Represents a value and its unit of measure that is used to specify the preferred width of a table or a cell.

For a list of all members of this type, see PreferredWidth Members.

System.Object
Aspose.Words.Tables.PreferredWidth

[Visual Basic]
NotInheritable Public Class PreferredWidth
[C#]
public sealed class PreferredWidth

Remarks

Preferred width can be specified as a percentage, number of points or a special "none/auto" value.

The instances of this class are immutable.

Example

Shows how to set a table to auto fit to 50% of the page width.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table with a width that takes up half the page width.
Table table = builder.StartTable();

// Insert a few cells
builder.InsertCell();
table.PreferredWidth = PreferredWidth.FromPercent(50);
builder.Writeln("Cell #1");

builder.InsertCell();
builder.Writeln("Cell #2");

builder.InsertCell();
builder.Writeln("Cell #3");

doc.Save(ArtifactsDir + "Table.PreferredWidth.doc");
Shows how to set the different preferred width settings.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table row made up of three cells which have different preferred widths.
Table table = builder.StartTable();

// Insert an absolute sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightYellow;
builder.Writeln("Cell at 40 points width");

// Insert a relative (percent) sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(20);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
builder.Writeln("Cell at 20% width");

// Insert a auto sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.Auto;
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGreen;
builder.Writeln(
    "Cell automatically sized. The size of this cell is calculated from the table preferred width.");
builder.Writeln("In this case the cell will fill up the rest of the available space.");

doc.Save(ArtifactsDir + "Table.CellPreferredWidths.doc");

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

PreferredWidth Members | Aspose.Words.Tables Namespace | PreferredWidth | PreferredWidth


PreferredWidth Members

PreferredWidth overview

Public Static (Shared) Fields

Auto Returns an instance that represents the "preferred width is not specified" value.

Public Static (Shared) Methods

FromPercent | A creation method that returns a new instance that represents a preferred width specified as a percentage.
FromPoints | A creation method that returns a new instance that represents a preferred width specified using a number of points.

Public Instance Properties

Type | Gets the unit of measure used for this preferred width value.
Value | Gets the preferred width value. The unit of measure is specified in the Type property.

Public Instance Methods

Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.
ToString | Returns a user-friendly string that displays the value of this object.

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace | PreferredWidth | PreferredWidth


PreferredWidth Fields

The fields of the PreferredWidth class are listed below. For a complete list of PreferredWidth class members, see the PreferredWidth Members topic.

Public Static (Shared) Fields

Auto Returns an instance that represents the "preferred width is not specified" value.

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace | PreferredWidth | PreferredWidth


PreferredWidth.Auto Field

Returns an instance that represents the "preferred width is not specified" value.

[Visual Basic]
Public Shared ReadOnly Auto As PreferredWidth
[C#]
public static readonly PreferredWidth Auto;

Example

Shows how to set the different preferred width settings.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table row made up of three cells which have different preferred widths.
Table table = builder.StartTable();

// Insert an absolute sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightYellow;
builder.Writeln("Cell at 40 points width");

// Insert a relative (percent) sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(20);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
builder.Writeln("Cell at 20% width");

// Insert a auto sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.Auto;
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGreen;
builder.Writeln(
    "Cell automatically sized. The size of this cell is calculated from the table preferred width.");
builder.Writeln("In this case the cell will fill up the rest of the available space.");

doc.Save(ArtifactsDir + "Table.CellPreferredWidths.doc");

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidth Properties

The properties of the PreferredWidth class are listed below. For a complete list of PreferredWidth class members, see the PreferredWidth Members topic.

Public Instance Properties

Type | Gets the unit of measure used for this preferred width value.
Value | Gets the preferred width value. The unit of measure is specified in the Type property.

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace | PreferredWidth | PreferredWidth


Type Property

Aspose.Words

PreferredWidth.Type Property

Gets the unit of measure used for this preferred width value.

[Visual Basic]
Public ReadOnly Property Type As PreferredWidthType
[C#]
public PreferredWidthType Type {get;}

Example

Retrieves the preferred width type of a table cell.

[C#]

Cell firstCell = table.FirstRow.FirstCell;
PreferredWidthType type = firstCell.CellFormat.PreferredWidth.Type;
double value = firstCell.CellFormat.PreferredWidth.Value;

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


Value Property

Aspose.Words

PreferredWidth.Value Property

Gets the preferred width value. The unit of measure is specified in the Type property.

[Visual Basic]
Public ReadOnly Property Value As Double
[C#]
public double Value {get;}

Example

Retrieves the preferred width type of a table cell.

[C#]

Cell firstCell = table.FirstRow.FirstCell;
PreferredWidthType type = firstCell.CellFormat.PreferredWidth.Type;
double value = firstCell.CellFormat.PreferredWidth.Value;

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidth Methods

The methods of the PreferredWidth class are listed below. For a complete list of PreferredWidth class members, see the PreferredWidth Members topic.

Public Static (Shared) Methods

FromPercent | A creation method that returns a new instance that represents a preferred width specified as a percentage.
FromPoints | A creation method that returns a new instance that represents a preferred width specified using a number of points.

Public Instance Methods

Equals | Determines whether the specified object is equal in value to the current object.
GetHashCode | Serves as a hash function for this type.
ToString | Returns a user-friendly string that displays the value of this object.

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace | PreferredWidth | PreferredWidth


PreferredWidth.Equals Method

Determines whether the specified object is equal in value to the current object.

[Visual Basic]
Overrides Public Function Equals( _
ByVal obj As Object _
) As Boolean
[C#]
public override bool Equals(
object obj
);

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidth.FromPercent Method

A creation method that returns a new instance that represents a preferred width specified as a percentage.

[Visual Basic]
Public Shared Function FromPercent( _
ByVal percent As Double _
) As PreferredWidth
[C#]
public static PreferredWidth FromPercent(
double percent
);

Parameters

percent
The value must be from 0 to 100.

Example

Shows how to set a table to auto fit to 50% of the page width.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table with a width that takes up half the page width.
Table table = builder.StartTable();

// Insert a few cells
builder.InsertCell();
table.PreferredWidth = PreferredWidth.FromPercent(50);
builder.Writeln("Cell #1");

builder.InsertCell();
builder.Writeln("Cell #2");

builder.InsertCell();
builder.Writeln("Cell #3");

doc.Save(ArtifactsDir + "Table.PreferredWidth.doc");
Shows how to set the different preferred width settings.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table row made up of three cells which have different preferred widths.
Table table = builder.StartTable();

// Insert an absolute sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightYellow;
builder.Writeln("Cell at 40 points width");

// Insert a relative (percent) sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(20);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
builder.Writeln("Cell at 20% width");

// Insert a auto sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.Auto;
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGreen;
builder.Writeln(
    "Cell automatically sized. The size of this cell is calculated from the table preferred width.");
builder.Writeln("In this case the cell will fill up the rest of the available space.");

doc.Save(ArtifactsDir + "Table.CellPreferredWidths.doc");

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidth.FromPoints Method

A creation method that returns a new instance that represents a preferred width specified using a number of points.

[Visual Basic]
Public Shared Function FromPoints( _
ByVal points As Double _
) As PreferredWidth
[C#]
public static PreferredWidth FromPoints(
double points
);

Parameters

points
The value must be from 0 to 22 inches (22 * 72 points).

Example

Shows how to specify a cell preferred width by converting inches to points.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(ConvertUtil.InchToPoint(3));
builder.InsertCell();
Shows how to set the different preferred width settings.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table row made up of three cells which have different preferred widths.
Table table = builder.StartTable();

// Insert an absolute sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightYellow;
builder.Writeln("Cell at 40 points width");

// Insert a relative (percent) sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(20);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
builder.Writeln("Cell at 20% width");

// Insert a auto sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.Auto;
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGreen;
builder.Writeln(
    "Cell automatically sized. The size of this cell is calculated from the table preferred width.");
builder.Writeln("In this case the cell will fill up the rest of the available space.");

doc.Save(ArtifactsDir + "Table.CellPreferredWidths.doc");

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidth.GetHashCode Method

Serves as a hash function for this type.

[Visual Basic]
Overrides Public Function GetHashCode() As Integer
[C#]
public override int GetHashCode();

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidth.ToString Method

Returns a user-friendly string that displays the value of this object.

[Visual Basic]
Overrides Public Function ToString() As String
[C#]
public override string ToString();

See Also

PreferredWidth Class | Aspose.Words.Tables Namespace


PreferredWidthType Enumeration

Specifies the unit of measurement for the preferred width of a table or cell.

[Visual Basic]
Public Enum PreferredWidthType
[C#]
public enum PreferredWidthType

Remarks

Example

Retrieves the preferred width type of a table cell.

[C#]

Cell firstCell = table.FirstRow.FirstCell;
PreferredWidthType type = firstCell.CellFormat.PreferredWidth.Type;
double value = firstCell.CellFormat.PreferredWidth.Value;

Members

Member Name | Description | Value
Auto | The preferred width is not specified. The actual width of the table or cell is either specified using the explicit width or will be determined automatically by the table layout algorithm when the table is displayed, depending on the table auto fit setting. | 1
Percent | Measure the current item width using a specified percentage. | 2
Points | Measure the current item width using a specified number of points (1/72 inch). | 3

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace | PreferredWidth


Row Class

Represents a table row.

For a list of all members of this type, see Row Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Tables.Row

[Visual Basic]
Public Class Row
Inherits CompositeNode
[C#]
public class Row : CompositeNode

Remarks

Row can only be a child of a Table.

Row can contain one or more Cell nodes.

A minimal valid row needs to have at least one Cell.

Example

Retrieves the index of a row in a table.

[C#]

int rowIndex = table.IndexOf(row);
Shows how to make a clone of the last row of a table and append it to the table.
[C#]

Document doc = new Document(MyDir + "Table.SimpleTable.doc");

// Retrieve the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Clone the last row in the table.
Row clonedRow = (Row) table.LastRow.Clone(true);

// Remove all content from the cloned row's cells. This makes the row ready for
// new content to be inserted into.
foreach (Cell cell in clonedRow.Cells.OfType<Cell>())
    cell.RemoveAllChildren();

// Add the row to the end of the table.
table.AppendChild(clonedRow);

doc.Save(ArtifactsDir + "Table.AddCloneRowToTable.doc");
Shows how to iterate through all tables in the document and display the content from each cell.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");
Shows how to build a nested table without using DocumentBuilder.
[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Row Members | Aspose.Words.Tables Namespace


Row Members

Row overview

Public Instance Constructors

Row Constructor Initializes a new instance of the Row class.

Public Instance Properties

Cells | Provides typed access to the Cell child nodes of the row.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstCell | Returns the first Cell in the row.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsFirstRow | True if this is the first row in a table; false otherwise.
IsLastRow | True if this is the last row in a table; false otherwise.
LastCell | Returns the last Cell in the row.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Row.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentTable | Returns the immediate parent table of the row.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RowFormat | Provides access to the formatting properties of the row.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum | If the Row has no cells, creates and appends one Cell.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText | Gets the text of all cells in this row including the end of row character.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Row Class | Aspose.Words.Tables Namespace


Row Constructor

Initializes a new instance of the Row class.

[Visual Basic]
Overloads Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Row(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Row is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Row to the document use InsertAfter or InsertBefore on the table where you want the row inserted.

Example

Shows how to build a nested table without using DocumentBuilder.

[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

See Also

Row Class | Aspose.Words.Tables Namespace


Row Properties

The properties of the Row class are listed below. For a complete list of Row class members, see the Row Members topic.

Public Instance Properties

Cells | Provides typed access to the Cell child nodes of the row.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstCell | Returns the first Cell in the row.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
IsFirstRow | True if this is the first row in a table; false otherwise.
IsLastRow | True if this is the last row in a table; false otherwise.
LastCell | Returns the last Cell in the row.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Row.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
ParentTable | Returns the immediate parent table of the row.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RowFormat | Provides access to the formatting properties of the row.

See Also

Row Class | Aspose.Words.Tables Namespace


Cells Property

Aspose.Words

Row.Cells Property

Provides typed access to the Cell child nodes of the row.

[Visual Basic]
Public ReadOnly Property Cells As CellCollection
[C#]
public CellCollection Cells {get;}

Example

Shows how to iterate through all tables in the document and display the content from each cell.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}

See Also

Row Class | Aspose.Words.Tables Namespace


FirstCell Property

Aspose.Words

Row.FirstCell Property

Returns the first Cell in the row.

[Visual Basic]
Public ReadOnly Property FirstCell As Cell
[C#]
public Cell FirstCell {get;}

See Also

Row Class | Aspose.Words.Tables Namespace


IsFirstRow Property

Aspose.Words

Row.IsFirstRow Property

True if this is the first row in a table; false otherwise.

[Visual Basic]
Public ReadOnly Property IsFirstRow As Boolean
[C#]
public bool IsFirstRow {get;}

See Also

Row Class | Aspose.Words.Tables Namespace


IsLastRow Property

Aspose.Words

Row.IsLastRow Property

True if this is the last row in a table; false otherwise.

[Visual Basic]
Public ReadOnly Property IsLastRow As Boolean
[C#]
public bool IsLastRow {get;}

Example

Shows how to set a table to stay together on the same page.

[C#]

// To keep a table from breaking across a page we need to enable KeepWithNext
// for every paragraph in the table except for the last paragraphs in the last
// row of the table.
foreach (Cell cell in table.GetChildNodes(NodeType.Cell, true).OfType<Cell>())
foreach (Paragraph para in cell.Paragraphs.OfType<Paragraph>())
    if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
        para.ParagraphFormat.KeepWithNext = true;

See Also

Row Class | Aspose.Words.Tables Namespace


LastCell Property

Aspose.Words

Row.LastCell Property

Returns the last Cell in the row.

[Visual Basic]
Public ReadOnly Property LastCell As Cell
[C#]
public Cell LastCell {get;}

See Also

Row Class | Aspose.Words.Tables Namespace


NodeType Property

Aspose.Words

Row.NodeType Property

Returns NodeType.Row.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));

See Also

Row Class | Aspose.Words.Tables Namespace


ParentTable Property

Aspose.Words

Row.ParentTable Property

Returns the immediate parent table of the row.

[Visual Basic]
Public ReadOnly Property ParentTable As Table
[C#]
public Table ParentTable {get;}

Remarks

Equivalent to (Table)FirstNonMarkupParentNode.

See Also

Row Class | Aspose.Words.Tables Namespace


RowFormat Property

Aspose.Words

Row.RowFormat Property

Provides access to the formatting properties of the row.

[Visual Basic]
Public ReadOnly Property RowFormat As RowFormat
[C#]
public RowFormat RowFormat {get;}

Example

Shows how to modify formatting of a table row.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Retrieve the first row in the table.
Row firstRow = table.FirstRow;

// Modify some row level properties.
firstRow.RowFormat.Borders.LineStyle = LineStyle.None;
firstRow.RowFormat.HeightRule = HeightRule.Auto;
firstRow.RowFormat.AllowBreakAcrossPages = true;
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

See Also

Row Class | Aspose.Words.Tables Namespace


Row Methods

The methods of the Row class are listed below. For a complete list of Row class members, see the Row Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) |
EnsureMinimum | If the Row has no cells, creates and appends one Cell.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText | Gets the text of all cells in this row including the end of row character.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Row Class | Aspose.Words.Tables Namespace


Row.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitRowStart, then calls Accept for all child nodes of the section and calls DocumentVisitor.VisitRowEnd at the end.

See Also

Row Class | Aspose.Words.Tables Namespace


Row.EnsureMinimum Method

If the Row has no cells, creates and appends one Cell.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Shows how to ensure a row node is valid.

[C#]

Document doc = new Document();

// Create a new table and add it to the document.
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);

// Create a new row and add it to the table.
Row row = new Row(doc);
table.AppendChild(row);

// Ensure the row is valid (has at least one cell).
row.EnsureMinimum();

See Also

Row Class | Aspose.Words.Tables Namespace


Row.GetText Method

Gets the text of all cells in this row including the end of row character.

[Visual Basic]
Overrides Public Function GetText() As String
[C#]
public override string GetText();

Remarks

Returns concatenated text of all child nodes with the end of row character ControlChar.Cell appended at the end.

The returned string includes all control and special characters as described in ControlChar.

See Also

Row Class | Aspose.Words.Tables Namespace


RowCollection Class

Provides typed access to a collection of Row nodes.

For a list of all members of this type, see RowCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.Tables.RowCollection

[Visual Basic]
Public Class RowCollection
Inherits NodeCollection
[C#]
public class RowCollection : NodeCollection

Example

Shows how to iterate through all tables in the document and display the content from each cell.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RowCollection Members | Aspose.Words.Tables Namespace


RowCollection Members

RowCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Row at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all rows from the collection to a new array of rows.

See Also

RowCollection Class | Aspose.Words.Tables Namespace


RowCollection Properties

The properties of the RowCollection class are listed below. For a complete list of RowCollection class members, see the RowCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Row at the given index.

See Also

RowCollection Class | Aspose.Words.Tables Namespace


Item Property

Aspose.Words

RowCollection.Item Property

Retrieves a Row at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Row
[C#]
new public Row this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

RowCollection Class | Aspose.Words.Tables Namespace


RowCollection Methods

The methods of the RowCollection class are listed below. For a complete list of RowCollection class members, see the RowCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all rows from the collection to a new array of rows.

See Also

RowCollection Class | Aspose.Words.Tables Namespace


RowCollection.ToArray Method

Copies all rows from the collection to a new array of rows.

[Visual Basic]
Public Function ToArray() As Row()
[C#]
new public Row[] ToArray();

Return Value

An array of rows.

See Also

RowCollection Class | Aspose.Words.Tables Namespace


RowFormat Class

Represents all formatting for a table row.

For a list of all members of this type, see RowFormat Members.

System.Object
Aspose.Words.Tables.RowFormat

[Visual Basic]
Public Class RowFormat
[C#]
public class RowFormat

Example

Shows how to modify formatting of a table row.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Retrieve the first row in the table.
Row firstRow = table.FirstRow;

// Modify some row level properties.
firstRow.RowFormat.Borders.LineStyle = LineStyle.None;
firstRow.RowFormat.HeightRule = HeightRule.Auto;
firstRow.RowFormat.AllowBreakAcrossPages = true;
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

RowFormat Members | Aspose.Words.Tables Namespace


RowFormat Members

RowFormat overview

Public Instance Properties

AllowBreakAcrossPages | True if the text in a table row is allowed to split across a page break.
Borders | Gets the collection of default cell borders for the row.
HeadingFormat | True if the row is repeated as a table heading on every page when the table spans more than one page.
Height | Gets or sets the height of the table row in points.
HeightRule | Gets or sets the rule for determining the height of the table row.

Public Instance Methods

ClearFormatting Resets to default row formatting.

See Also

RowFormat Class | Aspose.Words.Tables Namespace


RowFormat Properties

The properties of the RowFormat class are listed below. For a complete list of RowFormat class members, see the RowFormat Members topic.

Public Instance Properties

AllowBreakAcrossPages | True if the text in a table row is allowed to split across a page break.
Borders | Gets the collection of default cell borders for the row.
HeadingFormat | True if the row is repeated as a table heading on every page when the table spans more than one page.
Height | Gets or sets the height of the table row in points.
HeightRule | Gets or sets the rule for determining the height of the table row.

See Also

RowFormat Class | Aspose.Words.Tables Namespace


AllowBreakAcrossPages Property

Aspose.Words

RowFormat.AllowBreakAcrossPages Property

True if the text in a table row is allowed to split across a page break.

[Visual Basic]
Public Property AllowBreakAcrossPages As Boolean
[C#]
public bool AllowBreakAcrossPages {get; set;}

Example

Shows how to disable rows breaking across pages for every row in a table.

[C#]

// Disable breaking across pages for all rows in the table.
foreach (Row row in table.OfType<Row>())
    row.RowFormat.AllowBreakAcrossPages = false;

See Also

RowFormat Class | Aspose.Words.Tables Namespace


Borders Property

Aspose.Words

RowFormat.Borders Property

Gets the collection of default cell borders for the row.

[Visual Basic]
Public ReadOnly Property Borders As BorderCollection
[C#]
public BorderCollection Borders {get;}

See Also

RowFormat Class | Aspose.Words.Tables Namespace


HeadingFormat Property

Aspose.Words

RowFormat.HeadingFormat Property

True if the row is repeated as a table heading on every page when the table spans more than one page.

[Visual Basic]
Public Property HeadingFormat As Boolean
[C#]
public bool HeadingFormat {get; set;}

Example

Shows how to build a table which include heading rows that repeat on subsequent pages.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.RowFormat.HeadingFormat = true;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.CellFormat.Width = 100;
builder.InsertCell();
builder.Writeln("Heading row 1");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Heading row 2");
builder.EndRow();

builder.CellFormat.Width = 50;
builder.ParagraphFormat.ClearFormatting();

// Insert some content so the table is long enough to continue onto the next page.
for (int i = 0; i < 50; i++)
{
    builder.InsertCell();
    builder.RowFormat.HeadingFormat = false;
    builder.Write("Column 1 Text");
    builder.InsertCell();
    builder.Write("Column 2 Text");
    builder.EndRow();
}

doc.Save(ArtifactsDir + "Table.HeadingRow.doc");

See Also

RowFormat Class | Aspose.Words.Tables Namespace


Height Property

Aspose.Words

RowFormat.Height Property

Gets or sets the height of the table row in points.

[Visual Basic]
Public Property Height As Double
[C#]
public double Height {get; set;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

RowFormat Class | Aspose.Words.Tables Namespace


HeightRule Property

Aspose.Words

RowFormat.HeightRule Property

Gets or sets the rule for determining the height of the table row.

[Visual Basic]
Public Property HeightRule As HeightRule
[C#]
public HeightRule HeightRule {get; set;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to create a formatted table using DocumentBuilder
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

RowFormat Class | Aspose.Words.Tables Namespace


RowFormat Methods

The methods of the RowFormat class are listed below. For a complete list of RowFormat class members, see the RowFormat Members topic.

Public Instance Methods

ClearFormatting Resets to default row formatting.

See Also

RowFormat Class | Aspose.Words.Tables Namespace


RowFormat.ClearFormatting Method

Resets to default row formatting.

[Visual Basic]
Public Sub ClearFormatting()
[C#]
public void ClearFormatting();

See Also

RowFormat Class | Aspose.Words.Tables Namespace


Table Class

Represents a table in a Word document.

For a list of all members of this type, see Table Members.

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Tables.Table

[Visual Basic]
Public Class Table
Inherits CompositeNode
[C#]
public class Table : CompositeNode

Remarks

Table is a block-level node and can be a child of classes derived from Story or InlineStory.

Table can contain one or more Row nodes.

A minimal valid table needs to have at least one Row.

Example

Shows how to remove all borders from a table.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Remove all borders from the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Clear the borders all cells in the table.
table.ClearBorders();

doc.Save(ArtifactsDir + "Table.ClearBorders.doc");
Shows how to combine the rows from two tables into one.
[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table) doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table) doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(ArtifactsDir + "Table.CombineTables.doc");
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to iterate through all tables in the document and display the content from each cell.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
Shows how to insert a table using the constructors of nodes.
[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");
Shows how to build a nested table without using DocumentBuilder.
[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Table Members | Aspose.Words.Tables Namespace


Table Members

Table overview

Public Instance Constructors

Table Constructor Initializes a new instance of the Table class.

Public Instance Properties

AbsoluteHorizontalDistance | Gets absolute horizontal floating table position specified by the table properties, in points. Default value is 0.
AbsoluteVerticalDistance | Gets absolute vertical floating table position specified by the table properties, in points. Default value is 0.
Alignment | Specifies how an inline table is aligned in the document.
AllowAutoFit | Allows Microsoft Word and Aspose.Words to automatically resize cells in a table to fit their contents.
AllowCellSpacing | Gets or sets the "Allow spacing between cells" option.
AllowOverlap | Gets whether a floating table shall allow other floating objects in the document to overlap its extents when displayed. Default value is true.
Bidi | Gets or sets whether this is a right-to-left table.
BottomPadding | Gets or sets the amount of space (in points) to add below the contents of cells.
CellSpacing | Gets or sets the amount of space (in points) between the cells.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Description | Gets or sets description of this table. It provides an alternative text representation of the information contained in the table.
DistanceBottom | Gets distance between table bottom and the surrounding text, in points.
DistanceLeft | Gets distance between table left and the surrounding text, in points.
DistanceRight | Gets distance between table right and the surrounding text, in points.
DistanceTop | Gets distance between table top and the surrounding text, in points.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstRow | Returns the first Row node in the table.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HorizontalAnchor | Gets the base object from which the horizontal positioning of floating table should be calculated. Default value is Column.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastRow | Returns the last Row node in the table.
LeftIndent | Gets or sets the value that represents the left indent of the table.
LeftPadding | Gets or sets the amount of space (in points) to add to the left of the contents of cells.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Table.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreferredWidth | Gets or sets the table preferred width.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalAlignment | Gets floating table relative horizontal alignment.
RelativeVerticalAlignment | Gets floating table relative vertical alignment.
RightPadding | Gets or sets the amount of space (in points) to add to the right of the contents of cells.
Rows | Provides typed access to the rows of the table.
Style | Gets or sets the table style applied to this table.
StyleIdentifier | Gets or sets the locale independent style identifier of the table style applied to this table.
StyleName | Gets or sets the name of the table style applied to this table.
StyleOptions | Gets or sets bit flags that specify how a table style is applied to this table.
TextWrapping | Gets or sets TextWrapping for table.
Title | Gets or sets title of this table. It provides an alternative text representation of the information contained in the table.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of cells.
VerticalAnchor | Gets the base object from which the vertical positioning of floating table should be calculated. Default value is Margin.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AutoFit | Resizes the table and cells according to the specified auto fit behavior.
ClearBorders | Removes all table and cell borders on this table.
ClearShading | Removes all shading on the table.
Clone (inherited from Node) |
ConvertToHorizontallyMergedCells | Converts cells horizontally merged by width to cells merged by HorizontalMerge.
EnsureMinimum | If the table has no rows, creates and appends one Row.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
SetBorder | Sets the specified table border to the specified line style, width and color.
SetBorders | Sets all table borders to the specified line style, width and color.
SetShading | Sets shading to the specified values on all cells in the table.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Table Class | Aspose.Words.Tables Namespace


Table Constructor

Initializes a new instance of the Table class.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase _
)
[C#]
public Table(
DocumentBase doc
);

Parameters

doc
The owner document.

Remarks

When Table is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Table to the document use InsertAfter or InsertBefore on the story where you want the table inserted.

Example

Shows how to build a nested table without using DocumentBuilder.

[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

See Also

Table Class | Aspose.Words.Tables Namespace


Table Properties

The properties of the Table class are listed below. For a complete list of Table class members, see the Table Members topic.

Public Instance Properties

AbsoluteHorizontalDistance | Gets absolute horizontal floating table position specified by the table properties, in points. Default value is 0.
AbsoluteVerticalDistance | Gets absolute vertical floating table position specified by the table properties, in points. Default value is 0.
Alignment | Specifies how an inline table is aligned in the document.
AllowAutoFit | Allows Microsoft Word and Aspose.Words to automatically resize cells in a table to fit their contents.
AllowCellSpacing | Gets or sets the "Allow spacing between cells" option.
AllowOverlap | Gets whether a floating table shall allow other floating objects in the document to overlap its extents when displayed. Default value is true.
Bidi | Gets or sets whether this is a right-to-left table.
BottomPadding | Gets or sets the amount of space (in points) to add below the contents of cells.
CellSpacing | Gets or sets the amount of space (in points) between the cells.
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
Count (inherited from CompositeNode) | Gets the number of immediate children of this node.
Description | Gets or sets description of this table. It provides an alternative text representation of the information contained in the table.
DistanceBottom | Gets distance between table bottom and the surrounding text, in points.
DistanceLeft | Gets distance between table left and the surrounding text, in points.
DistanceRight | Gets distance between table right and the surrounding text, in points.
DistanceTop | Gets distance between table top and the surrounding text, in points.
Document (inherited from Node) | Gets the document to which this node belongs.
FirstChild (inherited from CompositeNode) | Gets the first child of the node.
FirstRow | Returns the first Row node in the table.
HasChildNodes (inherited from CompositeNode) | Returns true if this node has any child nodes.
HorizontalAnchor | Gets the base object from which the horizontal positioning of floating table should be calculated. Default value is Column.
IsComposite (inherited from CompositeNode) | Returns true as this node can have child nodes.
LastChild (inherited from CompositeNode) | Gets the last child of the node.
LastRow | Returns the last Row node in the table.
LeftIndent | Gets or sets the value that represents the left indent of the table.
LeftPadding | Gets or sets the amount of space (in points) to add to the left of the contents of cells.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.Table.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
PreferredWidth | Gets or sets the table preferred width.
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Range (inherited from Node) | Returns a Range object that represents the portion of a document that is contained in this node.
RelativeHorizontalAlignment | Gets floating table relative horizontal alignment.
RelativeVerticalAlignment | Gets floating table relative vertical alignment.
RightPadding | Gets or sets the amount of space (in points) to add to the right of the contents of cells.
Rows | Provides typed access to the rows of the table.
Style | Gets or sets the table style applied to this table.
StyleIdentifier | Gets or sets the locale independent style identifier of the table style applied to this table.
StyleName | Gets or sets the name of the table style applied to this table.
StyleOptions | Gets or sets bit flags that specify how a table style is applied to this table.
TextWrapping | Gets or sets TextWrapping for table.
Title | Gets or sets title of this table. It provides an alternative text representation of the information contained in the table.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of cells.
VerticalAnchor | Gets the base object from which the vertical positioning of floating table should be calculated. Default value is Margin.

See Also

Table Class | Aspose.Words.Tables Namespace


AbsoluteHorizontalDistance Property

Aspose.Words

Table.AbsoluteHorizontalDistance Property

Gets absolute horizontal floating table position specified by the table properties, in points. Default value is 0.

[Visual Basic]
Public ReadOnly Property AbsoluteHorizontalDistance As Double
[C#]
public double AbsoluteHorizontalDistance {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


AbsoluteVerticalDistance Property

Aspose.Words

Table.AbsoluteVerticalDistance Property

Gets absolute vertical floating table position specified by the table properties, in points. Default value is 0.

[Visual Basic]
Public ReadOnly Property AbsoluteVerticalDistance As Double
[C#]
public double AbsoluteVerticalDistance {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


Alignment Property

Aspose.Words

Table.Alignment Property

Specifies how an inline table is aligned in the document.

[Visual Basic]
Public Property Alignment As TableAlignment
[C#]
public TableAlignment Alignment {get; set;}

Remarks

The default value is Left.

Example

Shows how to apply a outline border to a table.

[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

doc.Save(ArtifactsDir + "Table.SetOutlineBorders.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


AllowAutoFit Property

Aspose.Words

Table.AllowAutoFit Property

Allows Microsoft Word and Aspose.Words to automatically resize cells in a table to fit their contents.

[Visual Basic]
Public Property AllowAutoFit As Boolean
[C#]
public bool AllowAutoFit {get; set;}

Remarks

The default value is true.

Example

Shows how to set a table to shrink or grow each cell to accommodate its contents.

[C#]

table.AllowAutoFit = true;

See Also

Table Class | Aspose.Words.Tables Namespace | AutoFit


AllowCellSpacing Property

Aspose.Words

Table.AllowCellSpacing Property

Gets or sets the "Allow spacing between cells" option.

[Visual Basic]
Public Property AllowCellSpacing As Boolean
[C#]
public bool AllowCellSpacing {get; set;}

Example

Shows how to insert a table using the constructors of nodes.

[C#]

Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorithm for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.AppendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


AllowOverlap Property

Aspose.Words

Table.AllowOverlap Property

Gets whether a floating table shall allow other floating objects in the document to overlap its extents when displayed. Default value is true.

[Visual Basic]
Public ReadOnly Property AllowOverlap As Boolean
[C#]
public bool AllowOverlap {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


Bidi Property

Aspose.Words

Table.Bidi Property

Gets or sets whether this is a right-to-left table.

[Visual Basic]
Public Property Bidi As Boolean
[C#]
public bool Bidi {get; set;}

Remarks

When true, the cells in this row are laid out right to left.

The default value is false.

See Also

Table Class | Aspose.Words.Tables Namespace


BottomPadding Property

Aspose.Words

Table.BottomPadding Property

Gets or sets the amount of space (in points) to add below the contents of cells.

[Visual Basic]
Public Property BottomPadding As Double
[C#]
public double BottomPadding {get; set;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();

See Also

Table Class | Aspose.Words.Tables Namespace


CellSpacing Property

Aspose.Words

Table.CellSpacing Property

Gets or sets the amount of space (in points) between the cells.

[Visual Basic]
Public Property CellSpacing As Double
[C#]
public double CellSpacing {get; set;}

See Also

Table Class | Aspose.Words.Tables Namespace


Description Property

Aspose.Words

Table.Description Property

Gets or sets description of this table. It provides an alternative text representation of the information contained in the table.

[Visual Basic]
Public Property Description As String
[C#]
public string Description {get; set;}

Remarks

The default value is an empty string.

This property is meaningful for ISO/IEC 29500 compliant DOCX documents (OoxmlCompliance). When saved to pre-ISO/IEC 29500 formats, the property is ignored.

Example

Shows how to build a nested table without using DocumentBuilder.

[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

See Also

Table Class | Aspose.Words.Tables Namespace


DistanceBottom Property

Aspose.Words

Table.DistanceBottom Property

Gets distance between table bottom and the surrounding text, in points.

[Visual Basic]
Public ReadOnly Property DistanceBottom As Double
[C#]
public double DistanceBottom {get;}

See Also

Table Class | Aspose.Words.Tables Namespace


DistanceLeft Property

Aspose.Words

Table.DistanceLeft Property

Gets distance between table left and the surrounding text, in points.

[Visual Basic]
Public ReadOnly Property DistanceLeft As Double
[C#]
public double DistanceLeft {get;}

See Also

Table Class | Aspose.Words.Tables Namespace


DistanceRight Property

Aspose.Words

Table.DistanceRight Property

Gets distance between table right and the surrounding text, in points.

[Visual Basic]
Public ReadOnly Property DistanceRight As Double
[C#]
public double DistanceRight {get;}

See Also

Table Class | Aspose.Words.Tables Namespace


DistanceTop Property

Aspose.Words

Table.DistanceTop Property

Gets distance between table top and the surrounding text, in points.

[Visual Basic]
Public ReadOnly Property DistanceTop As Double
[C#]
public double DistanceTop {get;}

See Also

Table Class | Aspose.Words.Tables Namespace


FirstRow Property

Aspose.Words

Table.FirstRow Property

Returns the first Row node in the table.

[Visual Basic]
Public ReadOnly Property FirstRow As Row
[C#]
public Row FirstRow {get;}

Example

Demonstrates how to use typed properties to access nodes of the document tree.

[C#]

// Quick typed access to the first child Section node of the Document.
Section section = doc.FirstSection;

// Quick typed access to the Body child node of the Section.
Body body = section.Body;

// Quick typed access to all Table child nodes contained in the Body.
TableCollection tables = body.Tables;

foreach (Table table in tables.OfType<Table>())
{
    // Quick typed access to the first row of the table.
    table.FirstRow?.Remove();

    // Quick typed access to the last row of the table.
    table.LastRow?.Remove();
}
Shows how to combine the rows from two tables into one.
[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table) doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table) doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(ArtifactsDir + "Table.CombineTables.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


HorizontalAnchor Property

Aspose.Words

Table.HorizontalAnchor Property

Gets the base object from which the horizontal positioning of floating table should be calculated. Default value is Column.

[Visual Basic]
Public ReadOnly Property HorizontalAnchor As RelativeHorizontalPosition
[C#]
public RelativeHorizontalPosition HorizontalAnchor {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


LastRow Property

Aspose.Words

Table.LastRow Property

Returns the last Row node in the table.

[Visual Basic]
Public ReadOnly Property LastRow As Row
[C#]
public Row LastRow {get;}

Example

Demonstrates how to use typed properties to access nodes of the document tree.

[C#]

// Quick typed access to the first child Section node of the Document.
Section section = doc.FirstSection;

// Quick typed access to the Body child node of the Section.
Body body = section.Body;

// Quick typed access to all Table child nodes contained in the Body.
TableCollection tables = body.Tables;

foreach (Table table in tables.OfType<Table>())
{
    // Quick typed access to the first row of the table.
    table.FirstRow?.Remove();

    // Quick typed access to the last row of the table.
    table.LastRow?.Remove();
}

See Also

Table Class | Aspose.Words.Tables Namespace


LeftIndent Property

Aspose.Words

Table.LeftIndent Property

Gets or sets the value that represents the left indent of the table.

[Visual Basic]
Public Property LeftIndent As Double
[C#]
public double LeftIndent {get; set;}

Example

Shows how to create a formatted table using DocumentBuilder

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Make the header row.
builder.InsertCell();

// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.LeftIndent = 20.0;

// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;

// Some special features for the header row.
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;

builder.CellFormat.Width = 100.0;
builder.Write("Header Row,\n Cell 1");

// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.InsertCell();
builder.Write("Header Row,\n Cell 2");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();

// Set features for the other rows and cells.
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

// Reset height and define a different height rule for table body
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;

// Build the other cells.
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();

builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");

builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");

builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();

doc.Save(ArtifactsDir + "DocumentBuilder.CreateFormattedTable.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


LeftPadding Property

Aspose.Words

Table.LeftPadding Property

Gets or sets the amount of space (in points) to add to the left of the contents of cells.

[Visual Basic]
Public Property LeftPadding As Double
[C#]
public double LeftPadding {get; set;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();

See Also

Table Class | Aspose.Words.Tables Namespace


NodeType Property

Aspose.Words

Table.NodeType Property

Returns NodeType.Table.

[Visual Basic]
Overrides Public ReadOnly Property NodeType As NodeType
[C#]
public override NodeType NodeType {get;}

Example

Shows how to retrieve the NodeType enumeration of nodes.

[C#]

Document doc = new Document(MyDir + "Document.doc");

// Let's pick a node that we can't be quite sure of what type it is.
// In this case lets pick the first node of the first paragraph in the body of the document
Node node = doc.FirstSection.Body.FirstParagraph.FirstChild;
Console.WriteLine("NodeType of first child: " + Node.NodeTypeToString(node.NodeType));

// This time let's pick a node that we know the type of. Create a new paragraph and a table node.
Paragraph para = new Paragraph(doc);
Table table = new Table(doc);

// Access to NodeType for typed nodes will always return their specific NodeType.
// i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
Console.WriteLine("NodeType of Paragraph: " + Node.NodeTypeToString(para.NodeType));
Console.WriteLine("NodeType of Table: " + Node.NodeTypeToString(table.NodeType));
Shows how to find out if a table contains another table or if the table itself is nested inside another table.
[C#]

Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true).OfType<Table>())
    {
        // First lets find if any cells in the table have tables themselves as children.
        int count = GetChildTableCount(table);
        Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

        // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
        int tableDepth = GetNestedDepthOfTable(table);

        if (tableDepth > 0)
            Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex,
                tableDepth);
        else
            Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);

        tableIndex++;
    }
}

/// <summary>
/// Calculates what level a table is nested inside other tables.
/// <returns>
/// An integer containing the level the table is nested at.
/// 0 = Table is not nested inside any other table
/// 1 = Table is nested within one parent table
/// 2 = Table is nested within two parent tables etc..</returns>
/// </summary>
private static int GetNestedDepthOfTable(Table table)
{
    int depth = 0;

    NodeType type = table.NodeType;
    // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Node parent = table.GetAncestor(type);

    while (parent != null)
    {
        // Every time we find a table a level up we increase the depth counter and then try to find an
        // ancestor of type table from the parent.
        depth++;
        parent = parent.GetAncestor(type);
    }

    return depth;
}

/// <summary>
/// Determines if a table contains any immediate child table within its cells.
/// Does not recursively traverse through those tables to check for further tables.
/// <returns>Returns true if at least one child cell contains a table.
/// Returns false if no cells in the table contains a table.</returns>
/// </summary>
private static int GetChildTableCount(Table table)
{
    int tableCount = 0;
    // Iterate through all child rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells.OfType<Cell>())
        {
            // Retrieve the collection of child tables of this cell
            TableCollection childTables = Cell.Tables;

            // If this cell has a table as a child then return true
            if (childTables.Count > 0)
                tableCount++;
        }
    }

    // No cell contains a table
    return tableCount;
}

See Also

Table Class | Aspose.Words.Tables Namespace


PreferredWidth Property

Aspose.Words

Table.PreferredWidth Property

Gets or sets the table preferred width.

[Visual Basic]
Public Property PreferredWidth As PreferredWidth
[C#]
public PreferredWidth PreferredWidth {get; set;}

Remarks

The default value is Auto.

Example

Shows how to set a table to auto fit to 50% of the page width.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table with a width that takes up half the page width.
Table table = builder.StartTable();

// Insert a few cells
builder.InsertCell();
table.PreferredWidth = PreferredWidth.FromPercent(50);
builder.Writeln("Cell #1");

builder.InsertCell();
builder.Writeln("Cell #2");

builder.InsertCell();
builder.Writeln("Cell #3");

doc.Save(ArtifactsDir + "Table.PreferredWidth.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


RelativeHorizontalAlignment Property

Aspose.Words

Table.RelativeHorizontalAlignment Property

Gets floating table relative horizontal alignment.

[Visual Basic]
Public ReadOnly Property RelativeHorizontalAlignment As HorizontalAlignment
[C#]
public HorizontalAlignment RelativeHorizontalAlignment {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


RelativeVerticalAlignment Property

Aspose.Words

Table.RelativeVerticalAlignment Property

Gets floating table relative vertical alignment.

[Visual Basic]
Public ReadOnly Property RelativeVerticalAlignment As VerticalAlignment
[C#]
public VerticalAlignment RelativeVerticalAlignment {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


RightPadding Property

Aspose.Words

Table.RightPadding Property

Gets or sets the amount of space (in points) to add to the right of the contents of cells.

[Visual Basic]
Public Property RightPadding As Double
[C#]
public double RightPadding {get; set;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();

See Also

Table Class | Aspose.Words.Tables Namespace


Rows Property

Aspose.Words

Table.Rows Property

Provides typed access to the rows of the table.

[Visual Basic]
Public ReadOnly Property Rows As RowCollection
[C#]
public RowCollection Rows {get;}

Example

Shows how to combine the rows from two tables into one.

[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table) doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table) doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(ArtifactsDir + "Table.CombineTables.doc");
Shows how to iterate through all tables in the document and display the content from each cell.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables.OfType<Table>())
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells.OfType<Cell>())
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            String cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }

        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}

See Also

Table Class | Aspose.Words.Tables Namespace


Style Property

Aspose.Words

Table.Style Property

Gets or sets the table style applied to this table.

[Visual Basic]
Public Property Style As Style
[C#]
public Style Style {get; set;}

See Also

Table Class | Aspose.Words.Tables Namespace


StyleIdentifier Property

Aspose.Words

Table.StyleIdentifier Property

Gets or sets the locale independent style identifier of the table style applied to this table.

[Visual Basic]
Public Property StyleIdentifier As StyleIdentifier
[C#]
public StyleIdentifier StyleIdentifier {get; set;}

Example

Shows how to build a new table with a table style applied.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions =
    TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Continue with building the table as normal.
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.SetTableStyle.docx");

See Also

Table Class | Aspose.Words.Tables Namespace


StyleName Property

Aspose.Words

Table.StyleName Property

Gets or sets the name of the table style applied to this table.

[Visual Basic]
Public Property StyleName As String
[C#]
public string StyleName {get; set;}

See Also

Table Class | Aspose.Words.Tables Namespace


StyleOptions Property

Aspose.Words

Table.StyleOptions Property

Gets or sets bit flags that specify how a table style is applied to this table.

[Visual Basic]
Public Property StyleOptions As TableStyleOptions
[C#]
public TableStyleOptions StyleOptions {get; set;}

Example

Shows how to build a new table with a table style applied.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions =
    TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Continue with building the table as normal.
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.SetTableStyle.docx");

See Also

Table Class | Aspose.Words.Tables Namespace


TextWrapping Property

Aspose.Words

Table.TextWrapping Property

Gets or sets TextWrapping for table.

[Visual Basic]
Public Property TextWrapping As TextWrapping
[C#]
public TextWrapping TextWrapping {get; set;}

See Also

Table Class | Aspose.Words.Tables Namespace


Title Property

Aspose.Words

Table.Title Property

Gets or sets title of this table. It provides an alternative text representation of the information contained in the table.

[Visual Basic]
Public Property Title As String
[C#]
public string Title {get; set;}

Remarks

The default value is an empty string.

This property is meaningful for ISO/IEC 29500 compliant DOCX documents (OoxmlCompliance). When saved to pre-ISO/IEC 29500 formats, the property is ignored.

Example

Shows how to build a nested table without using DocumentBuilder.

[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(ArtifactsDir + "Table.CreateNestedTable.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, String cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}

See Also

Table Class | Aspose.Words.Tables Namespace


TopPadding Property

Aspose.Words

Table.TopPadding Property

Gets or sets the amount of space (in points) to add above the contents of cells.

[Visual Basic]
Public Property TopPadding As Double
[C#]
public double TopPadding {get; set;}

Example

Shows how to create a table that contains a single cell and apply row formatting.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;

builder.Writeln("I'm a wonderful formatted row.");

builder.EndRow();
builder.EndTable();

See Also

Table Class | Aspose.Words.Tables Namespace


VerticalAnchor Property

Aspose.Words

Table.VerticalAnchor Property

Gets the base object from which the vertical positioning of floating table should be calculated. Default value is Margin.

[Visual Basic]
Public ReadOnly Property VerticalAnchor As RelativeVerticalPosition
[C#]
public RelativeVerticalPosition VerticalAnchor {get;}

Example

Shows how get properties for floating tables

[C#]

Document doc = new Document(MyDir + "Table.Distance.docx");

Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

if (table.TextWrapping == TextWrapping.Around)
{
    Assert.AreEqual(HorizontalAlignment.Default, table.RelativeHorizontalAlignment);
    Assert.AreEqual(VerticalAlignment.Default, table.RelativeVerticalAlignment);
    Assert.AreEqual(RelativeHorizontalPosition.Margin, table.HorizontalAnchor);
    Assert.AreEqual(RelativeVerticalPosition.Paragraph, table.VerticalAnchor);
    Assert.AreEqual(0, table.AbsoluteHorizontalDistance);
    Assert.AreEqual(4.8, table.AbsoluteVerticalDistance);
    Assert.AreEqual(true, table.AllowOverlap);
}

See Also

Table Class | Aspose.Words.Tables Namespace


Table Methods

The methods of the Table class are listed below. For a complete list of Table class members, see the Table Members topic.

Public Instance Methods

Accept | Accepts a visitor.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
AutoFit | Resizes the table and cells according to the specified auto fit behavior.
ClearBorders | Removes all table and cell borders on this table.
ClearShading | Removes all shading on the table.
Clone (inherited from Node) |
ConvertToHorizontallyMergedCells | Converts cells horizontally merged by width to cells merged by HorizontalMerge.
EnsureMinimum | If the table has no rows, creates and appends one Row.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetChild (inherited from CompositeNode) | Returns an Nth child node that matches the specified type.
GetChildNodes (inherited from CompositeNode) | Returns a live collection of child nodes that match the specified type.
GetEnumerator (inherited from IEnumerator<Node>) | Provides support for the for each style iteration over the child nodes of this node.
GetText (inherited from CompositeNode) | Gets the text of this node and of all its children.
IndexOf (inherited from CompositeNode) | Returns the index of the specified child node in the child node array.
InsertAfter (inherited from CompositeNode) | Inserts the specified node immediately after the specified reference node.
InsertBefore (inherited from CompositeNode) | Inserts the specified node immediately before the specified reference node.
NextPreOrder (inherited from Node) | Gets next node according to the pre-order tree traversal algorithm.
PrependChild (inherited from CompositeNode) | Adds the specified node to the beginning of the list of child nodes for this node.
PreviousPreOrder (inherited from Node) | Gets the previous node according to the pre-order tree traversal algorithm.
Remove (inherited from Node) | Removes itself from the parent.
RemoveAllChildren (inherited from CompositeNode) | Removes all the child nodes of the current node.
RemoveChild (inherited from CompositeNode) | Removes the specified child node.
RemoveSmartTags (inherited from CompositeNode) | Removes all SmartTag descendant nodes of the current node.
SelectNodes (inherited from CompositeNode) | Selects a list of nodes matching the XPath expression.
SelectSingleNode (inherited from CompositeNode) | Selects the first Node that matches the XPath expression.
SetBorder | Sets the specified table border to the specified line style, width and color.
SetBorders | Sets all table borders to the specified line style, width and color.
SetShading | Sets shading to the specified values on all cells in the table.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.

See Also

Table Class | Aspose.Words.Tables Namespace


Table.Accept Method

Accepts a visitor.

[Visual Basic]
Overrides Public Function Accept( _
ByVal visitor As DocumentVisitor _
) As Boolean
[C#]
public override bool Accept(
DocumentVisitor visitor
);

Parameters

visitor
The visitor that will visit the nodes.

Return Value

True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

Remarks

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Calls DocumentVisitor.VisitTableStart, then calls Accept for all child nodes of the section and calls DocumentVisitor.VisitTableEnd at the end.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

// Open the document we want to remove hidden content from.
    Document doc = new Document(MyDir + "Font.Hidden.doc");

    // Create an object that inherits from the DocumentVisitor class.
    RemoveHiddenContentVisitor hiddenContentRemover = new RemoveHiddenContentVisitor();

    // This is the well known Visitor pattern. Get the model to accept a visitor.
    // The model will iterate through itself by calling the corresponding methods
    // on the visitor object (this is called visiting).

    // We can run it over the entire the document like so:
    doc.Accept(hiddenContentRemover);

    // Or we can run it on only a specific node.
    Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 4, true);
    para.Accept(hiddenContentRemover);

    // Or over a different type of node like below.
    Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
    table.Accept(hiddenContentRemover);

    doc.Save(ArtifactsDir + "Font.Hidden.doc");

}

/// <summary>
/// This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
/// </summary>
class RemoveHiddenContentVisitor : DocumentVisitor
{
    /// <summary>
    /// Called when a FieldStart node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // If this node is hidden, then remove it.
        if (isHidden(fieldStart))
            fieldStart.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldEnd node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (isHidden(fieldEnd))
            fieldEnd.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FieldSeparator node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        if (isHidden(fieldSeparator))
            fieldSeparator.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Run node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitRun(Run run)
    {
        if (isHidden(run))
            run.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Paragraph node is encountered in the document.
    /// </summary>
    public override VisitorAction VisitParagraphStart(Paragraph paragraph)
    {
        if (isHidden(paragraph))
            paragraph.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a FormField is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFormField(FormField formField)
    {
        if (isHidden(formField))
            formField.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a GroupShape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitGroupShapeStart(GroupShape groupShape)
    {
        if (isHidden(groupShape))
            groupShape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Shape is encountered in the document.
    /// </summary>
    public override VisitorAction VisitShapeStart(Shape shape)
    {
        if (isHidden(shape))
            shape.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Comment is encountered in the document.
    /// </summary>
    public override VisitorAction VisitCommentStart(Comment comment)
    {
        if (isHidden(comment))
            comment.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a Footnote is encountered in the document.
    /// </summary>
    public override VisitorAction VisitFootnoteStart(Footnote footnote)
    {
        if (isHidden(footnote))
            footnote.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Table node is ended in the document.
    /// </summary>
    public override VisitorAction VisitTableEnd(Table table)
    {
        // At the moment there is no way to tell if a particular Table/Row/Cell is hidden.
        // Instead, if the content of a table is hidden, then all inline child nodes of the table should be
        // hidden and thus removed by previous visits as well. This will result in the container being empty
        // so if this is the case we know to remove the table node.
        //
        // Note that a table which is not hidden but simply has no content will not be affected by this algorithm,
        // as technically they are not completely empty (for example a properly formed Cell will have at least
        // an empty paragraph in it)
        if (!table.HasChildNodes)
            table.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Cell node is ended in the document.
    /// </summary>
    public override VisitorAction VisitCellEnd(Cell cell)
    {
        if (!cell.HasChildNodes && cell.ParentNode != null)
            cell.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when visiting of a Row node is ended in the document.
    /// </summary>
    public override VisitorAction VisitRowEnd(Row row)
    {
        if (!row.HasChildNodes && row.ParentNode != null)
            row.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Called when a SpecialCharacter is encountered in the document.
    /// </summary>
    public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
    {
        if (isHidden(specialChar))
            specialChar.Remove();

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Returns true if the node passed is set as hidden, returns false if it is visible.
    /// </summary>
    private bool isHidden(Node node)
    {
        if (node is Inline currentNode)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            return currentNode.Font.Hidden;
        }
        else if (node.NodeType == NodeType.Paragraph)
        {
            // If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Paragraph para = (Paragraph) node;
            return para.ParagraphBreakFont.Hidden;
        }
        else if (node is ShapeBase shape)
        {
            // Node is a shape or groupshape.
            return shape.Font.Hidden;
        }
        else if (node is InlineStory inlineStory)
        {
            // Node is a comment or footnote.
            return inlineStory.Font.Hidden;
        }

        // A node that is passed to this method which does not contain a hidden property will end up here.
        // By default nodes are not hidden so return false.
        return false;
    }
}

See Also

Table Class | Aspose.Words.Tables Namespace


Table.AutoFit Method

Resizes the table and cells according to the specified auto fit behavior.

[Visual Basic]
Public Sub AutoFit( _
ByVal behavior As AutoFitBehavior _
)
[C#]
public void AutoFit(
AutoFitBehavior behavior
);

Parameters

behavior
Specifies how to auto fit the table.

Remarks

This method mimics the commands available in the Auto Fit menu for a table in Microsoft Word. The commands available are "Auto Fit to Contents", "Auto Fit to Window" and "Fixed Column Width". In Microsoft Word these commands set relevant table properties and then update the table layout and Aspose.Words does the same for you.

Example

Shows how to build a formatted table that contains 2 rows and 2 columns.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
Shows how to build a new table with a table style applied.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions =
    TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Continue with building the table as normal.
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.SetTableStyle.docx");

See Also

Table Class | Aspose.Words.Tables Namespace


Table.ClearBorders Method

Removes all table and cell borders on this table.

[Visual Basic]
Public Sub ClearBorders()
[C#]
public void ClearBorders();

Example

Shows how to remove all borders from a table.

[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Remove all borders from the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Clear the borders all cells in the table.
table.ClearBorders();

doc.Save(ArtifactsDir + "Table.ClearBorders.doc");
Shows how to apply a outline border to a table.
[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

doc.Save(ArtifactsDir + "Table.SetOutlineBorders.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


Table.ClearShading Method

Removes all shading on the table.

[Visual Basic]
Public Sub ClearShading()
[C#]
public void ClearShading();

See Also

Table Class | Aspose.Words.Tables Namespace


Table.ConvertToHorizontallyMergedCells Method

Converts cells horizontally merged by width to cells merged by HorizontalMerge.

[Visual Basic]
Public Sub ConvertToHorizontallyMergedCells()
[C#]
public void ConvertToHorizontallyMergedCells();

Example

Shows how to convert cells horizontally merged by width to cells merged by CellFormat.HorizontalMerge.

[C#]

Document doc = new Document(MyDir + "Table.ConvertToHorizontallyMergedCells.docx");

// MS Word does not write merge flags anymore, they define merged cells by its width
// So AW by default define only 5 cells in a row and all of it didn't have horizontal merge flag
Table table = doc.FirstSection.Body.Tables[0];
Row row = table.Rows[0];
Assert.AreEqual(5, row.Cells.Count);

// To resolve this inconvenience, we have added new public method to convert cells which are horizontally merged
// by its width to the cell horizontally merged by flags. Thus now we have 7 cells and some of them have
// horizontal merge value
table.ConvertToHorizontallyMergedCells();
row = table.Rows[0];
Assert.AreEqual(7, row.Cells.Count);

Assert.AreEqual(CellMerge.None, row.Cells[0].CellFormat.HorizontalMerge);
Assert.AreEqual(CellMerge.First, row.Cells[1].CellFormat.HorizontalMerge);
Assert.AreEqual(CellMerge.Previous, row.Cells[2].CellFormat.HorizontalMerge);
Assert.AreEqual(CellMerge.None, row.Cells[3].CellFormat.HorizontalMerge);
Assert.AreEqual(CellMerge.First, row.Cells[4].CellFormat.HorizontalMerge);
Assert.AreEqual(CellMerge.Previous, row.Cells[5].CellFormat.HorizontalMerge);
Assert.AreEqual(CellMerge.None, row.Cells[6].CellFormat.HorizontalMerge);

See Also

Table Class | Aspose.Words.Tables Namespace


Table.EnsureMinimum Method

If the table has no rows, creates and appends one Row.

[Visual Basic]
Public Sub EnsureMinimum()
[C#]
public void EnsureMinimum();

Example

Shows how to ensure a table node is valid.

[C#]

Document doc = new Document();

// Create a new table and add it to the document.
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);

// Ensure the table is valid (has at least one row with one cell).
table.EnsureMinimum();

See Also

Table Class | Aspose.Words.Tables Namespace


Table.SetBorder Method

Sets the specified table border to the specified line style, width and color.

[Visual Basic]
Public Sub SetBorder( _
ByVal borderType As BorderType, _
ByVal lineStyle As LineStyle, _
ByVal lineWidth As Double, _
ByVal color As Color, _
ByVal isOverrideCellBorders As Boolean _
)
[C#]
public void SetBorder(
BorderType borderType,
LineStyle lineStyle,
double lineWidth,
Color color,
bool isOverrideCellBorders
);

Parameters

borderType
The table border to change.
lineStyle
The line style to apply.
lineWidth
The line width to set (in points).
color
The color to use for the border.
isOverrideCellBorders
When true, causes all existing explicit cell borders to be removed.

Example

Shows how to apply a outline border to a table.

[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

doc.Save(ArtifactsDir + "Table.SetOutlineBorders.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


Table.SetBorders Method

Sets all table borders to the specified line style, width and color.

[Visual Basic]
Public Sub SetBorders( _
ByVal lineStyle As LineStyle, _
ByVal lineWidth As Double, _
ByVal color As Color _
)
[C#]
public void SetBorders(
LineStyle lineStyle,
double lineWidth,
Color color
);

Parameters

lineStyle
The line style to apply.
lineWidth
The line width to set (in points).
color
The color to use for the border.

Example

Shows how to build a table with all borders enabled (grid).

[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around and inside the table.
table.SetBorders(LineStyle.Single, 1.5, Color.Green);

doc.Save(ArtifactsDir + "Table.SetAllBorders.doc");
Shows how to format table and cell with different borders and shadings
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
builder.InsertCell();

// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");

builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");

// End this row.
builder.EndRow();

// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();

// Create the second row.
builder.InsertCell();

// Create larger borders for the first cell of this row. This will be different
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");

builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");

doc.Save(ArtifactsDir + "Table.SetBordersAndShading.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


Table.SetShading Method

Sets shading to the specified values on all cells in the table.

[Visual Basic]
Public Sub SetShading( _
ByVal texture As TextureIndex, _
ByVal foregroundColor As Color, _
ByVal backgroundColor As Color _
)
[C#]
public void SetShading(
TextureIndex texture,
Color foregroundColor,
Color backgroundColor
);

Parameters

texture
The texture to apply.
foregroundColor
The color of the texture.
backgroundColor
The color of the background fill.

Example

Shows how to apply a outline border to a table.

[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

doc.Save(ArtifactsDir + "Table.SetOutlineBorders.doc");

See Also

Table Class | Aspose.Words.Tables Namespace


TableAlignment Enumeration

Specifies alignment for an inline table.

[Visual Basic]
Public Enum TableAlignment
[C#]
public enum TableAlignment

Example

Shows how to apply a outline border to a table.

[C#]

Document doc = new Document(MyDir + "Table.EmptyTable.doc");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);

// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;

// Clear any existing borders from the table.
table.ClearBorders();

// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

doc.Save(ArtifactsDir + "Table.SetOutlineBorders.doc");

Members

Member Name | Description | Value
Left | The table is aligned to the left. | 0
Center | The table is centered. | 1
Right | The table is aligned to the right. | 2

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace


TableCollection Class

Provides typed access to a collection of Table nodes.

For a list of all members of this type, see TableCollection Members.

System.Object
Aspose.Words.NodeCollection
Aspose.Words.Tables.TableCollection

[Visual Basic]
Public Class TableCollection
Inherits NodeCollection
[C#]
public class TableCollection : NodeCollection

Example

Demonstrates how to use typed properties to access nodes of the document tree.

[C#]

// Quick typed access to the first child Section node of the Document.
Section section = doc.FirstSection;

// Quick typed access to the Body child node of the Section.
Body body = section.Body;

// Quick typed access to all Table child nodes contained in the Body.
TableCollection tables = body.Tables;

foreach (Table table in tables.OfType<Table>())
{
    // Quick typed access to the first row of the table.
    table.FirstRow?.Remove();

    // Quick typed access to the last row of the table.
    table.LastRow?.Remove();
}
Shows how to find out if a table contains another table or if the table itself is nested inside another table.
[C#]

Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true).OfType<Table>())
    {
        // First lets find if any cells in the table have tables themselves as children.
        int count = GetChildTableCount(table);
        Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count);

        // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
        int tableDepth = GetNestedDepthOfTable(table);

        if (tableDepth > 0)
            Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex,
                tableDepth);
        else
            Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex);

        tableIndex++;
    }
}

/// <summary>
/// Calculates what level a table is nested inside other tables.
/// <returns>
/// An integer containing the level the table is nested at.
/// 0 = Table is not nested inside any other table
/// 1 = Table is nested within one parent table
/// 2 = Table is nested within two parent tables etc..</returns>
/// </summary>
private static int GetNestedDepthOfTable(Table table)
{
    int depth = 0;

    NodeType type = table.NodeType;
    // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Node parent = table.GetAncestor(type);

    while (parent != null)
    {
        // Every time we find a table a level up we increase the depth counter and then try to find an
        // ancestor of type table from the parent.
        depth++;
        parent = parent.GetAncestor(type);
    }

    return depth;
}

/// <summary>
/// Determines if a table contains any immediate child table within its cells.
/// Does not recursively traverse through those tables to check for further tables.
/// <returns>Returns true if at least one child cell contains a table.
/// Returns false if no cells in the table contains a table.</returns>
/// </summary>
private static int GetChildTableCount(Table table)
{
    int tableCount = 0;
    // Iterate through all child rows in the table
    foreach (Row row in table.Rows.OfType<Row>())
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells.OfType<Cell>())
        {
            // Retrieve the collection of child tables of this cell
            TableCollection childTables = Cell.Tables;

            // If this cell has a table as a child then return true
            if (childTables.Count > 0)
                tableCount++;
        }
    }

    // No cell contains a table
    return tableCount;
}

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

TableCollection Members | Aspose.Words.Tables Namespace


TableCollection Members

TableCollection overview

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Table at the given index.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all tables from the collection to a new array of tables.

See Also

TableCollection Class | Aspose.Words.Tables Namespace


TableCollection Properties

The properties of the TableCollection class are listed below. For a complete list of TableCollection class members, see the TableCollection Members topic.

Public Instance Properties

Count (inherited from NodeCollection) | Gets the number of nodes in the collection.
Item | Overloaded. Retrieves a Table at the given index.

See Also

TableCollection Class | Aspose.Words.Tables Namespace


Item Property

Aspose.Words

TableCollection.Item Property

Retrieves a Table at the given index.

[Visual Basic]
Overloads Public Default ReadOnly Property Item( _
ByVal index As Integer _
) As Table
[C#]
new public Table this[
int index
] {get;}

Parameters

index
An index into the collection.

Remarks

The index is zero-based.

Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

If index is greater than or equal to the number of items in the list, this returns a null reference.

If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

See Also

TableCollection Class | Aspose.Words.Tables Namespace


TableCollection Methods

The methods of the TableCollection class are listed below. For a complete list of TableCollection class members, see the TableCollection Members topic.

Public Instance Methods

Add (inherited from NodeCollection) | Adds a node to the end of the collection.
Clear (inherited from NodeCollection) | Removes all nodes from this collection and from the document.
Contains (inherited from NodeCollection) | Determines whether a node is in the collection.
GetEnumerator (inherited from IEnumerator<Node>) |
IndexOf (inherited from NodeCollection) | Returns the zero-based index of the specified node.
Insert (inherited from NodeCollection) | Inserts a node into the collection at the specified index.
Remove (inherited from NodeCollection) | Removes the node from the collection and from the document.
RemoveAt (inherited from NodeCollection) | Removes the node at the specified index from the collection and from the document.
ToArray | Copies all tables from the collection to a new array of tables.

See Also

TableCollection Class | Aspose.Words.Tables Namespace


TableCollection.ToArray Method

Copies all tables from the collection to a new array of tables.

[Visual Basic]
Public Function ToArray() As Table()
[C#]
new public Table[] ToArray();

Return Value

An array of tables.

See Also

TableCollection Class | Aspose.Words.Tables Namespace


TableStyleOptions Enumeration

Specifies how table style is applied to a table.

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

[Visual Basic]
Public Enum TableStyleOptions
[C#]
public enum TableStyleOptions

Remarks

Example

Shows how to build a new table with a table style applied.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions =
    TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Continue with building the table as normal.
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.SetTableStyle.docx");

Members

Member Name | Description | Value
None | No table style formatting is applied. | 0
FirstRow | Apply first row conditional formatting. | 32
LastRow | Apply last row conditional formatting. | 64
FirstColumn | Apply 1 first column conditional formatting. | 128
LastColumn | Apply last column conditional formatting. | 256
RowBands | Apply row banding conditional formatting. | 512
ColumnBands | Apply column banding conditional formatting. | 1024
Default2003 | Row and column banding is applied. This is Microsoft Word default for old formats such as DOC, WML and RTF. | 1536
Default | This is Microsoft Word defaults. | 672

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace | StyleOptions


TextWrapping Enumeration

Specifies how text is wrapped around the table.

[Visual Basic]
Public Enum TextWrapping
[C#]
public enum TextWrapping

Members

Member Name | Description | Value
None | Text and table is displayed in the order of their appearance in the document. | 0
Around | Text is wrapped around the table occupying available side space. | 1
Default | Default value. | 0

Requirements

Namespace: Aspose.Words.Tables

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Aspose.Words.Tables Namespace


Aspose.Words.Themes

Aspose.Words

Aspose.Words.Themes Namespace

The Aspose.Words.Themes namespace provides classes that allow to access theme information in Microsoft Word documents.

A document theme can specify fonts and colors to be used in a document. Themes are supported in Word 2007 and higher.

Namespace hierarchy

Classes

Class | Description
Theme | Represents document Theme, and provides access to main theme parts including MajorFonts, MinorFonts and Colors
ThemeColors | Represents the color scheme of the document theme which contains twelve colors. ThemeColors object contains six accent colors, two dark colors, two light colors and a color for each of a hyperlink and followed hyperlink.
ThemeFonts | Represents a collection of fonts in the font scheme, allowing to specify different fonts for different languages Latin, EastAsian and ComplexScript.


Theme Class

Represents document Theme, and provides access to main theme parts including MajorFonts, MinorFonts and Colors

For a list of all members of this type, see Theme Members.

System.Object
Aspose.Words.Themes.Theme

[Visual Basic]
Public Class Theme
[C#]
public class Theme

Example

Show how to change document theme options.

[C#]

Document doc = new Document();
// Get document theme and do something useful
Theme theme = doc.Theme;

theme.Colors.Accent1 = Color.Black;
theme.Colors.Dark1 = Color.Blue;
theme.Colors.FollowedHyperlink = Color.White;
theme.Colors.Hyperlink = Color.WhiteSmoke;
theme.Colors.Light1 = Color.Empty; //There is default Color.Black

theme.MajorFonts.ComplexScript = "Arial";
theme.MajorFonts.EastAsian = String.Empty;
theme.MajorFonts.Latin = "Times New Roman";

theme.MinorFonts.ComplexScript = String.Empty;
theme.MinorFonts.EastAsian = "Times New Roman";
theme.MinorFonts.Latin = "Arial";

Requirements

Namespace: Aspose.Words.Themes

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

Theme Members | Aspose.Words.Themes Namespace


Theme Members

Theme overview

Public Instance Constructors

Theme Constructor Initializes a new instance of the Theme class.

Public Instance Properties

Colors | Allows to specify the set of theme colors for the document.
MajorFonts | Allows to specify the set of major fonts for different languages.
MinorFonts | Allows to specify the set of minor fonts for different languages.

See Also

Theme Class | Aspose.Words.Themes Namespace


Theme Constructor

Initializes a new instance of the Theme class.

[Visual Basic]
Public Sub New()
[C#]
public Theme();

See Also

Theme Class | Aspose.Words.Themes Namespace


Theme Properties

The properties of the Theme class are listed below. For a complete list of Theme class members, see the Theme Members topic.

Public Instance Properties

Colors | Allows to specify the set of theme colors for the document.
MajorFonts | Allows to specify the set of major fonts for different languages.
MinorFonts | Allows to specify the set of minor fonts for different languages.

See Also

Theme Class | Aspose.Words.Themes Namespace


Colors Property

Aspose.Words

Theme.Colors Property

Allows to specify the set of theme colors for the document.

[Visual Basic]
Public ReadOnly Property Colors As ThemeColors
[C#]
public ThemeColors Colors {get;}

Example

Show how to change document theme options.

[C#]

Document doc = new Document();
// Get document theme and do something useful
Theme theme = doc.Theme;

theme.Colors.Accent1 = Color.Black;
theme.Colors.Dark1 = Color.Blue;
theme.Colors.FollowedHyperlink = Color.White;
theme.Colors.Hyperlink = Color.WhiteSmoke;
theme.Colors.Light1 = Color.Empty; //There is default Color.Black

theme.MajorFonts.ComplexScript = "Arial";
theme.MajorFonts.EastAsian = String.Empty;
theme.MajorFonts.Latin = "Times New Roman";

theme.MinorFonts.ComplexScript = String.Empty;
theme.MinorFonts.EastAsian = "Times New Roman";
theme.MinorFonts.Latin = "Arial";

See Also

Theme Class | Aspose.Words.Themes Namespace


MajorFonts Property

Aspose.Words

Theme.MajorFonts Property

Allows to specify the set of major fonts for different languages.

[Visual Basic]
Public ReadOnly Property MajorFonts As ThemeFonts
[C#]
public ThemeFonts MajorFonts {get;}

Example

Show how to change document theme options.

[C#]

Document doc = new Document();
// Get document theme and do something useful
Theme theme = doc.Theme;

theme.Colors.Accent1 = Color.Black;
theme.Colors.Dark1 = Color.Blue;
theme.Colors.FollowedHyperlink = Color.White;
theme.Colors.Hyperlink = Color.WhiteSmoke;
theme.Colors.Light1 = Color.Empty; //There is default Color.Black

theme.MajorFonts.ComplexScript = "Arial";
theme.MajorFonts.EastAsian = String.Empty;
theme.MajorFonts.Latin = "Times New Roman";

theme.MinorFonts.ComplexScript = String.Empty;
theme.MinorFonts.EastAsian = "Times New Roman";
theme.MinorFonts.Latin = "Arial";

See Also

Theme Class | Aspose.Words.Themes Namespace


MinorFonts Property

Aspose.Words

Theme.MinorFonts Property

Allows to specify the set of minor fonts for different languages.

[Visual Basic]
Public ReadOnly Property MinorFonts As ThemeFonts
[C#]
public ThemeFonts MinorFonts {get;}

Example

Show how to change document theme options.

[C#]

Document doc = new Document();
// Get document theme and do something useful
Theme theme = doc.Theme;

theme.Colors.Accent1 = Color.Black;
theme.Colors.Dark1 = Color.Blue;
theme.Colors.FollowedHyperlink = Color.White;
theme.Colors.Hyperlink = Color.WhiteSmoke;
theme.Colors.Light1 = Color.Empty; //There is default Color.Black

theme.MajorFonts.ComplexScript = "Arial";
theme.MajorFonts.EastAsian = String.Empty;
theme.MajorFonts.Latin = "Times New Roman";

theme.MinorFonts.ComplexScript = String.Empty;
theme.MinorFonts.EastAsian = "Times New Roman";
theme.MinorFonts.Latin = "Arial";

See Also

Theme Class | Aspose.Words.Themes Namespace


ThemeColors Class

Represents the color scheme of the document theme which contains twelve colors.

ThemeColors object contains six accent colors, two dark colors, two light colors and a color for each of a hyperlink and followed hyperlink.

For a list of all members of this type, see ThemeColors Members.

System.Object
Aspose.Words.Themes.ThemeColors

[Visual Basic]
Public Class ThemeColors
[C#]
public class ThemeColors

Requirements

Namespace: Aspose.Words.Themes

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ThemeColors Members | Aspose.Words.Themes Namespace


ThemeColors Members

ThemeColors overview

Public Instance Properties

Accent1 | Specifies color Accent 1.
Accent2 | Specifies color Accent 2.
Accent3 | Specifies color Accent 3.
Accent4 | Specifies color Accent 4.
Accent5 | Specifies color Accent 5.
Accent6 | Specifies color Accent 6.
Dark1 | Specifies color Dark 1.
Dark2 | Specifies color Dark 2.
FollowedHyperlink | Specifies color for a clicked hyperlink.
Hyperlink | Specifies color for a hyperlink.
Light1 | Specifies color Light 1.
Light2 | Specifies color Light 2.

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


ThemeColors Properties

The properties of the ThemeColors class are listed below. For a complete list of ThemeColors class members, see the ThemeColors Members topic.

Public Instance Properties

Accent1 | Specifies color Accent 1.
Accent2 | Specifies color Accent 2.
Accent3 | Specifies color Accent 3.
Accent4 | Specifies color Accent 4.
Accent5 | Specifies color Accent 5.
Accent6 | Specifies color Accent 6.
Dark1 | Specifies color Dark 1.
Dark2 | Specifies color Dark 2.
FollowedHyperlink | Specifies color for a clicked hyperlink.
Hyperlink | Specifies color for a hyperlink.
Light1 | Specifies color Light 1.
Light2 | Specifies color Light 2.

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Accent1 Property

Aspose.Words

ThemeColors.Accent1 Property

Specifies color Accent 1.

[Visual Basic]
Public Property Accent1 As Color
[C#]
public Color Accent1 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Accent2 Property

Aspose.Words

ThemeColors.Accent2 Property

Specifies color Accent 2.

[Visual Basic]
Public Property Accent2 As Color
[C#]
public Color Accent2 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Accent3 Property

Aspose.Words

ThemeColors.Accent3 Property

Specifies color Accent 3.

[Visual Basic]
Public Property Accent3 As Color
[C#]
public Color Accent3 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Accent4 Property

Aspose.Words

ThemeColors.Accent4 Property

Specifies color Accent 4.

[Visual Basic]
Public Property Accent4 As Color
[C#]
public Color Accent4 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Accent5 Property

Aspose.Words

ThemeColors.Accent5 Property

Specifies color Accent 5.

[Visual Basic]
Public Property Accent5 As Color
[C#]
public Color Accent5 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Accent6 Property

Aspose.Words

ThemeColors.Accent6 Property

Specifies color Accent 6.

[Visual Basic]
Public Property Accent6 As Color
[C#]
public Color Accent6 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Dark1 Property

Aspose.Words

ThemeColors.Dark1 Property

Specifies color Dark 1.

[Visual Basic]
Public Property Dark1 As Color
[C#]
public Color Dark1 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Dark2 Property

Aspose.Words

ThemeColors.Dark2 Property

Specifies color Dark 2.

[Visual Basic]
Public Property Dark2 As Color
[C#]
public Color Dark2 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


FollowedHyperlink Property

Aspose.Words

ThemeColors.FollowedHyperlink Property

Specifies color for a clicked hyperlink.

[Visual Basic]
Public Property FollowedHyperlink As Color
[C#]
public Color FollowedHyperlink {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Hyperlink Property

Aspose.Words

ThemeColors.Hyperlink Property

Specifies color for a hyperlink.

[Visual Basic]
Public Property Hyperlink As Color
[C#]
public Color Hyperlink {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Light1 Property

Aspose.Words

ThemeColors.Light1 Property

Specifies color Light 1.

[Visual Basic]
Public Property Light1 As Color
[C#]
public Color Light1 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


Light2 Property

Aspose.Words

ThemeColors.Light2 Property

Specifies color Light 2.

[Visual Basic]
Public Property Light2 As Color
[C#]
public Color Light2 {get; set;}

See Also

ThemeColors Class | Aspose.Words.Themes Namespace


ThemeFonts Class

Represents a collection of fonts in the font scheme, allowing to specify different fonts for different languages Latin, EastAsian and ComplexScript.

For a list of all members of this type, see ThemeFonts Members.

System.Object
Aspose.Words.Themes.ThemeFonts

[Visual Basic]
Public Class ThemeFonts
[C#]
public class ThemeFonts

Requirements

Namespace: Aspose.Words.Themes

Assembly: Aspose.Words (in Aspose.Words.dll)

See Also

ThemeFonts Members | Aspose.Words.Themes Namespace


ThemeFonts Members

ThemeFonts overview

Public Instance Properties

ComplexScript | Specifies font name for ComplexScript characters.
EastAsian | Specifies font name for EastAsian characters.
Latin | Specifies font name for Latin characters.

See Also

ThemeFonts Class | Aspose.Words.Themes Namespace


ThemeFonts Properties

The properties of the ThemeFonts class are listed below. For a complete list of ThemeFonts class members, see the ThemeFonts Members topic.

Public Instance Properties

ComplexScript | Specifies font name for ComplexScript characters.
EastAsian | Specifies font name for EastAsian characters.
Latin | Specifies font name for Latin characters.

See Also

ThemeFonts Class | Aspose.Words.Themes Namespace


ComplexScript Property

Aspose.Words

ThemeFonts.ComplexScript Property

Specifies font name for ComplexScript characters.

[Visual Basic]
Public Property ComplexScript As String
[C#]
public string ComplexScript {get; set;}

See Also

ThemeFonts Class | Aspose.Words.Themes Namespace


EastAsian Property

Aspose.Words

ThemeFonts.EastAsian Property

Specifies font name for EastAsian characters.

[Visual Basic]
Public Property EastAsian As String
[C#]
public string EastAsian {get; set;}

See Also

ThemeFonts Class | Aspose.Words.Themes Namespace


Latin Property

Aspose.Words

ThemeFonts.Latin Property

Specifies font name for Latin characters.

[Visual Basic]
Public Property Latin As String
[C#]
public string Latin {get; set;}

See Also

ThemeFonts Class | Aspose.Words.Themes Namespace


Aspose.Words.BuildingBlocksHierarchy

Aspose.Words

Aspose.Words.BuildingBlocks Hierarchy

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.BuildingBlocks.BuildingBlock
Aspose.Words.DocumentBase
Aspose.Words.BuildingBlocks.GlossaryDocument
Aspose.Words.NodeCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.BuildingBlocks.BuildingBlockCollection
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.BuildingBlocks.BuildingBlockBehavior
Aspose.Words.BuildingBlocks.BuildingBlockGallery
Aspose.Words.BuildingBlocks.BuildingBlockType

See Also

Aspose.Words.BuildingBlocks Namespace


CompositeNode Hierarchy

System.Object
Node
CompositeNode
BuildingBlock
DocumentBase
ShapeBase
InlineStory
SmartTag
StructuredDocumentTag
OfficeMath
Paragraph
Section
Story
Cell
Row
Table

See Also

CompositeNode Class | CompositeNode Members | Aspose.Words Namespace


Aspose.Words.Drawing.ChartsHierarchy

Aspose.Words

Aspose.Words.Drawing.Charts Hierarchy

System.Object
Aspose.Words.Drawing.Charts.AxisBound
Aspose.Words.Drawing.Charts.AxisDisplayUnit
Aspose.Words.Drawing.Charts.AxisScaling
Aspose.Words.Drawing.Charts.Chart
Aspose.Words.Drawing.Charts.ChartAxis
Aspose.Words.Drawing.Charts.ChartDataLabel
Aspose.Words.Drawing.Charts.ChartDataLabelCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Drawing.Charts.ChartDataLabel, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Drawing.Charts.ChartDataPoint ---- Aspose.Words.Drawing.Charts.IChartDataPoint
Aspose.Words.Drawing.Charts.ChartDataPointCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Drawing.Charts.ChartDataPoint, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Drawing.Charts.ChartLegend
Aspose.Words.Drawing.Charts.ChartMarker
Aspose.Words.Drawing.Charts.ChartNumberFormat
Aspose.Words.Drawing.Charts.ChartSeries ---- Aspose.Words.Drawing.Charts.IChartDataPoint
Aspose.Words.Drawing.Charts.ChartSeriesCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Drawing.Charts.ChartSeries, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Drawing.Charts.ChartTitle
Aspose.Words.Drawing.Charts.IChartDataPoint
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Drawing.Charts.AxisBuiltInUnit
Aspose.Words.Drawing.Charts.AxisCategoryType
Aspose.Words.Drawing.Charts.AxisCrosses
Aspose.Words.Drawing.Charts.AxisScaleType
Aspose.Words.Drawing.Charts.AxisTickLabelPosition
Aspose.Words.Drawing.Charts.AxisTickMark
Aspose.Words.Drawing.Charts.AxisTimeUnit
Aspose.Words.Drawing.Charts.ChartAxisType
Aspose.Words.Drawing.Charts.ChartType
Aspose.Words.Drawing.Charts.LegendPosition
Aspose.Words.Drawing.Charts.MarkerSymbol

See Also

Aspose.Words.Drawing.Charts Namespace


Aspose.Words.Drawing.OleHierarchy

Aspose.Words

Aspose.Words.Drawing.Ole Hierarchy

System.Object
Aspose.Words.Drawing.Ole.Forms2OleControlCollection
Aspose.Words.Drawing.Ole.OleControl
Aspose.Words.Drawing.Ole.Forms2OleControl
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Drawing.Ole.Forms2OleControlType

See Also

Aspose.Words.Drawing.Ole Namespace


Aspose.Words.DrawingHierarchy

Aspose.Words

Aspose.Words.Drawing Hierarchy

System.Object
Aspose.Words.Drawing.Fill
Aspose.Words.Drawing.ImageData
Aspose.Words.Drawing.ImageSize
Aspose.Words.Drawing.OleFormat
Aspose.Words.Drawing.OlePackage
Aspose.Words.Drawing.SignatureLine
Aspose.Words.Drawing.Stroke
Aspose.Words.Drawing.TextBox
Aspose.Words.Drawing.TextPath
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Drawing.ShapeBase
Aspose.Words.Drawing.GroupShape
Aspose.Words.Drawing.Shape
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Drawing.ArrowLength
Aspose.Words.Drawing.ArrowType
Aspose.Words.Drawing.ArrowWidth
Aspose.Words.Drawing.DashStyle
Aspose.Words.Drawing.EndCap
Aspose.Words.Drawing.FlipOrientation
Aspose.Words.Drawing.HorizontalAlignment
Aspose.Words.Drawing.ImageType
Aspose.Words.Drawing.JoinStyle
Aspose.Words.Drawing.LayoutFlow
Aspose.Words.Drawing.RelativeHorizontalPosition
Aspose.Words.Drawing.RelativeVerticalPosition
Aspose.Words.Drawing.ShapeLineStyle
Aspose.Words.Drawing.ShapeMarkupLanguage
Aspose.Words.Drawing.ShapeType
Aspose.Words.Drawing.TextBoxAnchor
Aspose.Words.Drawing.TextBoxWrapMode
Aspose.Words.Drawing.TextPathAlignment
Aspose.Words.Drawing.VerticalAlignment
Aspose.Words.Drawing.WrapSide
Aspose.Words.Drawing.WrapType

See Also

Aspose.Words.Drawing Namespace


Field Hierarchy

System.Object
Field
FieldAddIn
FieldAddressBlock
FieldAdvance
FieldAsk
FieldAuthor
FieldAutoNum
FieldAutoNumLgl
FieldAutoNumOut
FieldAutoText
FieldAutoTextList
FieldBarcode
FieldBibliography
FieldBidiOutline
FieldCitation
FieldComments
FieldCompare
FieldCreateDate
FieldData
FieldDatabase
FieldDate
FieldDde
FieldDdeAuto
FieldDisplayBarcode
FieldDocProperty
FieldDocVariable
FieldEditTime
FieldEmbed
FieldEQ
FieldFileName
FieldFileSize
FieldFillIn
FieldFootnoteRef
FieldFormCheckBox
FieldFormDropDown
FieldFormText
FieldFormula
FieldGlossary
FieldGoToButton
FieldGreetingLine
FieldHyperlink
FieldIf
FieldImport
FieldInclude
FieldIncludePicture
FieldIncludeText
FieldIndex
FieldInfo
FieldKeywords
FieldLastSavedBy
FieldLink
FieldListNum
FieldMacroButton
FieldMergeBarcode
FieldMergeField
FieldMergeRec
FieldMergeSeq
FieldNext
FieldNextIf
FieldNoteRef
FieldNumChars
FieldNumPages
FieldNumWords
FieldOcx
FieldPage
FieldPageRef
FieldPrint
FieldPrintDate
FieldPrivate
FieldQuote
FieldRD
FieldRef
FieldRevNum
FieldSaveDate
FieldSection
FieldSectionPages
FieldSeq
FieldSet
FieldShape
FieldSkipIf
FieldStyleRef
FieldSubject
FieldSymbol
FieldTA
FieldTC
FieldTemplate
FieldTime
FieldTitle
FieldToa
FieldToc
FieldUnknown
FieldUserAddress
FieldUserInitials
FieldUserName
FieldXE

See Also

Field Class | Field Members | Aspose.Words.Fields Namespace


Aspose.Words.FieldsHierarchy

Aspose.Words

Aspose.Words.Fields Hierarchy

System.Object
Aspose.Words.Fields.BarcodeParameters
Aspose.Words.Fields.DropDownItemCollection ---- System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Collections.IEnumerable
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldAddIn
Aspose.Words.Fields.FieldAddressBlock
Aspose.Words.Fields.FieldAdvance
Aspose.Words.Fields.FieldAsk
Aspose.Words.Fields.FieldAuthor
Aspose.Words.Fields.FieldAutoNum
Aspose.Words.Fields.FieldAutoNumLgl
Aspose.Words.Fields.FieldAutoNumOut
Aspose.Words.Fields.FieldAutoText
Aspose.Words.Fields.FieldAutoTextList
Aspose.Words.Fields.FieldBarcode
Aspose.Words.Fields.FieldBibliography
Aspose.Words.Fields.FieldBidiOutline
Aspose.Words.Fields.FieldCitation
Aspose.Words.Fields.FieldComments
Aspose.Words.Fields.FieldCompare
Aspose.Words.Fields.FieldCreateDate
Aspose.Words.Fields.FieldData
Aspose.Words.Fields.FieldDatabase
Aspose.Words.Fields.FieldDate
Aspose.Words.Fields.FieldDde
Aspose.Words.Fields.FieldDdeAuto
Aspose.Words.Fields.FieldDisplayBarcode
Aspose.Words.Fields.FieldDocProperty
Aspose.Words.Fields.FieldDocVariable
Aspose.Words.Fields.FieldEditTime
Aspose.Words.Fields.FieldEmbed
Aspose.Words.Fields.FieldEQ
Aspose.Words.Fields.FieldFileName
Aspose.Words.Fields.FieldFileSize
Aspose.Words.Fields.FieldFillIn
Aspose.Words.Fields.FieldFootnoteRef
Aspose.Words.Fields.FieldFormCheckBox
Aspose.Words.Fields.FieldFormDropDown
Aspose.Words.Fields.FieldFormText
Aspose.Words.Fields.FieldFormula
Aspose.Words.Fields.FieldGlossary
Aspose.Words.Fields.FieldGoToButton
Aspose.Words.Fields.FieldGreetingLine
Aspose.Words.Fields.FieldHyperlink
Aspose.Words.Fields.FieldIf
Aspose.Words.Fields.FieldImport
Aspose.Words.Fields.FieldInclude
Aspose.Words.Fields.FieldIncludePicture
Aspose.Words.Fields.FieldIncludeText
Aspose.Words.Fields.FieldIndex
Aspose.Words.Fields.FieldInfo
Aspose.Words.Fields.FieldKeywords
Aspose.Words.Fields.FieldLastSavedBy
Aspose.Words.Fields.FieldLink
Aspose.Words.Fields.FieldListNum
Aspose.Words.Fields.FieldMacroButton
Aspose.Words.Fields.FieldMergeBarcode
Aspose.Words.Fields.FieldMergeField
Aspose.Words.Fields.FieldMergeRec
Aspose.Words.Fields.FieldMergeSeq
Aspose.Words.Fields.FieldNext
Aspose.Words.Fields.FieldNextIf
Aspose.Words.Fields.FieldNoteRef
Aspose.Words.Fields.FieldNumChars
Aspose.Words.Fields.FieldNumPages
Aspose.Words.Fields.FieldNumWords
Aspose.Words.Fields.FieldOcx
Aspose.Words.Fields.FieldPage
Aspose.Words.Fields.FieldPageRef
Aspose.Words.Fields.FieldPrint
Aspose.Words.Fields.FieldPrintDate
Aspose.Words.Fields.FieldPrivate
Aspose.Words.Fields.FieldQuote
Aspose.Words.Fields.FieldRD
Aspose.Words.Fields.FieldRef
Aspose.Words.Fields.FieldRevNum
Aspose.Words.Fields.FieldSaveDate
Aspose.Words.Fields.FieldSection
Aspose.Words.Fields.FieldSectionPages
Aspose.Words.Fields.FieldSeq
Aspose.Words.Fields.FieldSet
Aspose.Words.Fields.FieldShape
Aspose.Words.Fields.FieldSkipIf
Aspose.Words.Fields.FieldStyleRef
Aspose.Words.Fields.FieldSubject
Aspose.Words.Fields.FieldSymbol
Aspose.Words.Fields.FieldTA
Aspose.Words.Fields.FieldTC
Aspose.Words.Fields.FieldTemplate
Aspose.Words.Fields.FieldTime
Aspose.Words.Fields.FieldTitle
Aspose.Words.Fields.FieldToa
Aspose.Words.Fields.FieldToc
Aspose.Words.Fields.FieldUnknown
Aspose.Words.Fields.FieldUserAddress
Aspose.Words.Fields.FieldUserInitials
Aspose.Words.Fields.FieldUserName
Aspose.Words.Fields.FieldXE
Aspose.Words.Fields.FieldArgumentBuilder
Aspose.Words.Fields.FieldBuilder
Aspose.Words.Fields.FieldCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Fields.Field, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Fields.FieldFormat
Aspose.Words.Fields.FieldOptions
Aspose.Words.Fields.FormFieldCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Fields.FormField, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Fields.GeneralFormatCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Fields.GeneralFormat, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Fields.IBarcodeGenerator
Aspose.Words.Fields.IFieldResultFormatter
Aspose.Words.Fields.IFieldUpdateCultureProvider
Aspose.Words.Fields.IFieldUserPromptRespondent
Aspose.Words.Fields.MergeFieldImageDimension
Aspose.Words.Fields.ToaCategories
Aspose.Words.Fields.UserInformation
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.SpecialChar
Aspose.Words.Fields.FieldChar
Aspose.Words.Fields.FieldEnd
Aspose.Words.Fields.FieldSeparator
Aspose.Words.Fields.FieldStart
Aspose.Words.Fields.FormField
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Fields.FieldIfComparisonResult
Aspose.Words.Fields.FieldType
Aspose.Words.Fields.FieldUpdateCultureSource
Aspose.Words.Fields.GeneralFormat
Aspose.Words.Fields.MergeFieldImageDimensionUnit
Aspose.Words.Fields.TextFormFieldType

See Also

Aspose.Words.Fields Namespace


Aspose.Words.FontsHierarchy

Aspose.Words

Aspose.Words.Fonts Hierarchy

System.Object
Aspose.Words.Fonts.FontFallbackSettings
Aspose.Words.Fonts.FontInfo
Aspose.Words.Fonts.FontInfoCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Fonts.FontInfo, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Fonts.FontSettings
Aspose.Words.Fonts.FontSourceBase
Aspose.Words.Fonts.FileFontSource
Aspose.Words.Fonts.FolderFontSource
Aspose.Words.Fonts.MemoryFontSource
Aspose.Words.Fonts.StreamFontSource
Aspose.Words.Fonts.SystemFontSource
Aspose.Words.Fonts.FontSubstitutionRule
Aspose.Words.Fonts.DefaultFontSubstitutionRule
Aspose.Words.Fonts.FontConfigSubstitutionRule
Aspose.Words.Fonts.FontInfoSubstitutionRule
Aspose.Words.Fonts.TableSubstitutionRule
Aspose.Words.Fonts.FontSubstitutionSettings
Aspose.Words.Fonts.PhysicalFontInfo
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Fonts.EmbeddedFontFormat
Aspose.Words.Fonts.EmbeddedFontStyle
Aspose.Words.Fonts.FontFamily
Aspose.Words.Fonts.FontPitch
Aspose.Words.Fonts.FontSourceType

See Also

Aspose.Words.Fonts Namespace


Aspose.Words.LayoutHierarchy

Aspose.Words

Aspose.Words.Layout Hierarchy

System.Object
Aspose.Words.Layout.LayoutCollector
Aspose.Words.Layout.LayoutEnumerator
Aspose.Words.Layout.LayoutOptions
Aspose.Words.Layout.RevisionOptions
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Layout.LayoutEntityType
Aspose.Words.Layout.RevisionColor
Aspose.Words.Layout.RevisionTextEffect
Aspose.Words.Layout.ShowInBalloons

See Also

Aspose.Words.Layout Namespace


Aspose.Words.ListsHierarchy

Aspose.Words

Aspose.Words.Lists Hierarchy

System.Object
Aspose.Words.Lists.List ---- System.IComparable
Aspose.Words.Lists.ListCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Lists.List, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Lists.ListLabel
Aspose.Words.Lists.ListLevel
Aspose.Words.Lists.ListLevelCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Lists.ListLevel, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Lists.ListLevelAlignment
Aspose.Words.Lists.ListTemplate
Aspose.Words.Lists.ListTrailingCharacter

See Also

Aspose.Words.Lists Namespace


Aspose.Words.LoadingHierarchy

Aspose.Words

Aspose.Words.Loading Hierarchy

System.Object
Aspose.Words.Loading.IResourceLoadingCallback
Aspose.Words.Loading.ResourceLoadingArgs
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Loading.ResourceLoadingAction
Aspose.Words.Loading.ResourceType

See Also

Aspose.Words.Loading Namespace


Aspose.Words.MailMergingHierarchy

Aspose.Words

Aspose.Words.MailMerging Hierarchy

System.Object
Aspose.Words.MailMerging.FieldMergingArgsBase
Aspose.Words.MailMerging.FieldMergingArgs
Aspose.Words.MailMerging.ImageFieldMergingArgs
Aspose.Words.MailMerging.IFieldMergingCallback
Aspose.Words.MailMerging.IMailMergeCallback
Aspose.Words.MailMerging.IMailMergeDataSource
Aspose.Words.MailMerging.IMailMergeDataSourceRoot
Aspose.Words.MailMerging.MailMerge
Aspose.Words.MailMerging.MailMergeRegionInfo
Aspose.Words.MailMerging.MappedDataFieldCollection ---- System.Collections.Generic.IEnumerable`1[[System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Collections.IEnumerable
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.MailMerging.MailMergeCleanupOptions
Aspose.Words.MailMerging.MailMergeRtlCleanupMode

See Also

Aspose.Words.MailMerging Namespace


Aspose.Words.MarkupHierarchy

Aspose.Words

Aspose.Words.Markup Hierarchy

System.Object
Aspose.Words.Markup.CustomPart
Aspose.Words.Markup.CustomPartCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Markup.CustomPart, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Markup.CustomXmlPart
Aspose.Words.Markup.CustomXmlPartCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Markup.CustomXmlPart, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Markup.CustomXmlProperty
Aspose.Words.Markup.CustomXmlPropertyCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Markup.CustomXmlProperty, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Markup.CustomXmlSchemaCollection ---- System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Collections.IEnumerable
Aspose.Words.Markup.SdtListItem
Aspose.Words.Markup.SdtListItemCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Markup.SdtListItem, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Markup.XmlMapping
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Markup.SmartTag
Aspose.Words.Markup.StructuredDocumentTag
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Markup.MarkupLevel
Aspose.Words.Markup.SdtCalendarType
Aspose.Words.Markup.SdtDateStorageFormat
Aspose.Words.Markup.SdtType

See Also

Aspose.Words.Markup Namespace


Aspose.Words.MathHierarchy

Aspose.Words

Aspose.Words.Math Hierarchy

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Math.OfficeMath
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Math.MathObjectType
Aspose.Words.Math.OfficeMathDisplayType
Aspose.Words.Math.OfficeMathJustification

See Also

Aspose.Words.Math Namespace


NodeCollection Hierarchy

System.Object
NodeCollection
BuildingBlockCollection
CommentCollection
HeaderFooterCollection
ParagraphCollection
RunCollection
SectionCollection
CellCollection
RowCollection
TableCollection

See Also

NodeCollection Class | NodeCollection Members | Aspose.Words Namespace


Node Hierarchy

System.Object
Node
BookmarkEnd
BookmarkStart
CommentRangeEnd
CommentRangeStart
CompositeNode
EditableRangeEnd
EditableRangeStart
Inline
SubDocument

See Also

Node Class | Node Members | Aspose.Words Namespace


Aspose.Words.PropertiesHierarchy

Aspose.Words

Aspose.Words.Properties Hierarchy

System.Object
Aspose.Words.Properties.DocumentProperty
Aspose.Words.Properties.DocumentPropertyCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Properties.DocumentProperty, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Properties.BuiltInDocumentProperties
Aspose.Words.Properties.CustomDocumentProperties
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Properties.DocumentSecurity
Aspose.Words.Properties.PropertyType

See Also

Aspose.Words.Properties Namespace


Aspose.Words.RenderingHierarchy

Aspose.Words

Aspose.Words.Rendering Hierarchy

System.Object
Aspose.Words.Rendering.NodeRendererBase
Aspose.Words.Rendering.OfficeMathRenderer
Aspose.Words.Rendering.ShapeRenderer
Aspose.Words.Rendering.PageInfo
Aspose.Words.Rendering.PrinterSettingsContainer
Aspose.Words.Rendering.ThumbnailGeneratingOptions
System.MarshalByRefObject
System.ComponentModel.Component ---- System.ComponentModel.IComponent, System.IDisposable
System.Drawing.Printing.PrintDocument
Aspose.Words.Rendering.AsposeWordsPrintDocument

See Also

Aspose.Words.Rendering Namespace


Aspose.Words.ReplacingHierarchy

Aspose.Words

Aspose.Words.Replacing Hierarchy

System.Object
Aspose.Words.Replacing.FindReplaceOptions
Aspose.Words.Replacing.IReplacingCallback
Aspose.Words.Replacing.ReplacingArgs
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Replacing.ReplaceAction

See Also

Aspose.Words.Replacing Namespace


Aspose.Words.ReportingHierarchy

Aspose.Words

Aspose.Words.Reporting Hierarchy

System.Object
Aspose.Words.Reporting.KnownTypeSet ---- System.Collections.Generic.IEnumerable`1[[System.Type, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Collections.IEnumerable
Aspose.Words.Reporting.ReportingEngine
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Reporting.ReportBuildOptions

See Also

Aspose.Words.Reporting Namespace


FixedPageSaveOptions Hierarchy

System.Object
SaveOptions
FixedPageSaveOptions
HtmlFixedSaveOptions
ImageSaveOptions
PclSaveOptions
PdfSaveOptions
PsSaveOptions
SvgSaveOptions
XamlFixedSaveOptions
XpsSaveOptions

See Also

FixedPageSaveOptions Class | FixedPageSaveOptions Members | Aspose.Words.Saving Namespace


SaveOptions Hierarchy

System.Object
SaveOptions
DocSaveOptions
FixedPageSaveOptions
HtmlSaveOptions
OdtSaveOptions
OoxmlSaveOptions
RtfSaveOptions
TxtSaveOptionsBase
WordML2003SaveOptions
XamlFlowSaveOptions

See Also

SaveOptions Class | SaveOptions Members | Aspose.Words.Saving Namespace


Aspose.Words.SavingHierarchy

Aspose.Words

Aspose.Words.Saving Hierarchy

System.Object
Aspose.Words.Saving.BookmarksOutlineLevelCollection ---- System.Collections.Generic.IEnumerable`1[[System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Collections.IEnumerable
Aspose.Words.Saving.CssSavingArgs
Aspose.Words.Saving.DocumentPartSavingArgs
Aspose.Words.Saving.DownsampleOptions
Aspose.Words.Saving.FontSavingArgs
Aspose.Words.Saving.GraphicsQualityOptions
Aspose.Words.Saving.ICssSavingCallback
Aspose.Words.Saving.IDocumentPartSavingCallback
Aspose.Words.Saving.IFontSavingCallback
Aspose.Words.Saving.IImageSavingCallback
Aspose.Words.Saving.ImageSavingArgs
Aspose.Words.Saving.IPageSavingCallback
Aspose.Words.Saving.IResourceSavingCallback
Aspose.Words.Saving.MetafileRenderingOptions
Aspose.Words.Saving.OutlineOptions
Aspose.Words.Saving.PageSavingArgs
Aspose.Words.Saving.PdfDigitalSignatureDetails
Aspose.Words.Saving.PdfDigitalSignatureTimestampSettings
Aspose.Words.Saving.PdfEncryptionDetails
Aspose.Words.Saving.ResourceSavingArgs
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.DocSaveOptions
Aspose.Words.Saving.FixedPageSaveOptions
Aspose.Words.Saving.HtmlFixedSaveOptions
Aspose.Words.Saving.ImageSaveOptions
Aspose.Words.Saving.PclSaveOptions
Aspose.Words.Saving.PdfSaveOptions
Aspose.Words.Saving.PsSaveOptions
Aspose.Words.Saving.SvgSaveOptions
Aspose.Words.Saving.XamlFixedSaveOptions
Aspose.Words.Saving.XpsSaveOptions
Aspose.Words.Saving.HtmlSaveOptions
Aspose.Words.Saving.OdtSaveOptions
Aspose.Words.Saving.OoxmlSaveOptions
Aspose.Words.Saving.RtfSaveOptions
Aspose.Words.Saving.TxtSaveOptionsBase
Aspose.Words.Saving.TxtSaveOptions
Aspose.Words.Saving.WordML2003SaveOptions
Aspose.Words.Saving.XamlFlowSaveOptions
Aspose.Words.Saving.SaveOutputParameters
Aspose.Words.Saving.TxtListIndentation
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Saving.ColorMode
Aspose.Words.Saving.CssStyleSheetType
Aspose.Words.Saving.DmlEffectsRenderingMode
Aspose.Words.Saving.DmlRenderingMode
Aspose.Words.Saving.DocumentSplitCriteria
Aspose.Words.Saving.EmfPlusDualRenderingMode
Aspose.Words.Saving.ExportFontFormat
Aspose.Words.Saving.ExportHeadersFootersMode
Aspose.Words.Saving.ExportListLabels
Aspose.Words.Saving.HeaderFooterBookmarksExportMode
Aspose.Words.Saving.HtmlElementSizeOutputMode
Aspose.Words.Saving.HtmlFixedPageHorizontalAlignment
Aspose.Words.Saving.HtmlMetafileFormat
Aspose.Words.Saving.HtmlOfficeMathOutputMode
Aspose.Words.Saving.HtmlVersion
Aspose.Words.Saving.ImageBinarizationMethod
Aspose.Words.Saving.ImageColorMode
Aspose.Words.Saving.ImagePixelFormat
Aspose.Words.Saving.MetafileRenderingMode
Aspose.Words.Saving.NumeralFormat
Aspose.Words.Saving.OdtSaveMeasureUnit
Aspose.Words.Saving.OoxmlCompliance
Aspose.Words.Saving.PdfCompliance
Aspose.Words.Saving.PdfCustomPropertiesExport
Aspose.Words.Saving.PdfDigitalSignatureHashAlgorithm
Aspose.Words.Saving.PdfEncryptionAlgorithm
Aspose.Words.Saving.PdfFontEmbeddingMode
Aspose.Words.Saving.PdfImageColorSpaceExportMode
Aspose.Words.Saving.PdfImageCompression
Aspose.Words.Saving.PdfPageMode
Aspose.Words.Saving.PdfPermissions
Aspose.Words.Saving.PdfTextCompression
Aspose.Words.Saving.PdfZoomBehavior
Aspose.Words.Saving.SvgTextOutputMode
Aspose.Words.Saving.TiffCompression
Aspose.Words.Saving.TxtExportHeadersFootersMode

See Also

Aspose.Words.Saving Namespace


Aspose.Words.SettingsHierarchy

Aspose.Words

Aspose.Words.Settings Hierarchy

System.Object
Aspose.Words.Settings.CompatibilityOptions
Aspose.Words.Settings.HyphenationOptions
Aspose.Words.Settings.MailMergeSettings
Aspose.Words.Settings.Odso
Aspose.Words.Settings.OdsoFieldMapData
Aspose.Words.Settings.OdsoFieldMapDataCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Settings.OdsoFieldMapData, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Settings.OdsoRecipientData
Aspose.Words.Settings.OdsoRecipientDataCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Settings.OdsoRecipientData, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Settings.ViewOptions
Aspose.Words.Settings.WriteProtection
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Settings.Compatibility
Aspose.Words.Settings.MailMergeCheckErrors
Aspose.Words.Settings.MailMergeDataType
Aspose.Words.Settings.MailMergeDestination
Aspose.Words.Settings.MailMergeMainDocumentType
Aspose.Words.Settings.MsWordVersion
Aspose.Words.Settings.MultiplePagesType
Aspose.Words.Settings.OdsoDataSourceType
Aspose.Words.Settings.OdsoFieldMappingType
Aspose.Words.Settings.ViewType
Aspose.Words.Settings.ZoomType

See Also

Aspose.Words.Settings Namespace


Aspose.Words.ShapingHierarchy

Aspose.Words

Aspose.Words.Shaping Hierarchy

System.Object
Aspose.Words.Shaping.BasicTextShaperCache ---- Aspose.Words.Shaping.ITextShaperFactory, System.IDisposable
Aspose.Words.Shaping.Cluster
Aspose.Words.Shaping.Glyph
Aspose.Words.Shaping.ITextShaper ---- System.IDisposable
Aspose.Words.Shaping.ITextShaperFactory
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Shaping.Direction
Aspose.Words.Shaping.FontFeature
Aspose.Words.Shaping.Script

See Also

Aspose.Words.Shaping Namespace


Aspose.Words.TablesHierarchy

Aspose.Words

Aspose.Words.Tables Hierarchy

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Tables.Cell
Aspose.Words.Tables.Row
Aspose.Words.Tables.Table
Aspose.Words.NodeCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.Tables.CellCollection
Aspose.Words.Tables.RowCollection
Aspose.Words.Tables.TableCollection
Aspose.Words.Tables.CellFormat
Aspose.Words.Tables.PreferredWidth
Aspose.Words.Tables.RowFormat
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Tables.AutoFitBehavior
Aspose.Words.Tables.CellMerge
Aspose.Words.Tables.CellVerticalAlignment
Aspose.Words.Tables.PreferredWidthType
Aspose.Words.Tables.TableAlignment
Aspose.Words.Tables.TableStyleOptions
Aspose.Words.Tables.TextWrapping

See Also

Aspose.Words.Tables Namespace


Aspose.Words.ThemesHierarchy

Aspose.Words

Aspose.Words.Themes Hierarchy

System.Object
Aspose.Words.Themes.Theme
Aspose.Words.Themes.ThemeColors
Aspose.Words.Themes.ThemeFonts

See Also

Aspose.Words.Themes Namespace


Aspose.WordsHierarchy

Aspose.Words

Aspose.Words Hierarchy

System.Object
Aspose.Words.Bookmark
Aspose.Words.BookmarkCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Bookmark, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.BorderCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Border, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.BuildVersionInfo
Aspose.Words.CertificateHolder
Aspose.Words.CleanupOptions
Aspose.Words.ComHelper
Aspose.Words.CompareOptions
Aspose.Words.ConditionalStyle
Aspose.Words.ConditionalStyleCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.ConditionalStyle, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.ControlChar
Aspose.Words.ConvertUtil
Aspose.Words.DigitalSignature
Aspose.Words.DigitalSignatureCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.DigitalSignature, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.DigitalSignatureUtil
Aspose.Words.DocumentBuilder
Aspose.Words.DocumentVisitor
Aspose.Words.EditableRange
Aspose.Words.EndnoteOptions
Aspose.Words.FileFormatInfo
Aspose.Words.FileFormatUtil
Aspose.Words.Font
Aspose.Words.FootnoteOptions
Aspose.Words.FrameFormat
Aspose.Words.Hyphenation
Aspose.Words.IHyphenationCallback
Aspose.Words.ImportFormatOptions
Aspose.Words.INodeChangingCallback
Aspose.Words.InternableComplexAttr
Aspose.Words.Border
Aspose.Words.Shading
Aspose.Words.TabStopCollection
Aspose.Words.InterruptionToken
Aspose.Words.IWarningCallback
Aspose.Words.LanguagePreferences
Aspose.Words.License
Aspose.Words.ListFormat
Aspose.Words.LoadOptions
Aspose.Words.HtmlLoadOptions
Aspose.Words.RtfLoadOptions
Aspose.Words.TxtLoadOptions
Aspose.Words.Metered
Aspose.Words.Node
Aspose.Words.BookmarkEnd
Aspose.Words.BookmarkStart
Aspose.Words.CommentRangeEnd
Aspose.Words.CommentRangeStart
Aspose.Words.CompositeNode ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.DocumentBase
Aspose.Words.Document
Aspose.Words.InlineStory
Aspose.Words.Comment
Aspose.Words.Footnote
Aspose.Words.Paragraph
Aspose.Words.Section
Aspose.Words.Story
Aspose.Words.Body
Aspose.Words.HeaderFooter
Aspose.Words.EditableRangeEnd
Aspose.Words.EditableRangeStart
Aspose.Words.Inline
Aspose.Words.Run
Aspose.Words.SpecialChar
Aspose.Words.AbsolutePositionTab
Aspose.Words.SubDocument
Aspose.Words.NodeChangingArgs
Aspose.Words.NodeCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.CommentCollection
Aspose.Words.HeaderFooterCollection
Aspose.Words.ParagraphCollection
Aspose.Words.RunCollection
Aspose.Words.SectionCollection
Aspose.Words.NodeImporter
Aspose.Words.NodeList ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Node, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.PageSetup
Aspose.Words.ParagraphFormat
Aspose.Words.PlainTextDocument
Aspose.Words.Range
Aspose.Words.Revision
Aspose.Words.RevisionCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Revision, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.RevisionGroup
Aspose.Words.RevisionGroupCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.RevisionGroup, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.SignatureLineOptions
Aspose.Words.SignOptions
Aspose.Words.Style
Aspose.Words.TableStyle
Aspose.Words.StyleCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.Style, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.TabStop
Aspose.Words.TextColumn
Aspose.Words.TextColumnCollection
Aspose.Words.VariableCollection ---- System.Collections.Generic.IEnumerable`1[[System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Collections.IEnumerable
Aspose.Words.VbaModule
Aspose.Words.VbaModuleCollection ---- System.Collections.Generic.IEnumerable`1[[Aspose.Words.VbaModule, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
Aspose.Words.VbaProject
Aspose.Words.WarningInfo
Aspose.Words.WarningInfoCollection ---- Aspose.Words.IWarningCallback, System.Collections.Generic.IEnumerable`1[[Aspose.Words.WarningInfo, Aspose.Words, Version=19.7.0.0, Culture=neutral, PublicKeyToken=716fcc553a201e56]], System.Collections.IEnumerable
System.Exception ---- System.Runtime.Serialization.ISerializable
Aspose.Words.FileCorruptedException
Aspose.Words.IncorrectPasswordException
Aspose.Words.UnsupportedFileFormatException
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.BorderType
Aspose.Words.BreakType
Aspose.Words.CalendarType
Aspose.Words.ComparisonTargetType
Aspose.Words.ConditionalStyleType
Aspose.Words.ContentDisposition
Aspose.Words.DigitalSignatureType
Aspose.Words.DropCapPosition
Aspose.Words.EditingLanguage
Aspose.Words.EditorType
Aspose.Words.EndnotePosition
Aspose.Words.FindReplaceDirection
Aspose.Words.FootnoteNumberingRule
Aspose.Words.FootnotePosition
Aspose.Words.FootnoteType
Aspose.Words.HeaderFooterType
Aspose.Words.HeightRule
Aspose.Words.HtmlControlType
Aspose.Words.ImportFormatMode
Aspose.Words.LineNumberRestartMode
Aspose.Words.LineSpacingRule
Aspose.Words.LineStyle
Aspose.Words.LoadFormat
Aspose.Words.NodeChangingAction
Aspose.Words.NodeType
Aspose.Words.NumberStyle
Aspose.Words.Orientation
Aspose.Words.OutlineLevel
Aspose.Words.PageBorderAppliesTo
Aspose.Words.PageBorderDistanceFrom
Aspose.Words.PageVerticalAlignment
Aspose.Words.PaperSize
Aspose.Words.ParagraphAlignment
Aspose.Words.ProtectionType
Aspose.Words.RevisionType
Aspose.Words.SaveFormat
Aspose.Words.SectionLayoutMode
Aspose.Words.SectionStart
Aspose.Words.StoryType
Aspose.Words.StyleIdentifier
Aspose.Words.StyleType
Aspose.Words.TabAlignment
Aspose.Words.TabLeader
Aspose.Words.TextDmlEffect
Aspose.Words.TextEffect
Aspose.Words.TextOrientation
Aspose.Words.TextureIndex
Aspose.Words.TxtLeadingSpacesOptions
Aspose.Words.TxtTrailingSpacesOptions
Aspose.Words.Underline
Aspose.Words.VisitorAction
Aspose.Words.WarningSource
Aspose.Words.WarningType

See Also

Aspose.Words Namespace